# Question
Title: How to apply a filter to the screen of a running program?
The idea is to take old games without modifying them, but have the graphics card apply a series of filters to their output before sending them to the monitor. A very crude example would be to take a game that has a resolution of 640x480 and do:

* Increase the resolution to 1280x960
* Apply a blur (low pass filter)
* Apply a sharpen (1 + high pass filter)

These steps may not necessarily be the best to improve the visuals of an old game, but there are a lot of techniques that are well-known in image processing for this purpose.

The question is, do the (NVidia) graphics cards give the ability to load a program that modifies the screen before sending it to the monitor? If so, how are they called and what terminology should I use to search? I would be comfortable with doing the programming myself if this ability is part of a library.

Also, would the solution be different between Windows and Linux? If so, either is fine, since most of the games are probably runnable by `wine`.

# Answer
> 2 votes
This is non-trivial. Your best chance of success will not be by accessing the graphics card directly (unless you like re-writing hardware drivers for ever card you want to support), but rather, the rendering API that does all that for you; DirectX or OpenGL.

You'll need to hook (this is the term you'll want to search with) the API's interface with your own instructions.

https://stackoverflow.com/questions/2649702/c-sharp-hook-overlay-a-directx-game

https://stackoverflow.com/questions/10048333/capture-visual-output-of-a-directx-application-even-in-background

# Answer
> 0 votes
The way I would do this process is create a method that captures an off-screen (as supposed to the main image the user views); this is called page-flipping, then use that image to apply the image manipulation techniques of your programming language of choice (resize, blur and sharpen).

If you perform the aforementioned process with the least number of resources calls to your system, the speed should stay the same as if this image manipulations never happened.

These are the tutorials for what you want to do in Java language:

http://docs.oracle.com/javase/tutorial/2d/images/drawimage.html

(check the running program at the bottom of the page in the previous link)

http://docs.oracle.com/javase/tutorial/extra/fullscreen/doublebuf.html

They might not be useful if you don't write in Java, but the terminology will help you do your research. :)

---
Tags: nvidia, filtering
---


title: Multi-threaded JOGL Problem

text:
# Question
Title: Multi-threaded JOGL Problem
I'm writing a simple OpenGL application in Java that implements the Monte Carlo method for estimating the value of PI. The method is pretty easy. Simply, you draw a circle inside a unit square and then plot random points over the scene. Now, for each point that is inside the circle you increment the counter for in points. After determining for all the random points wither they are inside the circle or not you divide the number of in points over the total number of points you have plotted all multiplied by 4 to get an estimation of PI. It goes something like this PI = (inPoints / totalPoints) * 4. This is because mathematically the ratio of a circle's area to a square's area is PI/4, so when we multiply it by 4 we get PI.

My problem doesn't lie in the algorithm itself; however, I'm having problems trying to plot the points as they are being generated instead of just plotting everything at once when the program finishes executing. I want to give the application a sense of real-time display where the user would see the points as they are being plotted. I'm a beginner at OpenGL and I'm pretty sure there is a multi-threading feature built into it. Non the less, I tried to manually create my own thread. Each worker thread plots one point at a time. Following is the psudo-code:

```
/* this part of the code exists in display() method in MyCanvas.java
which extends GLCanvas and implements GLEventListener */

// main loop
for(int i = 0; i < number_of_points; i++){
    RandomGenerator random = new RandomGenerator();
    float x = random.nextFloat();
    float y = random.nextFloat();
    Thread pointThread = new Thread(new PointThread(x, y));
}

gl.glFlush();

/* this part of the code exists in run() method in
PointThread.java which implements Runnable */
void run(){
    try{
        gl.glPushMatrix();
        gl.glBegin(GL2.GL_POINTS);
            if(pointIsIn)
                gl.glColor3f(1.0f, 0.0f, 0.0f);   // red point
            else
                gl.glColor3f(0.0f, 0.0f, 1.0f);   // blue point
            gl.glVertex3f(x, y, 0.0f);   // coordinates
        gl.glEnd();
        gl.glPopMatrix();
    }catch(Exception e){
    }
}

```

I'm not sure if my approach to solving this issue is correct. I hope you guys can help me out. Thanks.

EDIT:

OK! So I have followed what you have suggested Sven, and instead of using AWT components that would restrict multi-threading, I went on and used GLWindow which is a NEWT context component that wouldn't restrict me from doing so; however, I'm still facing the same issue while dispatching threads. The program seems to wait until all points are determined and then draws everything all at once. Please look into my real code below which is one class called "MonteCarlo" the issue is specifically in the display() method. Put in mind that I'm not really plotting the points right now I'm just printing out hello to the standard output just to test the program.

```
import javax.media.opengl.GL2;
import javax.media.opengl.glu.gl2.GLUgl2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLProfile;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLEventListener;
import com.jogamp.newt.event.WindowAdapter;
import com.jogamp.newt.event.WindowEvent;
import com.jogamp.newt.opengl.GLWindow;
import com.jogamp.opengl.util.FPSAnimator;

import java.util.Random;

public class MonteCarlo implements GLEventListener{
private static final String TITLE = "Monte Carlo Method";
private static final int WINDOW_WIDTH = 400;
private static final int WINDOW_HEIGHT = 400;
private static final int FPS = 60;

private static final float RADIUS = 0.5f;

public MonteCarlo(){
}

@Override
public void init(GLAutoDrawable drawable){
    GL2 gl = drawable.getGL().getGL2();

    gl.glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
    gl.glClearDepth(1.0f);
}

@Override
public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height){
    GL2 gl = drawable.getGL().getGL2();
    GLUgl2 glu = new GLUgl2();

    gl.glViewport(0, 0, width, height);
    gl.glMatrixMode(GL2.GL_PROJECTION);
    gl.glLoadIdentity();
    glu.gluPerspective(53.14f, 1.0f, 1.0f, 100.0f);
    gl.glMatrixMode(GL2.GL_MODELVIEW);
}

@Override
public void display(GLAutoDrawable drawable){
    GL2 gl = drawable.getGL().getGL2();
    GLUgl2 glu = new GLUgl2();

    gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);
    gl.glLoadIdentity();
    glu.gluLookAt(0.5f, 0.5f, 1.0f, 0.5f, 0.5f, -1.0f, 0.0f, 1.0f, 0.0f);

    gl.glPushMatrix();
    gl.glBegin(GL2.GL_LINES);
        gl.glColor3f(0.0f, 0.0f, 0.0f);
        gl.glVertex3f(0.0f, 0.5f, 0.0f);
        gl.glVertex3f(1.0f, 0.5f, 0.0f);
        gl.glVertex3f(0.5f, 0.0f, 0.0f);
        gl.glVertex3f(0.5f, 1.0f, 0.0f);
    gl.glEnd();
    gl.glPopMatrix();

    int in = 0;
    int total = 1000000;
    Random floatRandomGenerator = new Random();
    for(int i = 0; i < total; i++){
        float x = floatRandomGenerator.nextFloat();
        float y = floatRandomGenerator.nextFloat();
        if((Math.pow(x - 0.5, 2) + Math.pow(y - 0.5, 2)) <= Math.pow(RADIUS, 2)){
            in++;
            new Thread(){
                @Override
                public void run(){
                    System.out.println("hello");
                }
            }.start();
        }
    }

    gl.glPushMatrix();
    gl.glPointSize(10.0f);
    gl.glBegin(GL2.GL_POINTS);
        gl.glColor3f(1.0f, 0.0f, 0.0f);
        gl.glVertex3f(0.5f, 0.5f, 0.0f);
        gl.glVertex3f(0.75f, 0.5f, 0.0f);
        gl.glVertex3f(1.0f, 0.5f, 0.0f);
    gl.glEnd();
    gl.glPopMatrix();

    gl.glFlush();
}

@Override
public void dispose(GLAutoDrawable drawable){
}

public static void main(String[] args){
    GLProfile glProfile = GLProfile.getDefault();
    GLCapabilities glCapabilities = new GLCapabilities(glProfile);
    GLWindow glWindow = GLWindow.create(glCapabilities);
    final FPSAnimator fpsAnimator = new FPSAnimator(glWindow, FPS, true);

    glWindow.addWindowListener(new WindowAdapter(){
        @Override
        public void windowDestroyNotify(WindowEvent e){
            new Thread(){
                @Override
                public void run(){
                    fpsAnimator.stop();
                    System.exit(0);
                }
            }.start();
        };
    });

    glWindow.addGLEventListener(new MonteCarlo());
    glWindow.setTitle(TITLE);
    glWindow.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
    glWindow.setVisible(true);

    fpsAnimator.start();
}
}

```

Thank you :)

# Answer
Multithreaded use of *one* OpenGL context is supported by the specs, but one OpenGL context can only be made current by one thread at a time.

To use your pseudo code w/ multiple threads and one drawable target, you want to use shared context, see my answer to a related OpenGL multithreading question.

The shared context would need to be bound to a common drawable, which is a quite different scenario than any use case we have covered so far.

Wade is right here, that it is quite possible to do so by the spec, at least not forbidden :)

However OpenGL driver implementations usually bind the context to one drawable (as it is true w/ Mesa DRI) and locking will be performed.

This is also true w/ JOGL, i.e. we claim the drawable lock when make the context current to ensure that no other thread is using it concurrently.

Using a drawable concurrently usually produce undefined results anyways, as described in the OpenGL spec in regards to FBO (framebuffer objects).

Another OpenGL implementation sideffect is the emulation of fixed function pipeline, i.e. constructs like \- glBegin(..) .. glVertex(..) .. glEnd()

will only \- create an VBO \- send it to the shader and render it at some point in time when it needs to be done (swapBuffer() is the latest point here).

Impact of the above means that your multiple threads will fight at least for the GPU's shader engine, but the impl. also for the drawable lock.

Even if you use OpenCL, which is designed for such a cause, i.e. HPC, your workflow is not suitable, since the data to be processed should be readily available before starting the kernel. Hence OpenGL or OpenCL would make no difference here.

There is one little light at the end of the tunnel though :) If you would use a fragment shader using the noise function (random) and render the circle solely in it - you might get what you are heading at, a GPU accelerated 'estimation'.
> 2 votes

# Answer
You're right that OpenGL is (in theory) multithreadable, and you can use it this way from JOGL. But in practice, if you pick any random platform and driver version, there are sometimes bugs in the multithreading support. So if you want your program to be robust for other users, accessing OpenGL from multiple threads might be more trouble than it's worth.

I'd suggest creating a single rendering thread that owns the GLContext and does all the OpenGL operations. Then have your worker PointThreads push the completed points into a thread-safe collection (e.g. a java.util.concurrent.ConcurrentLinkedQueue) maintained by the rendering thread. The rendering thread can just draw the points as they show up in the queue, or it can transfer them into a vertex buffer for higher-performance rendering.
> 1 votes

---
Tags: multithreading, jogl
---


# Question
Title: Are there any OpenGL ES 2.0 examples for JOGL?
I've scoured the internet for the last few hours looking for an example of how to run even the most basic OpenGL ES 2 example using JOGL but "by Jupiter!" it has been a total fail.

I tried converting the android example from the OpenGL ES 2.0 Programming Guide examples (and at the same time looking at the WebGL example -- which worked fine) yet without any success.

Are there any examples out there?

---

If anyone else wants some extra help regarding this question see this thread on the official Jogamp forum.

# Answer
The book "Guide to Graphics Software Tools" uses JOGL to his examples. There are examples for shaders in GLSL, HLSL and Cg.

**Edited**

In http://www.davidcornette.com/glsl/download.html there are examples with source code. http://www.guyford.co.uk/index.php/forum/14-java-jogl/15-jogl-example-glsl-shader-setup has a bit of code.
> 4 votes

# Answer
Xerxes Ranby contributed a raw ES2 demo, not using any JOGL utilities and is self contained.

Then you can have a look at another simple demo code using some JOGL utilities. Of course, here you would need to check the shader files.
> 2 votes

---
Tags: jogl, opengl-es2
---


title: Music Rhythm Game Difficulty Question

text:
# Question
Title: Music Rhythm Game Difficulty Question
I have curious question about music rhythm based genre while I'm making a code for the game. Is it really better if I set a **random pattern encountered on every music played** or there is **a specific pattern depending on the music and the difficulty**? I have observed the *Guitar Hero 3* game for the game console where the difficulty is set on the number of strings used and possible number of combo (e.g. two-string combo). Compared to the *Tap Tap Revenge* for the Android and iPhone, the difficulty based on the number of BPM (Beat per Minute), meaning, number of targets spawn and must be hit.

# Answer
> 5 votes
Don't use a random pattern, people would like to use their muscle memory to play a song the same every time.

I suggest you define the pattern for the entire song, and give each position a difficulty rating. The most difficult version of the song would include all the difficulties, say 1-5. Where as the medium version of the song would contain all the positions rated 3 or below. While the easiest version of the song would only contain rank 1 positions.

It would likely be easiest and most logical to build up these layers of difficulty from the easiest to hardest. On the first pass of analyzing the song, just get the most radical changes and the strongest beats. Then progress from there, filling in the richness of the song with more positions to be played.

But remember that each level should also contain those before it. This will help the players progress from one difficulty level to the next.

---
Tags: music, balance, difficulty
---


title: Using 2D sprites and 3D models together

text:
# Question
Title: Using 2D sprites and 3D models together
I have gone through a few posts that talks about changing the **GraphicsDevice.BlendState** and **GraphicsDevice.DepthStencilState** (SpriteBatch & Render states). . however even after changing the states .. i cant see my 3D model on the screen.. I see the model for a second before i draw my video in the background. . If i dont play my video then i can see the 3D model ..Here is the code:

```
GraphicsDevice.Clear(Color.AliceBlue);
spriteBatch.Begin();

if (player.State != MediaState.Stopped)
{
    videoTexture = player.GetTexture();
}

Rectangle screen = new Rectangle(GraphicsDevice.Viewport.X, GraphicsDevice.Viewport.Y, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);

// Draw the video, if we have a texture to draw.
if (videoTexture != null)
{
    spriteBatch.Draw(videoTexture, screen, Color.White);

    if (Selected_underwater == true)
    {
        spriteBatch.DrawString(font, "MaxX , MaxY" + maxWidth + "," + maxHeight, new Vector2(400, 10), Color.Red);
        spriteBatch.Draw(kinectRGBVideo, new Rectangle(0, 0, 100, 100), Color.White);
        spriteBatch.Draw(butterfly, handPosition, Color.White);

        foreach (AnimatedSprite a in aSprites)
        {
            a.Draw(spriteBatch);
        }
    }

    if(Selected_planet == true)
    {
        spriteBatch.Draw(kinectRGBVideo, new Rectangle(0, 0, 100, 100), Color.White);
        spriteBatch.Draw(butterfly, handPosition, Color.White);
        spriteBatch.Draw(videoTexture,screen,Color.White);

        GraphicsDevice.BlendState = BlendState.Opaque;
        GraphicsDevice.DepthStencilState = DepthStencilState.Default;
        GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;

        foreach (_3DModel m in Solar)
        {
            m.DrawModel();
        }
    }
    spriteBatch.End();

```

# Answer
> 2 votes
The problem you are having is because `SpriteBatch`, by default<sup>\[1\]</sup>, buffers all rendering until `End` is called.

It's not really a problem with render states. The states you specify in `Begin` (or the default states if you specify nothing) are only set during `End`.

What is happening is that, by calling `End` after drawing your model, **you are rendering all your sprites over the top of your model**.

Just split your rendering into multiple batches, or call `End` earlier (whichever suits) and it should work correctly. Be sure that `Begin`/`End` pairs always match up!

---

\[1\] : Except in `SpriteSortMode.Immediate`, which does everything, well, immediately. It sets states in `Begin` and draws a sprite for each `Draw`. Because of this it can't do batching and so is generally slower.

# Answer
> 2 votes
spriteBatch.Begin();

Defaults to SortMethod.Deferred. You can't change render states in between a begin/end pair unless its SortMethod.Immediate. So the below is not doing anything.

```
GraphicsDevice.BlendState = BlendState.Opaque;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;
GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;

```

The simple fix is to end the spritebatch then call the above code before you render your 3D stuff. Ex:

```
if(Selected_planet == true)
{
    spriteBatch.Draw(kinectRGBVideo, new Rectangle(0, 0, 100, 100), Color.White);
    spriteBatch.Draw(butterfly, handPosition, Color.White);
    spriteBatch.Draw(videoTexture,screen,Color.White);
}

spriteBatch.End();

if(Selected_planet == true)
{
    GraphicsDevice.BlendState = BlendState.Opaque;
    GraphicsDevice.DepthStencilState = DepthStencilState.Default;
    GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;

    foreach (_3DModel m in Solar)
    {
        m.DrawModel();
    }
}

```

---
Tags: xna-4.0
---


title: Turn based battle and formula

text:
# Question
Title: Turn based battle and formula
I'm building a game called DVP(Digimon Virtual Pet), and in this game other than taking care of your digimon, You can also battle and breed them. I'm working on the battle system (making it first cause the actual pet system will be easy compared to the netplay, or 39DLL)but here is the problem I don't want it to be "too" simple or "too" complicated, but I do want to go by a certain formula. There are str, def, spd, and int.

* **Strength**: How hard the attacking digimon is hitting
* **Defense**: How much damage your digimon can defend when being attacked
* **Speed**: The chance of you missing the enemy
* **Intelligence** (battle knowledge): The chance of you hitting a critical hit or defending a critical hit.

I can make a super simple turn based example, but I don't know how exactly to make the formulas for what I've explained above, any help?

# Answer
You can either copy an existing battle system, or create a new one.

1. **Copy**. This is obvious, use Google to find information about some RPG mechanics (e.g. AD&D or Fallout) or play your favorite game and this will be inspiring enough. Problem with this solution is the fact that better systems are more popular and players are more bored with them.
2. **Create**. This is not an easy task. I think no one will give you his virgin system, if it's really good. However, we're not here to keep wisdom to ourselves, so I'll try to give you some guidelines:

* the system should be **easy to learn.** Not necessarily simple, but without steep steps in it's learning curve:

* if you want the system to serve for long amounts of time without boredom, it must be **hard to master** \- that is have a high learning curve on above image (and because it shouldn't be too steep, it must be wide too)
* if you want the system to be casual-friendly, either pair weak players together (using ELO as in chess, or levels like in RPG games) or add a random factor (like in battleships game or systems with dices)
* if you want to avoid a situation, where there's a **specific, best build**, then again make a random factor important, but in a wider scale, e.g. in many RPG games you make a **build together with specific items**, and item drop is random.
* to make the system more rewarding for newbies fighting pros, you may add **stone-paper-scissors** mechanics to some extent - e.g. abilities that counter well other abilities, making it possible for a newbie to get a random opponent he counters well, even if he's not quite understanding game mechanics and is weak in tactics.
* as for the fight itself, **a player shouldn't be able to predict all possible outcomes** of his actions (that would happen in chess with 5 turn and 10 minute limit), but he should have an **intuitive feel of strengths of his moves**. You should balance these two as both extremes: knowing how the fight will end from start (like if in poker other players could see your cards, and there would be no change of the cards) and playing completely random (imagine a single paper-rock-scissors fight with a guy you don't know, through Internet where you can't cheat) aren't fun.

Now, while it's easy to create a complex system that listens to these rules (a lot of abilities well documented by tooltips, etc), it is hard to create a simple system that does:
* it's easy to predict result of actions in a simple system
* You learn mechanics of a simple system pretty fast, and then there's usually not much to learn about strategies.
* Because there are not much factors in a simple system, it's easy to calculate a best possible build

Creating a new system that is both simple and challenging is not an easy task - **you need to be a genius to create something that is 'ingenious in its simplicity'**.
> 11 votes

---
Tags: game-design, turn-based, balance
---


title: Simple (and fast) dices physics

text:
# Question
Title: Simple (and fast) dices physics
I'm programming a throw of 5 dices in Actionscript 3 + AwayPhysics (BulletPhysics port).

I had a lot of fun tweaking frictions, masses etc. and in the end I found best results with more physics ticks per frame. Currently I use 10 ticks per frame (1/60 s) and it's OK, though I see a difference in plus for 20 ticks.

Even though it's only 5 cubes (dices) in a box (or a floor with 3 walls really) I can't simulate 20 ticks in a frame and keep FPS at 60 on a medium-aged PC. That's why I decided to precompute frames for animation, finishing it in around 1700 ticks in 2 seconds. The flash player is freezed for these 2 seconds, and I'm afraid that this result will be more of a 5 seconds or even more, if I'll simulate multi-threading and compute frames in background of some other heavy processes and CPU drawing (dices is only a part of this game).

Because I want both players to see dices roll in same way, I can't compute physics when having free resources, and build a buffer for at least one throw of each type (where type is number of dices thrown). I'm afraid players will see a "preparing dices........." message too often and for too long.

I think the only solution to this problem is replacing PhysicsEngine with something simpler, or creating own physicsEngine. **Do You have any formulas for cube-cube and cube-wall collision detection, and for calculating how their angular and linear velocities should change after a collision occurs?**

Edit: I'm assuming the only way to solve my problem is to make a cube-cube and cube-wall collision engine, however maybe there's another solution for my problem.

* As Arthur pointer out, there can be one animation - for me this is just a shortcut, I could as well show the final result without any dices rolling.
* However, I thought about making 100 precomputed dice throws, though a user won't avoid repetition here as well. Sometimes a dice sits on it's edge (or corner) for a while, and that gives player some excitement (will it fall on 5 and give me a full house?), but with limited number of animations a player would already know how the animation will end.
* Buffering solution would work, if players would see dices roll in different way (results would still be the same) - I'm considering this solution, however I'm still going to try to create a simple physics engine and see how it works.
* less ticks is a solution I don't consider, because at as few ticks to be able to simulate physics in real-time, the dices behave not better than if I treated them as balls in my physics engine...

# Answer
> 1 votes
You could use FlasCC to optimize performance for 3d physics and rendering. Go here: http://gaming.adobe.com/technologies/flascc/

They have an example of flascc with bullet physics. I think using it should increase performance dramatically. Give it a shot.

---
Tags: collision-detection, physics, multiplayer, simulations, collision-resolution
---


# Question
Title: creating a simulation game,  what type of knowledge is needed?
I am a beginner in game development. As a part of learning and fun, want to create a game in java-script and html5. I am planning a game that we were used to play in childhood, that is "new business"- a monopoly game, in that we used to buy ,rent,sell places and bank we get some money to play and etc. are features. Its just simple ludo like game.

So can anyone suggest me from where to start? what will be the designing?

Is it possible to create it only in a html5 and java-script.

# Answer
> 1 votes
That's a very broad question, so I'm not sure there is any right answer.

An equally broad answer: try to make a simple prototype of your game - no fancy graphics and animations or such things, just the core gameplay. Then you test this (maybe let some other people test it as well), and see if that gameplay is fun, what is good and bad about it. Then you improve on that, test again, and repeat this process until you have something that you think will work well as a game.

Then you have two options:

1. The quick&dirty way: take your existing prototype and add graphics, animations, sounds etc. to it. That's quick&dirty in so far as you probably changed your code quite often during the improvement/testing iterations, and it's probably not very clean as a result. But it may be good enough for you.
2. Rewrite your game with all the knowledge you now have about what you want to do and how to do it. Keep everything clean and organized, and in the process also add in graphics and all the other stuff.

That's all I can say until you ask more specific questions.

---
Tags: javascript, html5
---


title: Rotate a vector

text:
# Question
Title: Rotate a vector
I want my first-person camera to smoothly change its viewing direction from direction d1 to direction d2. The latter direction is indicated by a target position t2.

So far I have implemented a rotation that works fine but the speed of the rotation slows down the closer the current direction gets to the desired one. This is what I want to avoid.

Here are the two very simple methods I have written so far:

```
// this method initiates the direction change and sets the parameter
public void LookAt(Vector3 target) {

        _desiredDirection = target - _cameraPosition;
        _desiredDirection.Normalize();

        _rotation = new Matrix();

        _rotationAxis = Vector3.Cross(Direction, _desiredDirection);

        _isLooking = true;
    }

// this method gets execute by the Update()-method if _isLooking flag is up.
private void _lookingAt() {

        dist = Vector3.Distance(Direction, _desiredDirection);

        // check whether the current direction has reached the desired one.
        if (dist >= 0.00001f) {

            _rotationAxis = Vector3.Cross(Direction, _desiredDirection);
            _rotation = Matrix.CreateFromAxisAngle(_rotationAxis, MathHelper.ToRadians(1));

            Direction = Vector3.TransformNormal(Direction, _rotation);
        } else {

            _onDirectionReached();
            _isLooking = false;
        }
    }

```

Again, rotation works fine; camera reaches its desired direction. But the speed is not equal over the course of movement -\> it slows down.

How to achieve a rotation with constant speed ?

# Answer
```
_rotationAxis = Vector3.Cross(Direction, _desiredDirection);
_rotation = Matrix.CreateFromAxisAngle(_rotationAxis, MathHelper.ToRadians(1));

```

As `Direction` & `_desiredDirection` change to be pointing in nearly the same direction (as they converge), The smaller the magnitude of `_rotationAxis` will be. It will still be pointing in the proper direction to be the axis but will be a shorter length. That is the nature of the cross calculation.

The guts of the `CreateFromAxisAngle` method uses the length of the axis as a factor in the amount of rotation it results in. When the axis has a length of 1, it results in the correct amount of rotation.

So if you were to normalize `_rotationAxis` between the two lines I quoted above, you would get a constant rotational rate.
> 3 votes

# Answer
I'd suggest letting the framework do all of the work for you. Start by calculating a rotation matrix for your start and end orientations, and convert them both to quaternions. You only do this *once* at the start of the movement and store the values.

```
Matrix start = /* calculate current rotation matrix */;
Matrix end = /* calculate desired rotation matrix */;
Quaternion startQ = Quaternion.CreateFromRotationMatrix(start);
Quaternion endQ = Quaternion.CreateFromRotationMatrix(end);

```

Now interpolate between these two orientations using spherical linear interpolation. There's a method for it so you don't have to implement anything yourself:

```
// Animate the progress parameter between 0 and 1
Quaternion currentQ = Quaternion.Slerp(startQ, endQ, progress);

```

Finally recalculate your direction using the quaternion above, or convert it back to a rotation matrix. Something like this for instance:

```
Vector3 direction = Vector3.Transform(Vector3.Forward, currentQ);

```
> 6 votes

---
Tags: xna, c#, camera, rotation, vector
---


# Question
Title: Making large scale changes to an economy in a social game
Are there any examples or case studies of social games, specifically on Facebook, where the developer has made drastic changes to the economy? I'm specifically interested in examples where the old economy was based off of purchasing items with Facebook credits then moving to a new model where the same inventory or similar inventory is sold with a soft currency. The closest comparisons I've been able to find so far are looking at iOS games that have gone from purchase models to freemium models, but haven't found a comparable scenario in a social game besides larger scale MMO's.

# Answer
There is a great presentation by Ben Cousins called Playing To Win. On slideshare (with narration) - http://www.slideshare.net/bcousins/paying-to-win

It describes the case of Battlefield Heroes game which was very popular but didn't monetize well and how they redesigned the entire virtual economy ecosystem to make it better. The main changes they did were:

* Giving unfair advantage to weapons (virtual goods) that are purchased with real money.
* Adding a flexible ownership model - allowing both renting and owning
* Increasing the cost of buying/renting with soft currency so that an average user can afford only one item of each category without using real money
* Decrease prices for real money purchases

This is not a facebook game but the same principals apply. In order to optimize and balance your virtual economy ecosystem you need to have at least two currencies and flexible ownership model.
> 6 votes

---
Tags: facebook, monetization, social, economy
---


title: multiplayer networking with physics

text:
# Question
Title: multiplayer networking with physics
I'm curious how multiplayer networking with physics is implemented in racing games. We have a physical world with multiple fast-moving vehicles controlled by different people. Let's say that vehicles have weapons and can shoot each other (Twisted Metal, Vigilante v8)

I'm anxious about hits and collisions. Authoritative server or a better alternative?

# Answer
> 8 votes
Usually, a Server is employed, storing the "truth" state that is periodically shared with the Clients. Collisions happen independently in Clients and Servers, with the states of the Clients estimated from the previous states using a process similar to what it's usually called Dead Reckoning. When a Server state reaches a Client, if there are differences, the Client performs a transition from its current state to the one just received mostly through interpolation.

However, with many objects collisions can be a real issue, therefore what is commonly done is to keep the simulated time of the Clients a bit behind the simulated time of the Server to allow various additional degrees of flexibility. This article about Valve's Source Engine netcode is quite explicative. Also, if you are still undecided about what networking middleware/library to use, I suggest you to look into RakNet and its "ReplicaManager3" component.

# Answer
> 4 votes
There are several things you can do.

1. You can centralize all the physics objects on the server and synch coordinates to the players objects on all clients. This is the easiest and works without many flaws, however it uses a lot of resources and requires lots of bandwidth. You can optimize bandwidth usage by only sending values to the player of other players that are within a certain radius.
2. You can do as Neenster mentioned and have the server and clients simulate physics, every so often the server will correct the clients. This means all clients calculate there own physics for every player, and you would sync keypress events over the server giving the trajectory of each player on every client. Every, lets say, 5 seconds the server broadcasts it's physics simulation and all clients accept the change. This may create slight offsets that are unnoticeable most times, but during network lag and packet loss(inevitable with high traffic UDP) you'll notice your player and/or other players glitching around the screen and changing position rapidly and choppily(is that a word?).
3. You can have each client calculate its own physics and sync its coordinates. This makes it difficult to simulate physics on objects shared between clients. Its a pretty complex concept to implement if you want to do anything snazzy, because certain object don't necessarily belong to any client.

The first is probably the easiest and should allow you to have about 4-5 players with little lag. It would require each match to have it's own server. If you're doing LAN matches this is hands down the way to go.

The second is probably the most practical, however it can be difficult to implement. It also is pretty resourceful to run physics simulations on the server. If you have centralized servers you'd probably need to load balance to several machines, maybe allow 10 matches a server, load new matches to the server with the least matches.

The third is definitely the least stressful on the server, and is probably the best solution if you're doing a peer to peer network scheme. As I mentioned it can be hard to sync objects other than your player object because those objects are alterable by other clients also.

I can't tell you which one to use because I don't know how your game works. All I can do is give you the facts. If you have any further questions feel free to comment.

---
Tags: physics, networking, synchronization
---


title: Client and Server game update speed

text:
# Question
Title: Client and Server game update speed
I am working on a simple two player networked asteroids game using XNA and the Lidgren networking library. For this set up I have a Lidgren server maintaining what I want to be the true state of the game, and the XNA game is the Lidgren client. The client sends key inputs to the server, and the server process the key inputs against game logic, sending back updates. (This seemed like a better idea then sending local positions to the server.) The client also processes the key inputs on its own, so as to not have any visible lag, and then interpolates between the local position and remote position. Based on what I have been reading this is the correct way to smooth out a networked game. The only thing I don’t get is what value to use as the time deltas.

Currently every message the server sends it also sends a delta-time update with it, which is time between the last update. The client then saves this delta time to use for its local position updates, so they can be using roughly the same time deltas to calculate position updates.

I know the XNA game update gets called 60 times a second, so I set my server to update the game state at the same speed. This will probably only work as long as the game is working on a fixed time step and will probably cause problems if I want to change that in the future. The server sends updates to clients on another thread, which runs at 10 updates per second to cut down on bandwidth.

I do not see noticeable lag in movement and over time if no user input is received the local and remote positions converge on each other as they should. I am also not currently calculating for any latency as I am trying to go one step at a time.

So my question is should the XNA client be using its current game time to update the local game state and not being using time deltas sent by the server? If I should be using the clients time delta between updates how do I keep it in-line with how fast the server is updating its game state?

# Answer
The best way to prevent lag in a two person game is to connect them with a peer to peer library. This means that you are using the server to pair users to games but once the arcade mode of the game starts you connect them directly to minimize lag.

Here is a great resource about different multi-player gaming architecture - http://gafferongames.com/networking-for-game-programmers/what-every-programmer-needs-to-know-about-game-networking/

It's important to note however that P2P is not a recommended architecture for games that include more than 2 players. The lag time becomes a factor of the weakest link in the chain and the more links you have the bigger the chances you will have one of the users on a slow connection that slows everyone down.
> 4 votes

---
Tags: xna, networking
---


# Question
Title: Best practices on separating Update and Draw on game loop
I've been working on my first HTML5 prototype and I found a good model that uses the regular Update and Draw loop we see in game dev. My question is, where does one end and the other begins?

The question popped when I wanted to rotate and draw an Image, and I kept wondering if the work of changing the tranformation matrix (that I presume would be a bit expensive since it works on the whole pixel array of an image) and calculating the right position do draw it would characterize drawing work, or maybe not, since after that I may need to check for collision or something similar.

Thinkig of it, seems like a silly question, but I would like some advice from more experienced developers. Where does does update ends and draw starts?

Thanks in advance.

# Answer
In your case you'd move around game objects based on their velocity, do collision detection and handling, and only then you'd render the game objects with their new positions and rotations.

* During the *update phase* you change your game state, amongst others calculating new positions and rotations for your game objects based on user input, gameplay rules and physics.
* The *draw phase* should only be about creating a view (like a snapshot) of your current game state. In this phase the game state shouldn't be modified anymore so as to create a consistent image.

*Side note:* The transformation matrix should be separate from your sprite's pixels. Updating it with a 2D-translation can be as cheap as 2 additions. If this doesn't make sense read up a little more or even ask a new question about it.
> 7 votes

# Answer
Determining (calculating) the transformation of the entire image is usually considered update work. You calculate it only once per frame and pass it on to the GPU however your API allows you to. The passing of that transformation to the GPU is considered part of the Draw work.

The GPU then does all heavy lifting (applying the transformation to every pixel) to make sure the pixels get lit correctly. Since the GPU can operate on many pixels at the same time (parallel processing), it happens very fast.

Also, it doesn't actually transform each pixel. Behind the scenes, it creates 2 triangles that merge to form a quad the dimensions of your image. The transformation is only applied to the 6 triangle points (vertices). the color of each pixel inside the triangle can be determined by interpolating the info contained in the 3 points instead of transforming each pixel.
> 4 votes

# Answer
A good rule of thumb of thumb is to imagine that you're doing a blind replay. That is, say you have a recording of player actions from a past game, and you want to find out how the player scored by replaying that game, but you only care about the outcome — there's nobody there to look at the game as it (re)plays.

**Anything you need to do to figure out how the game ends belongs in the update phase.** Anything you can safely skip in a blind replay belongs in the draw phase. Generally, you want to do as little work as possible during the update phase, so anything that can be moved from the update phase to the draw phase usually should be.

This way, you'll (hopefully) end up with a clean separation of update and draw logic.

That said, it should be noted that there are some perfectly valid techniques that can muddle the distinction: for example, classic 8-bit 2D games often use(d) pixel-by-pixel sprite collision detection (often done at least partially in hardware), which ties sprite rendering (drawing) and collision detection (update) all but inextricably together. If you use such techniques, you'll just have to accept that you'll have a combined update-and-draw phase, or at least that your update phase will include some things that are really more about drawing, but which need to be in the update phase because they affect game logic.
> 4 votes

---
Tags: html5, game-loop
---


title: Data structure for bubble shooter game

text:
# Question
Title: Data structure for bubble shooter game
I'm starting to make a bubble shooter game for a mobile OS. Assume this is just the basic "three or more same-color bubbles that touch pop" and all bubbles that are separated from their group fall/pop. **What data structures are common for storing the bubbles?**

I've considered using an undirected, connected graph where each node is a bubble. This seems like it could help answer the question "which bubbles (if any) should fall now?" after some arbitrary bubbles are popped and corresponding nodes are removed from the graph. I think the answer is all bubbles that were just disconnected from the graph should fall. However the graph approach might be overkill so I'm not sure.

Another consideration for the data structure is collision detection. Perhaps being able to grab a list of neighboring bubbles in constant time for a particular "bubble slot" is useful. So the collision detection would be something like "moving bubble is closest to slot ij, neighbors of slot ij are bubbles a,b,c, moving bubble is sufficiently close to bubble b hence moving bubble should come to rest in slot ij".

A game like this could be probably be made with a relatively crude grid structure as the primary data structure. However it seems like answering "which bubbles (if any) should fall now?" would be trickier with this data structure.

# Answer
Finding connectivity in a general graph is usually done with floodfill-style algorithms (i.e., breadth- or depth- first search and variants thereof) anyway, so I don't think that abstracting out the process in the way you're describing is actually any great help. Instead I would maintain the core data structure in a grid; there are very standard approaches for storing hex grids (which is what the bubble grid amounts to - imagine 'inflating' the bubbles until the gaps between them fill in) in rectangular 2d arrays that are directly applicable here. (And I can fill in more details on the specific grid structure here if you need them, certainly.)

The one small 'catch' is that you probably want to initialize your flood fill/search structure by adding all nodes adjacent to the top or walls to your 'to be processed' queue; this is likely to be quicker and more straightforward than flood-filling from each of the connected bubbles in turn. Regardless of how you do it, though, the connectivity pass should be so fast (you're iterating over probably not more than 100 items!) that doing anything too complex with it smacks of premature optimization; this just shouldn't be a huge part of your frame time.
> 2 votes

# Answer
Using a simple 2D array works. Then you don't have to walk a graph to get somewhere. Deciding what should fall next is as easy iterating up the current "column" of the array you're in.

You can easily step into the grid anywhere with the x/y coordinates and do your collision detection or whatever you need to. That means you can get neighbors in constant time.

If you need to know which bubbles should fall next it's as easy as starting at the bottom and iterating up, finding the first empty slot, and moving things down.
> 2 votes

---
Tags: algorithm, data-structure, graph
---


title: Lua GameDev iOS - Code on win and mac

text:
# Question
Title: Lua GameDev iOS - Code on win and mac
I am searching for a simple framework like http://getmoai.com where you can simply code a game in lua for iOS. I want to build it along with a friend. I am using a Mac, he prefers windows so the fw needs to be used in Windows 7. Preferably something like LOVE2D but then offcourse also for iOS!

Thanks in advance

# Answer
> 1 votes
I recently fell in love with the Gideros Mobile framework, works on both Mac and Windows, also its supposed to be working under Linux if you use wine.

Possible LUA mobile frameworks:

* Moai (open-source and thus free)
* Corona SDK ($199 per platform)
* Gideros Mobile (Free with Gideros splash screen, $149 to remove splash screen)

I looked and downloaded Moai, but its not very straightforward about how to use it, read a lot of documentation, but felt like I was still far of from starting. Could be just me.

Played around with Corona SDK, also looks pretty good, but a after reading this article I decided to go for Gideros.

**Gideros**:
Gideros comes with a IDE and I was up and running in no time.
The good thing about Gideros is it works with a player over network, you can instantly see the results on your mobile device or local player, but with the player on the device its very easy to test the accelerometer and how the touch is responding as if it was a ready build app. Leading to very fast feedback.

The Android player is distributed with the SDK, the iOS player needs to be build manually in Xcode and needs a Apple developer account.

Also note the Gideros forums are great place for examples and discussions, the developers are active on the forums and the response has been really great and fast. It feels like a great community.

# Answer
> 0 votes
I do just that C++ dev on Windows and Mac for Mac, Windows, iOS and Android. The solution is to use C++ and work with a middleware integrating multiple cross-platform libraries. This way I am able to compile the same project for iOS on mac and for a custom emulator on Windows.

Unity is a good framework which allows you to share code and resources across multiple platforms. If you want something that works out of the box it would be wise to have a look at that.

Writing such a middleware is possible. If you are two working together you can push forward quickly a prototype. You simply have to write your code for one platform once, then write your own interface and move all the platform specific code to dedicated files/libs.

It's what I have currently. The only down side is that my compile chain does not currently support compiling for iOS from Visual Studio yet.

---
Tags: ios, lua
---


title: Toggle Fullscreen at Runtime

text:
# Question
Title: Toggle Fullscreen at Runtime
Using the library GLFW, I can create a fullscreen window using this line of code.

```
glfwOpenWindow(Width, Height, 8, 8, 8, 8, 24, 0, GLFW_FULLSCREEN);

```

The line for creating a standard window looks like this.

```
glfwOpenWindow(Width, Height, 8, 8, 8, 8, 24, 0, GLFW_WINDOW);

```

What I want to do is letting the user switch between standard window and fullscreen by a keypress, let's say `F11`.

**It there a common practice of toggling fullscreen mode? What do I have to consider?**

# Answer
> 8 votes
I'm not sure about common practices, but lacking a `glfwToggleFullscreen`, this seems one way to toggle *fullscreen* mode:

```
// On input handling, check if F11 is down.
if ( glfwGetKey( GLFW_KEY_F11 ) ) {

    // Toggle fullscreen flag.
    fullscreen = !fullscreen;

    // Close the current window.
    glfwCloseWindow();

    // Renew calls to glfwOpenWindowHint.
    // (Hints get reset after the call to glfwOpenWindow.)
    myGLFWOpenWindowHints();

    // Create the new window.
    glfwOpenWindow(Width, Height, 8, 8, 8, 8, 24, 0,
                   fullscreen ? GLFW_FULLSCREEN : GLFW_WINDOW);

}

```

Another method, this time for *fullscreen windowed* mode:

```
// Create your window in windowed mode.
glfwOpenWindow(originalWidth, originalHeight, 8, 8, 8, 8, 24, 0, GLFW_WINDOW);
glfwSetWindowPos(originalPosX, originalPosY);

// Get the desktop resolution.
GLFWvidmode desktopMode;
glfwGetDesktopMode(&desktopMode);
desktopHeight = desktopMode.Height;
desktopWidth = desktopMode.Width;

// --8<--

// On input handling, check if F11 is down.
if ( glfwGetKey( GLFW_KEY_F11 ) ) {
    // Toggle fullscreen flag.
    fullscreen = !fullscreen;

    if ( fullscreen ) {
        // Set window size for "fullscreen windowed" mode to the desktop resolution.
        glfwSetWindowSize(desktopWidth, desktopHeight);
        // Move window to the upper left corner.
        glfwSetWindowPos(0, 0);
    } else {
        // Use start-up values for "windowed" mode.
        glfwSetWindowSize(originalWidth, originalHeight);
        glfwSetWindowPos(originalPosX, originalPosY);
    }
}

```

# Answer
> 1 votes
I'd suggest looking at the implementation of SFML, which fluently switches between fullscreen and windowed on Windows, Mac and Linux. SFAIK it doesn't use GLFW, but perhaps similar principles apply.

---
Tags: c++, opengl, glfw
---


title: Sprite Animation Toolkits for iPhone

text:
# Question
Title: Sprite Animation Toolkits for iPhone
Does anyone know of any good (and preferably **free**) Sprite Animation Toolkits/Libraries for iOS development?

This library should be able to handle the collision detection and the movement of the sprites. Back in the 90's there was a Pascal library called Sprite Animation Toolkit by Ingemar Ragnemalm that handled a lot of the heft to create animations and the such. I am just wondering if there is anything like that in the iOS world?

# Answer
* Cocos2d-iphone is a great open source framework for iOS
* Cocos2d-x will give you automatic porting for Android so you might want to check it as well
* Both are based on Open GL which is another open source graphic library
* Box2d is also a great open source resource for 2d graphics
> 2 votes

# Answer
While it's not specifically a sprite animation library, is Cocos 2d any use to you? You can also look at the source which might help you create a sprite animation library of your own.
> 0 votes

---
Tags: ios
---


# Question
Title: Handling player logoff and logon in a persistent world without breaking immersion
One problem I've never seen fixed in any persistent online game is how to handle player logon and logoff without the characters just popping in and out of the world. My first thought is to simply make a player's offline state as their character being asleep, but that doesn't make sense in the event of a disconnect and not an intentional logoff.

How would you fix this, if you would even bother fixing it at all?

# Answer
> 14 votes
You wouldn't bother.

> Immersion (wiki) :
>
> The state of consciousness where an immersant's awareness of physical self is diminished or lost by being surrounded in an engrossing total environment.

This term is often used in the wrong way ; people think that good graphics makes a game more *immersive*, or that a real physics simulation will do the same.

This is wrong, the biggest immersion breaker is incoherences in the world in which the player is. Like the physics engine messing up and sending random things flying, or a stupidly low res NPC. Something that is really immersion breaking (at least for me) is game rules being broken or frustration.

Once the player has made a conscious descision to join/leave the world they accept that they are entering/leaving the game world. Not breaking immersion would be solving any disconnection problems and, failing that, make it less frustrating for the player so they can pop straight back into the action. You could also consider that those who are playing *with* a player that gets d/c'd have their immersion broken because the guy just dissapears.

Of course the immersion of those staying in the game is momentarily 'fissured' because someone just dissapears. But even if you found some fancy animation, people would still know that the player was logging out. Some people may even get a chat message to say their friend has left the game - logging out is just an accepted part of the game.

# Answer
> 30 votes
The way one would deal with this would depend on the game and what would make sense for that world. For example a sci-fi game, they could "beam up" to some space storage facility for cryo-sleep. A fantasy game could have them cast a spell on them self to fade away. Or they could be sucked into a portal. Make them turn really small and a bird or robot comes and picks them up to take them away.

Essentially, you just need to do something other than just making them disappear/appear. Have some animation associated with it, and perhaps some vague explanation of where they came from/went to in local chat.

For accidental disconnections you can have a malfunctioning version of the log off. Like the player character sneezes and says oops before they fall into a portal. Where the log will explain they accidentally cast such and such spell on themselves or accidentally hit their cryo-sleep button.

If you were thinking "why bother, people will know that other people are logging out anyway", I say apply that logic to any other part of the game experience. Why make that tree look more like a tree instead of a trunk with billboard leaves? People already know it's a tree right? Because it completes the experience. We can't fool people into thinking they're not playing a game (yet). People will know that the other player logged out. The reason to do it is to improve and complete the experience. Especially in this scenario where the effort is truly minimal. Adding an animation and/or in-game explanation for where the character went is fairly easy.

# Answer
> 10 votes
The coolest solution for this that I have heard about is how Neal Stephenson envisages how it could work in his book Reamde.

Every character has a fairly intelligent auto-pilot. If your character is a fighter and you log off/loose connection, your character will spend its time training martial skills, eating, sleeping and so on. If your character is a miner, it will spend its time mining for minerals and so on.

The auto-pilot will not be as efficient as if you were logged in yourself, so there is always a reward for logging in and actually controlling your character (especially since they will also not defend themselves as efficiently when you are not logged in).

Neat idea but will probably require quite a bit of work on the character AI in order to get it working as intended.

# Answer
> 7 votes
Some of the old DIKU muds had a system called 'rent'. Your character only saved if you went to an Inn to log out, and payed enough rent to cover the cost of keeping your gear. It might seem a bit punitive to modern players but it had the effect of making characters appear to go to inns and sleep when they were out of the game, which keeps with the fiction.

# Answer
> 6 votes
You could use any existing in-game mechanic that allows for fast travel to avoid breaking immersion. What exactly this would be depends of course heavily on the specific game and genre.

As an example, in EVE Online if you disconnect while in space, your ship automatically warps to a random spot in the solar system and dissappears after a while. Warping is the usual way of traveling inside a solar system, and the emergency warp you enter when disconnecting is subject to exactly the same restrictions as a player-initiated warp (e.g. you can be prevented from warping by certain disruption mechanics).

# Answer
> 4 votes
I think any of the answers that suggest some kind of animation that indicates that someone is logging out are, essentially, not very good ideas to implement. If you assign specific animations to these two actions (logging in/logging out), players would quickly pick it up, and it would only **distract** them from the game and make them aware they are just playing in a virtual world from which it is **possible** to disconnect. This is the very definition of immersion-breaking.

The correct way of doing this, in my opinion, would be the most subtle one. Blizzard solved this magnificently: players simply fade away. It is uninteresting, not distracting, and barely noticeable.

---
Tags: game-design, multiplayer, rpg, online
---


title: Settings object with singleton pattern

text:
# Question
Title: Settings object with singleton pattern
I need to build an object that will have only one instance because this Object is dedicated to the storage of vital settings for my application and I would like to avoid a misuse of this type or a conflict at run-time.

The most popular solution for this, according to *the internet*, is the Singleton pattern. But I would like to know about other ideas or solutions for this; also I would like to know if other solutions can be much more easy to grasp for an user of this hypothetical library.

Thanks.

# Answer
> 3 votes
You generally will have some other globally unique object, like an Engie or Applicaion instance. Storing settings on that (in a member object for example) is totally viable.

It's in many ways the same as any other singleton, except now you have a single point of initialization and cleanup rather than tons of them for different singletons.

I've also seen fully component based engines where even the engine is composed of runtime components, and one or more configuration oriented components can be added there.

---
Tags: c++, design-patterns, data
---


title: XNA RTS A* pathfinding issues

text:
# Question
Title: XNA RTS A* pathfinding issues
I'm starting to develop an RTS game using the XNA framework in C# and am still in the very early prototyping stage. I'm working on the basics. I've got unit selection down and am currently working on moving multiple units. I've implemented an A\* pathfinding algorithm which works fine for moving a single unit. However when moving multiple units they stack on top of each other. I tried fixing this with a variation of the boids flocking algorithm but this has caused units to sometimes freeze and get stuck trying to move but going no where.

Ill post the related methods for moving the units below but ill only post a link to the pathfinding class because its really long and i don't want to clutter up the page.

These parts of the code are in the update method for the main controlling class:

```
if (selectedUnits.Count > 0)
            {
                int indexOfLeader = 0;
                for (int i = 0; i < selectedUnits.Count; i++)
                {
                    if (i == 0)
                    {
                        indexOfLeader = 0;
                    }
                    else
                    {
                        if (Vector2.Distance(selectedUnits[i].position, destination) < Vector2.Distance(selectedUnits[indexOfLeader].position, destination))
                            indexOfLeader = i;
                    }
                    selectedUnits[i].leader = false;
                }
                selectedUnits[indexOfLeader].leader = true;

                foreach (Unit unit in selectedUnits)
                    unit.FindPath(destination);
            }

foreach (Unit unit in units)
        {
            unit.Update(gameTime, selectedUnits);
        }

```

These three methods control movement in the Unit class:

```
public void FindPath(Vector2 destination)
    {
        if (path != null)
            path.Clear();

        Point startPoint = new Point((int)position.X / 32, (int)position.Y / 32);
        Point endPoint = new Point((int)destination.X / 32, (int)destination.Y / 32);

        path = pathfinder.FindPath(startPoint, endPoint);
        pointCounter = 0;
        if (path != null)
            nextPoint = path[pointCounter];

        dX = 0.0f;
        dY = 0.0f;

        stop = false;
    }

private void Move(List<Unit> units)
    {
        if (nextPoint == position && !stop)
        {
            pointCounter++;
            if (pointCounter <= path.Count - 1)
            {
                nextPoint = path[pointCounter];
                if (nextPoint == position)
                    stop = true;
            }
            else if (pointCounter >= path.Count)
            {
                path.Clear();
                pointCounter = 0;
                stop = true;
            }
        }
        else
        {
            if (!stop)
            {
                map.occupiedPoints.Remove(this);

                Flock(units);

                // Move in X ********* TOOK OUT SPEED **********
                if ((int)nextPoint.X > (int)position.X)
                {
                    position.X += dX;
                }
                else if ((int)nextPoint.X < (int)position.X)
                {
                    position.X -= dX;
                }

                // Move in Y
                if ((int)nextPoint.Y > (int)position.Y)
                {
                    position.Y += dY;
                }
                else if ((int)nextPoint.Y < (int)position.Y)
                {
                    position.Y -= dY;
                }

                if (position == nextPoint && pointCounter >= path.Count - 1)
                    stop = true;

                map.occupiedPoints.Add(this, position);
            }

            if (stop)
            {
                path.Clear();
                pointCounter = 0;
            }

        }
    }

private void Flock(List<Unit> units)
    {
        float distanceToNextPoint = Vector2.Distance(position, nextPoint);
        foreach (Unit unit in units)
        {
            float distance = Vector2.Distance(position, unit.position);
            if (unit != this)
            {
                if (distance < space && !leader && (nextPoint != position))
                {
                    // create space
                    dX += (position.X - unit.position.X) * 0.1f;
                    dY += (position.Y - unit.position.Y) * 0.1f;

                    if (dX > .05f)
                        nextPoint.X = nextPoint.X - dX;
                    else if (dX < -.05f)
                        nextPoint.X = nextPoint.X + dX;

                    if (dY > .05f)
                        nextPoint.Y = nextPoint.Y - dY;
                    else if (dY < -.05f)
                        nextPoint.Y = nextPoint.Y + dY;

                    if ((dX < .05f && dX > -.05f) && (dY < .05f && dY > -.05f))
                        stop = true;

                    path[pointCounter] = nextPoint;

                    Console.WriteLine("Make Space: " + dX + ", " + dY);
                }
                else if (nextPoint != position && !stop)
                {
                    dX = speed;
                    dY = speed;
                    Console.WriteLine(dX + ", " + dY);
                }
            }
        }
    }

```

And here's the link to the pathfinder: https://docs.google.com/open?id=0B\_Cqt6txUDkddU40QXBMeTR1djA

I hope this post wasn't too long. Also please excuse the messiness of the code. As I said before this is early prototyping. Any help would be appreciated. Thanks!

# Answer
You're over-complicating things. Just do some basic collision detection to make sure units don't overlap.
> 1 votes

# Answer
All right ,I didn't look very deeply to your code, however If for one unit you got it working, maybe you can try this: In order to make the group travel to the next point select the unit of the group which is closer to it and make it go. Then put every unit following that one, but only let a unit move until the place it will be in the next iteration has no one in a radius equal to the radius of the unit.

I'm sorry if this doesn't make sense in terms of how you're doing things.
> 0 votes

# Answer
I'm not sure this is answering your question, but by one of your comments, I am guessing you need to implement proper collision detection and resolution first. When coliding with another unit, the unit should not return to the space it was occupying before. It should rather move as far along the direction it wants to go as possible.
> 0 votes

---
Tags: xna, c#, path-finding, rts
---


# Question
Title: Getting a texture from a renderbuffer in OpenGL?
I've got a renderbuffer (DepthStencil) in an FBO and I need to get a texture from it. I can't have both a DepthComponent texture and a DepthStencil renderbuffer in the FBO, it seems, so I need some way to convert the renderbuffer to a DepthComponent texture after I'm done with it for use later down the pipeline.

I've tried plenty of techniques to grab the depth component from the renderbuffer for weeks but I always come out with junk. All I want at the end is the same texture I'd get from an FBO if I wasn't using a renderbuffer. Can anyone post some comprehensive instructions or code that covers this seemingly simple operation?

EDIT:

Linky to an extract version of the code http://dl.dropbox.com/u/9279501/fbo.cs

Screeny of the Depth of Field effect + FBO - without depth(!) https://i.stack.imgur.com/Hj9Oe.jpg

Screeny without Depth of Field effect + FBO - depth working fine https://i.stack.imgur.com/boOm1.jpg

# Answer
Alternately, you can just blit from one FBO to another, such as from a renderbuffer-based one to a texture-based one. I do it this way:

```
glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, m_renderBufferSurface->m_fbo);
glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, m_textureSurface->m_fbo);
glBlitFramebufferEXT(0, 0, m_renderBufferSurface->m_width, m_renderBufferSurface->m_height, 0, 0, m_textureSurface->m_width, m_textureSurface->m_height, GL_COLOR_BUFFER_BIT, GL_NEAREST);

```

(In your case, where you want to depth buffer, you can use GL\_DEPTH\_BUFFER\_BIT instead of GL\_COLOR\_BUFFER\_BIT)

After blitting into the texture-based renderbuffer, you can then use the texture as normal; passing it into shaders as a uniform or whatever you like.
> 2 votes

# Answer
No, that's not possible. At most you can glReadPixels the data to the CPU, and create a texture of it, but that will be cumbersome and slow. Renderbuffers aren't meant for it, that functionality is only provided by textures.
> 1 votes

# Answer
What you are asking is possible in OpenGL 3.2. I've got my FBO spitting out diffuse colour to a colour texture, normals to another colour texture, and depth to a depth texture -- no renderbuffers needed. In fact renderbuffers are just a problem, because you cannot sample from them, so you'd have to use `glReadPixels(...)` or otherwise somehow copy the data out of the RBO and into a texture on the CPU, instead of just maintaining everything in GPU memory. So...

If you really want to, you can write code in your first-pass shader to manually output stuff like depth, to a separate colour texture attachment in your FBO. That would be for use by *you* in your post-pass shaders. For *OpenGL's* use in its internal depth-testing, you would additionally need either an RBO or texture set as your FBO's GL\_DEPTH\_ATTACHMENT. But you can set up a single texture to serve *both* -- this is more efficient & easier to use.

My depth texture setup code looks like this (Java, just ignore the ByteBuffer stuff... and note I use "id" to refer to integer handles/pointers, since that concept doesn't really sit well in Java):

```
        gBufferDepthTexture = new Texture();
        gBufferDepthTexture.id = glGenTextures();
        gBufferDepthTexture.unit = 2;
        gBufferDepthTexture.width = Display.getWidth();
        gBufferDepthTexture.height = Display.getHeight();
        gBufferDepthTexture.bytes = ByteBuffer.allocateDirect(Display.getWidth()*Display.getHeight() * 4);
        glActiveTexture(gBufferDepthTexture.unit + GL_TEXTURE0); //eg. 0 + 33984 = GL_TEXTURE0, while 31 + 33984 = GL_TEXTURE31.
        glBindTexture(GL_TEXTURE_2D, gBufferDepthTexture.id);

        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, gBufferDepthTexture.width, gBufferDepthTexture.height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, gBufferDepthTexture.bytes);
        //...GL_UNSIGNED_INT or GL_UNSIGNED_BYTE may work better for you, instead... YMMV.

        //glPixelStorei(GL_PACK_ALIGNMENT, 4);
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

```

And later:

```
        glBindFrameBuffer(GL_DRAW_FRAMEBUFFER, fbo.id);
        //your existing glFramebufferTexture2D(...) calls here
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, gBufferDepthTexture.id, 0);

```

You can now pass `gBufferDepthTexture` (or what have you) as a uniform to your second, third pass fragment shaders. I think we can safely assume that you can do exactly the same thing with the stencil buffer.
> 1 votes

# Answer
You should be able to create a texture (instead of a RenderBuffer) using the GL\_DEPTH\_STENCIL format. I'm not sure of the exact process for using depth from such a texture in a shader program (which I assume you're using, since you're using FBOs), but the OpenGL spec should specify which color channels get which values (my guess would be that R,G, and B all get set to depth and A gets set to stencil).

I target OpenGL 3.2 these days, so you may need to verify that texture format is workable for you. I can never remember which versions introduce different features.
> 0 votes

---
Tags: opengl
---


# Question
Title: The reasons behind Unity3D engine design (game object/transform component)
I'm trying to understand the reasoning behind Unity3D engine design and this is something I can't get my head around yet: **why is transform data stored in a separate component, instead of being a part of GameObject, like name, layer masks and tags?** It cannot be removed like all of the other components anyway, there are no alternatives and thus no need for it to be removed.

# Answer
Only the Unity developers can give their true motivation for this design, but one argument in support of doing it this way is that there is an argument that each class in a software project should handle one and only one responsibility. The GameObject is a named collection of Components, and adding position/rotation/etc to that means it would have 2 responsibilities. The Transform component handles position and rotation and therefore shouldn't also be responsible for naming or aggregating other (potentially unrelated) components. So it makes sense for these 2 concepts to exist in 2 separate objects.

More generally, this question asks *"if there is a 1 to 1 relationship between X and Y, why is Y not part of X or vice versa?"* And the general answer is that software is easier to develop and maintain when broken up into smaller self-contained parts, even if 2 parts always work together in conjunction.
> 11 votes

# Answer
Transform is a mandatory component in Unity.

The reason why a transform is a mandatory component is that game objects are located in a scene and therefor needs spatial information (position, orientation and scale) about that object. (This information is not always used, but keeping the transform component mandatory keeps things a bit more simple).
> 1 votes

# Answer
The `TransformComponent` is the most difficult `Component` to properly design in video game architecture. Almost every other `Component` needs to know about a given `GameObject`'s position, rotation, or scale, so properly decoupling all of these interrelated systems is inherently difficult.

There will always be tradeoffs in architecture. By having `TransformComponent` be static (i.e. not dynamic), developers at Unity can write code under this assumption. I would assume this makes things much easier on their side without adding much of an inconvenience on our side. This is akin to an object-oriented paradigm, where `GameObject` would `extend` some `abstract class`, `Transformable`.
> 0 votes

---
Tags: architecture, unity, component-based
---


# Question
Title: How do I detect collision between movie clips?
I know there are some methods you can use, like `hittestPoint` and so on, but I want to see where my movie clip collides with another another movie clip. Are there any other methods I can use?

I have had trouble finding a good introduction to game physics, and I would like to know how to something like this, properly.

# Answer
"I want to see where my movieclip colliedes with another another movieclip."

Actionscript offers pixel perfect collision detection between bitmapData objects. It does not offer straight out of the box a tool to detect the exact points where the two objects overlap.

How to detect where two objects are 'touching' on another?

1. Create two bitmapData objects and .draw() the movieclips, each one to a separate bitmapData object using the \`.draw() function. only needs to be done once unless you rotate or scale the movie clips later)
2. Create 2 `Vector(typed array) of type Point` and trace the outline of the bitmap data objects. Do this by running in a loop over all pixels in the bitmapData. If a pixel's alpha is 0 or low enough to be invisible to the eye and it is next to a visible pixel, add it to the vector as point of the pixel position in (x,y).
3. Check if there is a collision between the mc's rectangles. If not, stop.
4. Check if there is a pixel perfect collision between the bitmapData objects using the API bitmapData.hitTest() and if not, stop.
5. Create a 2d-vector of type Boolean. Trace the first outline into the 2-vector. Now run over the points in the second outline. If any of them is already 'true' it means the two outlines collide in that point. You can return all points that meet this condition as a result for the function.

Here are two sample shapes.

Trace their outlines into two separate point vectors in advance.

If there was no collision between their containing rectangles, we could stop here and save processing time.

Time to check pixel perfect and outlines.
> 4 votes

# Answer
There are several ways to detect a colision in AS3, and you have to choose the one that fits better with your needs.

ActionScript3 provides two native methods for testing colisions:

* obj1.**hitTestObject**( obj2 );

This function will return true if the **bounds** of the objects are colliding. Be careful, this will cause fake colisions if you are using shapes like circles, because the function will test the area of the shapes, not the pixels.

* obj1.**hitTestPoint**( obj2.x, obj2.y, true );

This function will return true if a coordinate colides with the shape of an object. Be careful you can only test one point, you may want to determine several points of colision in a shape, then test all of them to a better result.

Of course these are only natives functions, if you want to save you some time, you can import and use a colision kit. They can be very useful, since they have a lot of features and examples. A good one can be found here.

---

About your other question, tonypa have a great tutorial about vectors, that can be very useful when developing phisic games. The tutorials are written in AS3, and provides a lot of graphics representations. These can be found here.

If you do not want to write the full code, you can learn how to use boxD2, that provides a full environment whith phisics. But maybe you will want to learn some theory before using a phisic library.

Good luck in your studies.
> 2 votes

# Answer
Jery, the truth is that structuring code is a function of the developer's understanding of the concept at hand (in your case, collision detection and physics). If you don't really understand the concepts, your code will be a mess.

So, better-structured code comes with an improved understanding of the problem. That means you will have to do your own research. This site, gpwiki.org, gamedev.net, are all worthwhile sources, among countless others, especially (I find) devblogs. When it comes to anything new and advanced like a particular AI technique, entity-component systems, collision detection, physics, 3D to name just a few -- you are going to have to take the initiative to do a bit of your own research.

Just don't be intimidated. Look at a lot of sources. If one source doesn't make sense, don't waste much time, move onto another. Good sources are hard to find, and maybe that's what you're asking for here, but I will tell you that looking through many sources leads to a broader understanding and capability, as you piece together the puzzle that is that particular concept. Mastery doesn't come from a single source. And finding the right sources is a major skill in itself, for any developer.
> 0 votes

---
Tags: collision-detection, physics, actionscript-3
---


# Question
Title: How do I make a rope from point A to B in Box2D?
I need to make a rope (preferably not elastic) from one point to the next in Box2D. If it helps, I'm trying to develop one of those 2D Spiderman games, like this: http://www.gamesbutler.com/game/4327/Hanger/

# Answer
> 1 votes
Look in the Box2D manual for `b2EdgeChainDef`. Simply restrict the parameters so that there is no elasticity per edge/joint.

---
Tags: 2d, box2d
---


# Question
Title: How can I achieve a 3D-like effect with spritebatch's rotation and scale parameters
I'm working on a 2d game with a top-down perspective similar to Secret of Mana and the 2D Final Fantasy games, with one big difference being that it's an action rpg using a 3-dimensional physics engine.

I'm trying to draw an aimer graphic (basically an arrow) at my characters' feet when they're aiming a ranged weapon. At first I just converted the character's aim vector to radians and passed that into spritebatch, but there was a problem. The position of every object in my world is scaled for perspective when it's drawn to the screen. So if the physics engine coordinates are (1, 0, 1), the screen coords are actually (1, .707) -- the Y and Z axis are scaled by a perspective factor of .707 and then added together to get the screen coordinates.

This meant that the direction the aimer graphic pointed (thanks to its rotation value passed into spritebatch) didn't match up with the direction the projectile actually traveled over time. Things looked fine when the characters fired left, right, up, or down, but if you fired on a diagonal the perspective of the physics engine didn't match with the simplistic way I was converting the character's aim direction to a screen rotation.

Ok, fast forward to now: I've got the aimer's rotation matched up with the path the projectile will actually take, which I'm doing by decomposing a transform matrix which I build from two rotation matrices (one to represent the aimer's rotation, and one to represent the camera's 45 degree rotation on the x axis). My question is, is there a way to get not just rotation from a series of matrix transformations, but to also get a Vector2 scale which would give the aimer the appearance of being a 3d object, being warped by perspective? Orthographic perspective is what I'm going for, I think. So, the aimer arrow would get longer when facing sideways, and shorter when facing north and south because of the perspective. At the same time, it would get wider when facing north and south, and less wide when facing right or left.

I'd like to avoid actually drawing the aimer texture in 3d because I'm still using spritebatch's layerdepth parameter at this point in my project, and I don't want to have to figure out how to draw a 3d object within the depth sorting system I already have.

I can provide code and more details if this is too vague as a question... This is my first post on stack exchange. Thanks a lot for reading!

Note: (I think) I realize it can't be a technically correct 3D perspective, because the spritebatch's vector2 scaling argument doesn't allow for an object to be skewed the way it actually should be. What I'm really interested in is, is there a good way to fake the effect, or should I just drop it and not scale at all?

*Edit to clarify without the help of a picture (apparently I can't post them yet):*

I want the aimer arrow to look like it has been painted on the ground at the character's feet, so it should appear to be drawn on the ground plane (in my case the XZ plane) which should be tilted at a 45 degree angle (around the X axis) from the viewing perspective.

Alex

# Answer
This can be done in two simple steps:

* Pass your custom transformation to `SpriteBatch.Begin` but...
* Attach a `Matrix.CreateScale(1,1,0)` at the end to flatten the quad and ensure it's fully visible.

Note however that the transformation matrix is relative to the world origin not the sprite's origin, so it might need some tweaking to get the result in the correct position.

```
Matrix matrix = Matrix.CreateRotationX(MathHelper.ToRadians(60)) *
                Matrix.CreateRotationY(MathHelper.ToRadians(30)) *
                Matrix.CreateScale(1,1,0);

spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, matrix);

```

I've moved the old answer here.

PS: Thanks to Andrew Russel for making me *think*.
> 5 votes

---
Tags: xna, spritebatch
---


# Question
Title: Do you need expensive servers and fancy hosting in order to make a multiplayer game?
I've finished working on an RPG and it would seem so much more fun to make it multiplayer. SFML has a networking feature, I figured it's possible but then again, never in my life have I even tried something basic about networking, in fact my knowledge of it is very limited.

What would it take to make a multiplayer game resource-wise? I'm not talking about an MMO, more like a co-op type of game. Do I need mountains of cash to pay for hosting and servers and many many things to make one?

# Answer
> 12 votes
You can actually do this without any of your own servers at all. It would be a bit more work for your users however. One user can act as the server (with a separate server application or built into your game) or you can implement a peer-to-peer architecture. Consider, for example, Minecraft, there's no public server hosting games. Users create their own servers and their friends connect directly to it. Or back in the old days of Warcraft 2, users would use their modem to call the other player's modem and have a direct connection over the phone.

However, if you wanted to have a lobby system, that lists available servers, you'd need to invest in your own hardware.

Learn more about the options and decide what kind of structure you want to setup.

# Answer
> 2 votes
you could also consider services like player.io there are a few more, but that one comes to mind. Player IO and some others have a free plan.

# Answer
> 1 votes
Until you have hoards of users, you don't need mountains of severs. A domain name and a cloud server ought to be about $300/yr to start, but don't go for the lowest price, there are a lot of crappy providers out there.

# Answer
> 1 votes
I don't think so. You can use "Cirrus" ( It's free ) from Adobe to make peer to peer based multiuser apps like chatting, and simple games ( not complex ofcourse, as that needs a server in between).

# Answer
> 0 votes
People who invest in their own servers also can sell the data that the users will generate and can also analyze all the stats and infos more effectively; but servers and bandwidth are really not that cheap, so if you do not have enough money do not even start to think about this and follow the ideas given by the other answers.

---
Tags: c++, multiplayer, sfml
---


# Question
Title: Single player game into Multiplayer game
I developed a Single player game in Flash (Tic Tac Toe) and in the Multiplayer mode i will be able to do both player playing on the same system with out network.

I would like to extend it and make it enable to play the Multiplayer game for two player playing it online.

How i can be made give me some ideas , How test the Multiplayer game playing along with different computers(I do not have internet connection in home).

How I able to change the single player game into Multiplayer game , any minor changes required or I have to change the code base completely.

In which way i can make it possible.

# Answer
> 2 votes
Actually, it's always better to think of a multiplayer port when writing your engine/code base. Why? Because the game logic have to be located on server and not on client like for single player games.

The first thing you should do is writing (i mean on paper) the protocol your client-server pattern will follow, it will be a list of all messages client and server can receive and what they will do regarding the message.

When the protocol is write down, export your game logic on the server side and only game logic, a server is a non graphical application and all it has to do is handling all gameplay-related stuffs.

Your client, at the opposite, do not have to care about gameplay, calculations etc... it only has to listen for input event and redirect them to server (protocol) and render the game. Actually, the client is a graphical application.

# Answer
> 0 votes
well, most multiplayer games use an even queue system (client-server) where one player sends the server a message, and the server validates it and then sends the results to all clients which have their own queue. So, if you were to turn tic tac toe into that type, have each move send to a queue in the game that would handle both player and ai/other player

However, you can also use a p2p system where each player just sends a move to the other, while validating. You can have a simple system of who's turn it is to send messages. Tic tac toe shouldn't really require much to make into a multiplayer game

# Answer
> 0 votes
If you look at the demo included in the player.io page it has a multiplayer tic-tac-toe example

---
Tags: multiplayer
---


title: How would you UV unwrap an octahedron?

text:
# Question
Title: How would you UV unwrap an octahedron?
I tried to UV unwrap this octahedron, by slicing *one* of the sides.

I was able to lay it out on the texture like this, but with severe distortions.

Can someone help me UV map this without distortions?

# Answer
The way you could have this texture look more relaxed and less stretched out is by taking the two extreme corners, bottom left and top right and pulling them towards one another until each of them sits approximately 3x3 from squares from it's current position. If you want to keep using all of the texture image, you would need to distort the texture in the opposite direction to make it appear even on the model itself.

There is another way to accomplish a more relaxed look. instead of texturing the object from the side, texture it from the top view, so the sharp points in the top and bottom are in the center.

How I'd go about stretching the texture:

1. Get a high-res version of the texture. Stretching is a 'lossy(not lossless)' transformation.
2. Create a square plain.
3. UV map the texture you wish to stretch to that plain with the same UV map shape as the ones used on the original object.
4. If you wish to adjust it some more, you may also stretch the square itself a little bit.
5. Render the square with the texture and use the resulting image as your new texture.
6. Because this transformation is lossy, you may want to re-size the texture to 50%.
7. Test the new texture on your model and add adjustments if necessary.
> 2 votes

# Answer
For simple shapes, you can usually find sensible unwrapping approaches by looking to papercraft (those guys are experts at unfolding shapes. Albeit backwards.) For an octohedron, you might consider the model here:

http://psmay.com/wp-content/uploads/2012/01/logihedron.pdf

This sort of approach doesn't entirely cover your texture the way that your unwrapping did, but it has the advantage that your texture isn't distorted across any face, and you get uniform texel density per unit of space on your object (whereas with your distorted mapping, you get areas of high density on some faces, and low density on others).

It's all tradeoffs, really.
> 3 votes

---
Tags: uv-mapping
---


title: RPGMakerVX - Changing item_max?

text:
# Question
Title: RPGMakerVX - Changing item_max?
I've been working on a game for awhile and I am developing it with RPG Maker VX. I came to a point where I needed to... I guess for lack of better explanation... Limit the key items to just 1. So I started looking through my scripts and found (in Game\_Party):

```
  #--------------------------------------------------------------------------
  # * Get Maximum Number of Items Possessed
  #--------------------------------------------------------------------------
  def max_item_number(item)
    return 99
  end

```

and added below it:

```
  #--------------------------------------------------------------------------
  # * Get Maximum Number of Key Items Possessed
  #--------------------------------------------------------------------------
  def max_key_item_number(item)
    return 1
  end

```

and right below that is:

```
  #--------------------------------------------------------------------------
  # * Determine if Maximum Number of Items Are Possessed
  #--------------------------------------------------------------------------
  def item_max?(item)
    item_number(item) >= max_item_number(item)
  end

```

So I changed the last one too:

```
  #--------------------------------------------------------------------------
  # * Determine if Maximum Number of Items Are Possessed
  #--------------------------------------------------------------------------
  def item_max?(item)
    if key_item? == true
      item_number(item) >= max_key_item_number(item)
    end

    if key_item? == false
      item_number(item) >= max_item_number(item)
    end
  end

```

Now this seemed to not affect anything (that I could tell). I tested it and its still the same as before I touched anything. I am new to developing games and relatively new to scripting for them. Is this approach even close to what I want to do? Any help is greatly apprecieated!

# Answer
This is the correct way to do it. Figured it out after playing around for about 2 hours lol.

```
  #--------------------------------------------------------------------------
  # * Determine if Maximum Number of Items Are Possessed
  #--------------------------------------------------------------------------
  def item_max?(item)
    if item.key_item?
      item_number(item) >= max_key_item_number(item)
    else
      item_number(item) >= max_item_number(item)
    end
  end

```
> 3 votes

---
Tags: software-engineering
---


# Question
Title: Circle physics and collision using vectors
This is a problem I've been having, When making a set number of filled circles at random locations on a JPanel and applying a gravity (a negative change in the y), each of the circles collide. I want them to have collision detection and push in the opposite direction using vectors but I don't know how to apply that to my scenario could someone help?

```
public void drawballs(Graphics g){
    g.setColor (Color.white);

    //displays circles
    for(int i = 0; i<xlocationofcircles.length-1; i++){
    g.fillOval( (int) xlocationofcircles[i],  (int) (ylocationofcircles[i]) ,16 ,16 );
    ylocationofcircles[i]+=.2; //gravity
    if(ylocationofcircles[i] > 550) //stops gravity at bottom of screen
    ylocationofcircles[i]-=.2;

    //Check distance between circles(i think..)
    float distance =(xlocationofcircles[i+1]-xlocationofcircles[i]) + (ylocationofcircles[i+1]-xlocationofcircles[i]);

    if( Math.sqrt(distance) <16)
    ...

```

# Answer
> 2 votes
Please consider using camel case in your code like this:

```
locationOfCirclesY

```

First there is a typo here:

```
float distance =(xlocationofcircles[i+1]-xlocationofcircles[i]) + (ylocationofcircles[i+1]-xlocationofcircles[i])  ;

```

I think you meant:

... `(ylocationofcircles[i+1]-ylocationofcircles[i]) ;`

Second, this is incorrect.

Use `a^2 + b^2 = c^2`.

Meaning `distance = sqrt(a*a + b*b)`

```
distance =
(xlocationofcircles[i+1]-xlocationofcircles[i]) *
(xlocationofcircles[i+1]-xlocationofcircles[i]) +
(ylocationofcircles[i+1]-ylocationofcircles[i]) *
(ylocationofcircles[i+1]-ylocationofcircles[i]);

```

instead of:

Assuming `Radius = 8`

```
Math.sqrt(distance) <16

```

I would recommend you use this instead:

```
distance < 16*16

```

sqrt is a wasteful function in processing time.

http://en.wikipedia.org/wiki/Pythagorean\_theorem

That will allow you to detect collisions. The issue is that collisions occur in-between the movements. When you calculate and check for collisions, you need to find the time of collision and base the result of the collision on that factor. It is easier to use a pre-built tested physics engine if you wish to address this.

# Answer
> 0 votes
1. Draw the circle after, not before calculations. Otherwise you're always a frame behind. It's not bad if there's no user input, and you keep your code consistent - but if you draw some things before calculating the frame, and some after, you will get problems...
2. Gravity is a constant acceleration, not constant speed. If you want your effect to be realistic, you need to make two additional arrays: `yVelocityOfCircles` and `xVelocityOfCircles`.
3. Put literals (arbitral values) into constants, making the code easier to read and change. `const GRAVITY = .2;`.
4. Don't just rebound the circle from floor by a constant value. Calculate where it should stop: `centerY = floorTop - circleRadius`.
5. If there is a circle-circle collision, and I guess there is, the problem is more complicated than it seems, because you're dealing with racing conditions (which collision occurs first?). Because of your low gravity I'm assuming racing conditions won't be much of a problem. This will help you with circle-circle collision resolution: How can I know in which direction 2 balls will go in billiard game?

---
Tags: java, collision-detection, physics
---