# Question
Title: What broad-phase collision algorithms are suited to a static tiled world with dynamic objects of different sizes?
Sorry for this routine question, but I can't think of what broad-phase collision algorithms really work in the following, reasonably standard, setup:

* 2D tile based world, consisting of objects that do not move but might be altered/changed in some ways (not too often).
* Significant amount of dynamic objects, interacting with eachother and with the static tiles. These objects can be of variable size, possibly much larger than the tile size.

I started thinking about using just a grid to store the static tiles, but that has its issues. One example would be a level which is a long corridor following the edges of a square; I'm anxious about creating a whole nxn grid when there is a huge amount of irrelevant space in the middle. Also I'm not sure a grid is going to be helpful when figuring out what needs to be considered for collision, or needs to be drawn on screen; a quadtree seems more appropriate.

So far, I'm thinking of:

* using a quadtree to store the static tiles (to account for the possibility of large empty spaces in the middle of the grid for instance); hopefully that won't be prohibitively expensive when I need to modify some tiles (this shouldn't happen excessively often);
* using some other data structure (I'm undecided which is most suited) to store the dynamic objects, which might have very different sizes;
* once that's done, from the tile map I determine which tile edges are empty, solid or need further investigation for collisions; then I would use axis aligned bounding boxes for the dynamic objects to see if there is a possible collision with the static world, and some other algorithm (depending on the data structure for the dynamic objects) to model collisions between dynamic objects.

Maybe something slightly different would be more suited for the tiles, I'm thinking some sort of grid but with "off limits" regions that can be dismissed. I'm also somewhat anxious about fast-moving dynamic objects; so maybe those could belong to yet another data structure. I wouldn't expect them to be of large size (so they should fit inside tiles nicely), but I'd like to keep my options open in case I make some design changes.

(One thing I am completely neglecting is what generally happens with off-screen dynamic objects; I'm ignoring that problem for now and assuming everything is to be simulated together, but that might be a blunder.)

# Answer
> 1 votes
I'm very leery of tossing out a grid simply because of potential wasted space. Go for a grid for your tiles until you actually have a problem because of it. If and only if you get into that situation, consider simply adding one higher level above the grid of tiles—i.e., a grid of 8x8 or 16x16 tiles, perhaps. If needed, larger chunks that are completely empty could be neglected. But unless you have a very large amount of per-tile data that can't be skipped for empty tiles, just bite the bullet and store the whole grid.

If you don't want to store small dynamic objects in the grid structure, consider spatial hashing (i.e. treating the coordinates of your grid position as the key for a hash table). And if you have very large objects that span so many tiles that you don't want to use the same structure for them, you probably have so few of them that a spatial data structure might not be worth it.

---
Tags: 2d, collision-detection, tiles
---


title: How do you save game state?

text:
# Question
Title: How do you save game state?
What is the procedure followed by game programmers for saving and resuming game state? like files/mappings. I want to save it for tower defense game and I am using unity3D game engine.

# Answer
> 16 votes
I generally don't think in terms of a memory snapshot, but rather I just make a list of which values need to be saved between sessions and save those values into an external file.

This depends of course on the needs of your specific game, but usually I simply save the state of the current level (ie. where all the enemies are, what their health is, etc.) and then higher level stuff like what levels the player has already completed.

# Answer
> 10 votes
*This answer is Unity3d specific*.
In Unity, most classes are serializable, this means you are able to stream complete Unity objects to disk. The follwing C# code is a way to serialize an object, save it to disk an load it again (after loading you must cast the object):

```
import System;
import System.IO;
import System.IO.Stream;
import System.Runtime.Serialization;
import System.Runtime.Serialization.Formatters.Binary;

class SaveLoad {
        public static function SaveFile(filename:String, obj:Object):void {
                try {
                        Debug.Log("Writing Stream to Disk.", SaveLoad);
                        var fileStream:Stream = File.Open(filename, FileMode.Create);
                        var formatter:BinaryFormatter = new BinaryFormatter();
                        formatter.Serialize(fileStream, obj);
                        fileStream.Close();
                } catch(e:Exception) {
                        Debug.LogWarning("Save.SaveFile(): Failed to serialize object to a file " + filename + " (Reason: " + e.ToString() + ")");
                }
        }

        public static function LoadFile(filename:String):Object {
                try {
                        Debug.Log("Reading Stream from Disk.", SaveLoad);
                        var fileStream:Stream = File.Open(filename, FileMode.Open, FileAccess.Read);
                        var formatter:BinaryFormatter = new BinaryFormatter();
                        var obj:Object= formatter.Deserialize(fileStream);
                        fileStream.Close();
                        return obj;
                } catch(e:Exception) {
                        Debug.LogWarning("SaveLoad.LoadFile(): Failed to deserialize a file " + filename + " (Reason: " + e.ToString() + ")");
                        return null;
                }
        }
}

```

# Answer
> 2 votes
For a TD I'd probably save exclusively between waves. That way all you have to think about is the towers. Put some automatic save points in the levels, no more than 10 minutes between, but less is probably preferable.

Of course if your levels are short enough you could simply save nothing but the campaign status.

# Answer
> 1 votes
When I refer to the current state of the game I am referring the memory snapshot at the moment of saving. You need to be able to recreate that from the data you are going to store on you HDD.

It is easiest just serialize all of you classes that have data that needs to be persistent and dump it to the HDD, essentially performing a memory dump. Problem with this is that altering you classes will change the number/types of serialized values and break old saves. Also because you are saving everything it increases loading times. Its more efficient to mark individual fields that are actually needed to rebuild the current "memory snapshot" with whatever attribute system your serializer/IDE uses. Then rebuild the "memory snapshot" from that saved data.

Also I have never used Unity before so it may have something built in. However, this is the typical approach.

---
Tags: unity, tower-defense, savegame
---


title: What are Glow Textures?

text:
# Question
Title: What are Glow Textures?
So i'm not quite sure exactly what "glow textures" are. For my implementation of a "lightning" effect, according to the comments on the article; http://drilian.com/2009/02/25/lightning-bolts/

They guy uses "glow textures". To achieve the really cool effects on his beams. I'm trying to-do the same thing, except that i'm not 100% sure what a glow texture is, currently the texture i'm using produces this output \*I'm also using a simple shader to adjust the color value the lightning is rendered at; http://www.youtube.com/watch?v=dQNRYD8bJJo

Which isn't very good, it has the shape of the lightning but it doesn't have the sorta "flare" of it. This is a screenshot of my current texture that i'm using: http://dl.dropbox.com/u/13874083/screenshots/screen120417-105326.png

So essentially what i'd like to ask is mainly what is a glow texture? And perhaps to see an example of one would be really appreicated.

Edit: Taking the advice of kaoD, i'm now rendering the using Additive Blending, I've also got the Max Blending working, yet, still the bolt's do not produce the required effect that i'd like. Here's another video of them in action with the current code; http://www.youtube.com/watch?v=T0OEBobHqks

And here's specifically how i'm rendering them;

```
        spriteBatch.Begin(SpriteSortMode.Immediate, new BlendState
            {
                ColorSourceBlend = Blend.One,
                ColorDestinationBlend = Blend.One,
                ColorBlendFunction = BlendFunction.Max
            }, null, null, null, effect);

        //Set Brightness of The First Bolt
        effect.Parameters["brightness"].SetValue(firstBoltBrightness);

        spriteBatch.Draw(firstBoltTarget, Vector2.Zero, Color.White);

        //Set Brightness of the Seconded Bolt
        effect.Parameters["brightness"].SetValue(secondBoltBrightness);

        spriteBatch.Draw(secondBoltTarget, Vector2.Zero, Color.White);

```

# Answer
> 2 votes
Glow textures are nothing special. He's just using a glow-like texture (in fact, look at the comments, the author describes it as a gradient.)

The magic behind the actual glow is not the texture but the blending of it into the scene. In this case, additive blending should do the trick (check for examples here at GDSE) although he describes he uses max blending (which, tbh, I'm not aware of.)

---
Tags: xna, glow
---


title: Essentials for building a RTS

text:
# Question
Title: Essentials for building a RTS
I was wondering if anyone had any links to good reads or books in regards to things to think about when developing a RTS game, I would have been reading things like this and this but would like to read more into it.

Also I have development experience and soon would like to start building the skeleton myself but if anyone has any additional articles about the process (not in programming, but more on planning) that would be great help.

# Answer
> 11 votes
You could read some Gamasutra features. That's usually a good source of information, from people that actually ship games:

---
Tags: rts, planning
---


# Question
Title: What technique should I use to facilitate communication between XNA GameComponents (or between components of any type in a game)?
I'm starting out on my first 'proper' game project, and I've inevitably hit a block trying to decide how game components in XNA should communicate.

From previous (Java) GUI programming events, handlers and listeners seemed like the way forward. So I'd have some kind of event bus which accepts event registrations and classes subscribed to those events, with handlers to deal with them. For example (pseudocode):

```
class SpriteManager
    Update(){
        if(player.collidesWith(enemy)
             // create new 'PlayerCollisionEvent'
    }

class HUDManager
    onPlayerCollisionEvent(){
        // Update the HUD (reduce lives etc)
    }

```

However, I'm not sure of the code setup (in C#) that would be required to fully accomplish this. What keeps track of events (some kind of bus?), and how is it structured?

There also seems to be a lot mentioned about on Game Services, whereby you can register a GameComponent in your main Game.cs class, then fetch it from anywhere in your code that has a reference to the main 'Game' object. I've tried this with my SpriteBatch object and it seems very easy.. however, I can't see this being as flexible as an event model.

Take for example when an enemy dies. We want to update the game score. Using services I can get a reference to my StateManager object created in Game1 and added as a service, then set 'score' to the new value. I would of thought a 'onEnemyDeath' event, which can be handled differently by a multitude of classes, but initiated by 1 line of code in the relevant 'enemy death detection' section, would be better than individually casting each required GameComponent then calling whatever methods are required.

Or are these inferior strategies to something else?

I realise this is partly my poor C# knowledge as much as game communication paradigms, but I'd really like to get this fundamental thing right.

**Update**

Having looked at Services is more detail I'm less convinced - it's basically passing a global variable around (from what I understand).

**Update 2**

Having had a look at this basic tutorial on event handling and testing the sample code it seems events would be a logical choice for what I'm discussing. But I can't much of it in use in the samples I've seen. Is there some obvious reason why one shouldn't?

# Answer
> From previous (Java) GUI programming events, handlers and listeners seemed like the way forward. So I'd have some kind of event bus which accepts event registrations and classes subscribed to those events, with handlers to deal with them.

The reason you won't find much about event buses in C# is because I don't think anybody outside of Java calls such a thing a 'bus', in my experience. More common terms might be message queue, event manager, signals/slots, publish/subscribe, etc.

You don't need any of those to make a working game, but if that is the kind of system you are comfortable with, it will serve you well here too. Unfortunately nobody can tell you exactly how to make one because everybody rolls them a bit differently, if they even use them at all. (I don't, for example.) You might start with a simple `System.Collections.Generic.List<Event>` for the queue, with your various events being subclasses of Event, and a list of subscribers for each event type. For each event in the queue, get the list of subscribers, and for each subscriber, call `handle(this_event)` on it. Then remove it from the queue. Repeat.

> There also seems to be a lot mentioned about on Game Services, whereby you can register a GameComponent in your main Game.cs class, then fetch it from anywhere in your code that has a reference to the main 'Game' object. I've tried this with my SpriteBatch object and it seems very easy.. however, I can't see this being as flexible as an event model.

It's probably not as flexible, but it's easier to debug. Events and messages are tricky because they decouple the calling function from the called function, which means that your call stacks aren't terribly helpful when debugging, intermediate actions can cause something to break which normally works, things can fail silently when not hooked up properly, and so on. The explicit method of "grab a component, and call what you need on it" works well when it comes to catching errors early on and having clear and explicit code. It just tends to lead to tightly coupled code and lots of complex dependencies.

> I realise this is partly my poor C# knowledge as much as game communication paradigms, but I'd really like to get this fundamental thing right.

C# is pretty much an identical language to Java. Whatever you did in Java can be done in C#, just with different syntax. If you have trouble translating a concept, it's probably just because you only know a Java-specific name for it.
> 4 votes

# Answer
Have you tried just using simple static events? For example, if you wanted your score class to know about when an enemy died, you would do something like this:

## Score.cs

```
class Score
{
    public int PlayerScore { get; set; }

    public Score()
    {
        EnemySpaceship.Death += new EventHandler<SpaceshipDeathEventArgs>(Spaceship_Death);
    }

    private void Spaceship_Death(object sender, SpaceshipDeathEventArgs e)
    {
        PlayerScore += e.Points;
    }
}

```

---

## EnemySpaceship.cs

```
class EnemySpaceship
{
    public static event EventHandler<SpaceshipDeathEventArgs> Death;

    public void Kill()
    {
        OnDeath();
    }

    protected virtual void OnDeath()
    {
        if (Death != null)
        {
            Death(this, new SpaceshipDeathEventArgs(50));
        }
    }
}

```

---

## SpaceshipDeathEventArgs.cs

```
class SpaceshipDeathEventArgs : EventArgs
{
    public int Points { get; private set; }

    internal SpaceshipDeathEventArgs(int points)
    {
        Points = points;
    }
}

```
> 1 votes

# Answer
If you feel uneasy with the event-based approach, give Artemis C# a try, it is an Entity System framework based on http://t-machine.org/index.php/2007/09/03/entity-systems-are-the-future-of-mmog-development-part-1/

Source: https://github.com/thelinuxlich/artemis\_CSharp Example game: https://github.com/thelinuxlich/starwarrior\_CSharp
> 1 votes

# Answer
try to use event aggregator like this one
> 0 votes

---
Tags: xna, c#, events, game-component
---


# Question
Title: How do I calculate the normal of a plane defined using homogeneous coordinates?
I can define a plane in 3D space using three 3D points (`p0`, `p1`, `p2`) that all lie in the plane and that form a non-degenerate triangle. Calculating the normal of the plane is as simple as calculating the cross product of any two non-parallel 3D vectors that lie in the plane, for instance `(p1 - p0)` and `(p2 - p0)`. So far, so good.

But what if I use homogeneous coordinates for my points? How do I find the normal of the plane then? Of course, if all points have `w != 0`, I could simply normalize them (divide by `w`) and treat them as regular 3D points. But what if one or more points have `w == 0`?

The way I see it, there are three possible answers to this question:

1. *You do it the same way.* If so, please explain how to calculate the cross product of two 3D vectors defined using homogeneous coordinates.
2. *You do it some other way.* If so, please explain how.
3. *You can't, your question makes no sense and you are clearly confused.* If so, please explain why.

# Answer
You do it the same way, basically. You just need to get rid of the divisions by zero.

First of all, there is no solution if `w0=w1=w2=0`. This degenerate case should be handled as if all points were aligned (because in a sense, they are, at infinity).

Let us assume, without loss of generality, that `w0!=0`. If not, just swap `p0` and `p1` for instance.

Here is how you would do it when no `w` is zero: divide the 3-dimensional points by their respective `w` value, then take a cross-product of the vectors you mention:

```
     |x0|         |x1|         |x2|
p0 = |y0|    p1 = |y1|    p2 = |y2|
     |z0|         |z1|         |z2|

q0 = p0/w0   q1 = p1/w1   q2 = p2/w2

v = (q2 - q0) × (q1 - q0)
  = (p2/w2 - p0/w0) × (p1/w1 - p0/w0)
  = 1/(w2*w1) (p2 - p0 w2/w0) × (p1 - p0 w1/w0)

```

But wait, if this vector `v` is normal to the plane, then obviously `v` multiplied by `w1*w2` is still normal to the plane! So here is another vector that works:

```
v' = (p2 - w2/w0 p0) × (p1 - w1/w0 p0)

```

This one involves no division by zero and is therefore safe to take to the `w1=0`, `w2=0` or `w1=w2=0` limits.
> 5 votes

---
Tags: 3d, mathematics, normals
---


title: Pointy top hexagonal A* pathfinding

text:
# Question
Title: Pointy top hexagonal A* pathfinding
I'm trying to create a game with a hex based map with the points at the top. I have most of it working, however the path finding is being a little awkward. The heuristic I'm using is called Euclidean I believe and is like so:

```
var dx:Number = destinationNode.c - node.c;
var dy:Number = destinationNode.r - node.r;

return Math.sqrt((dx * dx) + (dy * dy));

```

`Node` is the node the unit is currently on, `c` is the node's column number and `r` is its row number. I'm using these as a simpler x and y coords. I'm trying to limit the unit to 3 hex moves in one round, so initially I thought it'd be as simple as `IF returned heuristic < 3 unit can move to that hex`, however it's not working out quite like that.

As you can see in the pic above, the bottom right selected hex with the "1 + 9 = 3.162277" is moveable to in 3 moves, however the hex with "9 + 1 = 3.162277" on the far right would need 4 moves to reach it. Can anyone offer any advice on how to make this work?

EDIT: My problem was being caused because I was using a Cartesian coordinate system and was just staggering every other Y coord. Fixed this by making the Y axis go down at a 60 degree angle. Thanks to amitp for the links that showed me what I was doing wrong.

# Answer
> 4 votes
The A\* heuristic is an estimate. It usually does not give you the true distance.

You can calculate distances exactly on a hexagonal grid. See section 4 of Clark Verbrugge's hex grid guide, and then section 2. Alternatively, see aaz's answer on this stackoverflow post.

# Answer
> 1 votes
You have to plot the entire path and then only do the first 3 moves. The place within 3 squares with the best score isn't necessarily on the path to where you want to go.

Also your heuristic is an estimate, and from what I can tell, Euclidian is more than good enough for you, although it sometimes underestimates a little in your case.

---
Tags: path-finding, actionscript-3, hexagonal-grid
---


title: Accessing struct in glut

text:
# Question
Title: Accessing struct in glut
I have to write a game for a uni project using openGL / glut. I am just going to use a generic example code as I'm just looking for a solution to one specific problem:

Using glut, I have to call a function 'glutDisplayFunc(display);' in the main function. I am also using an IdleFunc(update). The problem is that, as described here, the 'display' function cannot pass anything. I have some structs outside my main that I wish to be initialized in the main, and be accessible by display and update. Hopefully some code will explain my problem better:

```
#include <gl/glut.h>

struct Player
{
GLfloat x;
GLfloat y;
GLfloat z;
int score;
...
}

//function prototypes (showing how I would normally pass the struct)
void InitPlayer         (Player &player);
void DrawPlayer         (Player &player);
void UpdatePlayer           (Player &player);

void main (int argc, char **argv)
{

    Player player;

    InitPlayer(player);

    //...
    //glut / openGL initialisation code left out
    //...

glutDisplayFunc         (display);
glutReshapeFunc         (reshape);
glutIdleFunc            (update);

glutMainLoop();

}

void display()
{
DrawPlayer(player);
}

void update ()
{
UpdatePlayer(player);
glutPostRedisplay ();
}
//end

```

The above code doesn't work: I hope it demonstrates what I would like to do though. Access the struct 'player' in 'display' and 'update', having the same values stored globally. How would I go about ?

# Answer
> 1 votes
First of all, you should be more descriptive about why something doesn't work. At the very least, explain whether it compiles and what errors or bad behavior you are experiencing.

Make player a global object (declared outside of main) and you should be good to go.

# Answer
> 1 votes
A function can only access two things (a member function can access 3, but you can't use them as GLUT callbacks): its parameters and any globally-accessible data. The parameters to your display function can't provide you the information. Therefore, the only alternative is to make whatever your display function needs to access globally accessible.

It's not the cleanest of coding, but that's what happens when you use GLUT. Best accept it and move on.

---
Tags: opengl, glut
---


title: How are "2.5D" art assets created?

text:
# Question
Title: How are "2.5D" art assets created?
By "2.5D" I mean the art style in games such as Roller Coaster Tycoon, Age of Empires 2 or Fallout 1 and :

Everything in the games appears to be created with a "pixel art"-like tool. Am I correct?

How are the moving characters are created though? Take AoE2: For much of my childhood I was convinced that the soldiers, villagers and other characters were 3D!

Could someone explain:

1. What dimensionality are the characters?
2. What sort of software package could I use to create them?

# Answer
Assets like these can be created in any 3D package.

They are imported into a game by pre-rendering the models at specified angles, using orthographic projection in the viewport. The pixel effect probably is a side-effect of rendering at a low resolution with little or no anti-aliasing. The spritesheets generated by these will be ordered in such a way that the application can mathematically compute which frames apply to which angles and animation frames.

In Age of Empires 2, you can easily tell that the structures are pre-rendered 3D assets, especially by how they have such a low frame rate of animation. The reason for this is simply disk and memory consumption. Animating large images like those at a high frame rate will bloat the asset sizes tremendously, on disk and in memory. The smaller sprites, e.g. the villagers, can have much higher rates of animation, as they are comparatively small and less intensive. This is also why the units in the game have only 8 directions of rotation, as accommodating all potential rotations and animation frames will, again, bloat disk and memory consumption (not to mention rendering time too).

There are some games however that do use a 3D method for rendering certain objects. Take C&C Tiberian Sun and C&C Red Alert 2 for example. The infantry and structures use pre-rendered sprites, like AOE2. However the vehicles use a 3D rendering technique called "Voxels", which are essentially 3D bitmaps that are rendered in real-time, which is why they have such a large variety of angles and positions, whilst still having that "2.5d" look.

Somewhat Unrelated: Also I believe that 2.5D normally refers to 3D rendered games that use 2D gameplay mechanics. I may be wrong in this case, but that is how I refer to it. :)
> 20 votes

---
Tags: 2d, art, rts, 2.5d
---


title: Sprite Sheet for Musical Notes?

text:
# Question
Title: Sprite Sheet for Musical Notes?
Does anybody know of a sprite sheet of musical notes (half note, minim)? I am trying to draw musical notes onto an android canvas.

# Answer
There are two fonts out there called Anastasia and Maestro. They consist of musical notes. If their license and your software license are compatible, you could just embed them in your application and render the notes using that.
> 1 votes

---
Tags: music, spritesheet, spritebatch
---


title: Getting the normals of a hemisphere?

text:
# Question
Title: Getting the normals of a hemisphere?
I'm trying to calculate the normal for a hemisphere.

I draw the hemi-sphere by this code:

```
for(float phi = 0.0; phi < 1.567; phi += factor) {

        glBegin(GL_QUAD_STRIP);

        for(float theta = 0.0; theta < 2*3.14 + factor; theta += factor)
        {
            x = rh * sin(phi) * cos(theta);
            z = rh * sin(phi) * sin(theta);
            y = -rh * cos(phi);

            gl::vertex(Vec3f(x, y, z));

            x = rh * sin(phi + factor) * cos(theta);
            z = rh * sin(phi + factor) * sin(theta);
            y = -rh * cos(phi + factor);

            gl::vertex(Vec3f(x, y, z));

        }
        glEnd();
    }

```

# Answer
Same way you get the normals of a sphere, the vector from the centre to any surface point is a normal for that surface point. For a lot of uses you probably want them normalized, but that is all there is to it. Just remove the `rh` factor from your position calculations and you get the normalized normals.

Spheres turn out to be mathematical entities that are incredibly easy to work with.
> 2 votes

---
Tags: opengl, mathematics, graphics-programming
---


title: Differential programming for a vehicle

text:
# Question
Title: Differential programming for a vehicle
I am to a point on my vehicle where, when im going fast and turning, the vehicle acts weird because the inside tires are moving faster than the outside tires. So i need to figure out how to program in a differential but I can't seem to get it working properly so I am here to see if anyone has experience with this.

I have checked online for the physics but that seems to take more info into account than i can supply in my game (like real gravity influence on the vehicle). Currently I use the following logic to determine the differential wheel speeds. I will try to explain as clearly and simply as possible so I apologize if it is confusing or over-simplified, its confusing to me!

**Here is what i do:** I divide my current turn degree by the max turn amount to get a percentage, I then take that percentage and apply that to a modifier percentage (just a percent i have made up and been tweaking to reduce the number passed to the differential, not sure what this should really be. Engine speed? Velocity?). Then in my differential, I check to see if the vehicle is turning left or right and *reduce* the speed on one side by x% and *increase* the speed on the other side by the same x%

I'm certain that my biggest problem is the number i'm making up to reduce the turn percent but I cant tell what to put there. I know that directly passing the turn % to the differential (say, 40%) would reduce one side by 40 and increase the other by 40 and that is clearly not right.

I have access to the engine speed, transmission, each wheels axle speed, torque, vehicle velocity, etc but I am not sure which of these i should take into consideration when doing this formula.

Maybe I am over complicating it or maybe i am over simplifying it. Any help in understanding this would be great!

# Answer
> 9 votes
I really think you should not do it this way and that you should look more into the real physics (see my comment). However I can tell you why your current approach doesn't work. (Too long for the comments so I'll just post this as an answer)

Let's first explore what happens (you've probably done this yourself already).

The sitation is basically as in the picture above, but let's simplify the numbers a bit:

Say the car C is 2 meters wide and has a minimum turning circle of 5 meter. I now steer full left. The front left wheel now follows a circle with a diameter of 5 meters. The front right wheel now follows a circle with the diameter of 7 meters. Completing one full circle will have the left wheel travel 10\*pi meters. The right wheel travels 14\*pi meters. Now say that the wheels of C all have the same size, and that the circumference of the wheels is 0.5\*pi meters *(yes those are big wheels, but no-one said we couldn't model a monster truck!)* The differential will have to make sure that for every 20 rotations of the left wheel the right wheel rotates 28 times in order for none of the wheels to slip.

So you could now say that the diff-% should be tweaked, say for full left it should differentiate +40%, and let's just lerp this to full right -40% and then we're golden?

Unfortunately, as you've seen, this doesn't work. Let's find a general formula for the differential in this car. Here x is the desired turning circle.

```
left wheel distance: x*pi meters
right wheel distance: (x+2)*pi meters:
left wheel rotations: x*4
right wheel rotations: (x+2)*4

```

I would argue that the diff should work at the fraction ((x+2)\*4 / (x\*4)) \[\*\]. *(Times 100% if you want it in percentages)* Let's plot that:

As you can clearly see this function is non-linear. So just having the differential depend linearly on how much your steer to the left or to the right is never going to work.

Now I see that it's tempting to just use the above formula but I think it's probably best if you don't for the reasons described above :). Also you will need to implement 2 differentials unless if your steering involves all four wheels, which makes it even more difficult to implement, see the 1st picture again.

\[\*\]: which we can simplify: (x+2)\*4 / (x\*4) =\> (x+2)/x

---
Tags: physics, algorithm, car
---


# Question
Title: Frame Interpolation issues for skeletal animation
I'm trying to animate in-between keyframes for skeletal animation but having some issues. Each joint is represented by a quaternion and there is no translation component. When I try to slerp between the orientations at the two key frames, I got a very wacky animation. I know my skinning equation is right because the animation is perfectly fine when the animation is directly on a keyframe rather than in-between two.

I'm using glm's built in mix function to do the slerp, so I don't think there are any problems with the actual slerp implementation.

There's really one thing left that could be wrong here. I must not be in the correct space to do slerp. Right now the orientations are in joint local space. Do I have to be in world space? In some other space along the way? I have the bind pose matrix and world-space transformation matrix at my disposal if those are needed.

# Answer
Stumbled upon this post: http://www.gamedev.net/topic/605007-animation-transitions/

Interpolation doesn't work too well when the dot product of the two quaternions is less than 0. If this is the case, I just negate one of them and then do the slerp.
> 2 votes

---
Tags: animation, skeletal-animation, interpolation
---


# Question
Title: How to deal with VBOs when rendering mesh's that may or may not be displayed?
I'm working on a multiplayer game and will be displaying other players near the player. At most 16 players could be near the gamer however there could also be 0. What I'm thinking of doing is setting up 16 empty VBOs so they're ready to load with character's position when the client receives them. Is it valid to create empty VBOs? If not how should I go about rendering data that may or may not be there depending on what the server is sending the client?

# Answer
The thing you seem to be missing is the concept of *transforming* objects. A mesh doesn't have a position in the world; it's just a collection of vertex data. When you *render* the mesh, you transform that vertex data from its default location to a place in the world.

This is what all of that matrix stuff people use does; vertex positions can be transformed by transformation matrices. Vertex shaders are primarily responsible for this.

This means that you don't modify the vertex data on the CPU. You don't translate it yourself; you let the GPU do the translations. When you render an object, you provide a transformation to the GPU, and your vertex shader will apply it.
> 5 votes

# Answer
This is obviusly bad approach. By creating empty VBO you will not gain any extra performance and you will waste memory.

So from the rendering point of view:

* If you wanna save memory: Create VBO per object if it is visible. If it is not visible, release it. But i do not recommend this for a simple game, since you are slowing game down.
* If you wanna be fast: Just have VBO per object and do not render it if it is not visible.
* If you wanna be super fast: Have all objects in one long VBO and render it using offset.
> 1 votes

# Answer
First, make a list of the resources (VBO, Texture, Shader, etc.) the current map/level needs to be rendered. Second, compute the amount of memory each resource consumes.

If everything fits in GPU memory, simply copy everything and render. If it doesn't fit, you'll have to devise a caching system.

Keep often used resources in GPU memory. Release unused resources when they're offscreen (and quite far from the current view). If rendering a single frame requires more memory than available, the process will be harder and quite slow.

To render only what's shown, you need a list of renderable "objects" along with their position and, maybe, their bounding volume. Keep a camera frustum updated in your game code and cull objects against it. Then, build a list of objects to render and send those to your renderer.

OpenGL will allow you to render objects, but you still need to build a minimal framework to identify what you want it to render. If your game is very simple, a simple distance test might be enough instead of frustum culling.
> 1 votes

---
Tags: opengl, vbo
---


# Question
Title: Most efficient way to implement walls and shadows in 2d
I am making a 2d top-down programming game similar to robocode. There will be up to 1000 walls (lines) in the arena, and up to 50 robots. Each robot can see in a 90 degree arc, and cannot see through walls. I need an efficient way to calculate what each robot can see (other robots and walls). I already have a grid of bins implemented. I was wondering what is the most efficient way to tackle this problem.

It would be nice if the method also includes a way to draw the shadows for visualization, but this is not necessary.

I am using C++ and the Qt framework.

**Summary:** The main question is how to generate a list of robots and walls that each robot can see. For example:

```
Robot 1 can see:
    Robot 6
    Robot 15
    A wall from (50,60) to (70,80)

Robot 2 can see:
...

```

# Answer
> 1 votes
Well I'd suggest storing them in some kind of scene graph so that you only have to draw what you can see, and it would be easy to calculate what you can see. And for what they can see, i suggest raycasting or some simplified version of it

---
Tags: c++, 2d, qt, line-of-sight
---


title: How to limit the distance of a point?

text:
# Question
Title: How to limit the distance of a point?
I'm making an Angry Birds like game and I need to limit the distance that the user can pull back the slingshot, how do I do this?

# Answer
> 6 votes
Get the length of the vector from the slingshot to the mouse/finger/whatever.

If it's more than your allowed length then normalise the vector (to make its length 1) then multiply it by the maximum length.

---

Note, to avoid a square-root (costly operation) in the first bit compare the length squared with the max length squared.

```
// Get a vector from slingPos to targetPos
// (you may actually want the other way round in your game,
// as the angry object will be thrown towards the slingPos)
var orignalVector = targetPos - slingPos;
var originalLengthSq = originalVector.X * originalVector.X +
                       originalVector.Y * originalVector.Y;
if (originalLengthSq > maxLengthSq)
{
    // I have already done the first bit of normalisation (getting the length squared)
    // so we re-use that calculation.
    var normalisedVector = originalVector / sqrt(orignalLengthSq);
    originalVector = normalisedVector * maxLength;
}

```

---
Tags: mathematics
---


title: Positional sound with headphones?

text:
# Question
Title: Positional sound with headphones?
I've have read this interesting question, where is explained how to simulate positional sound with the left and right channel; but still I wonder: is it possible to simulate positional sound (with headphones) when the source is "in front" of you, "behind", "above", or "below"?

Again, all I can do is to adjust left/right volume.

EDIT: I can also alter the playback rate (pitch) of the sound, ranging from double to half the original pitch.

# Answer
There are some tricks to fake the "in front" and "behind" effects. But this is not simple to implement in order to have a real sexy effect. You will find some tricks in the Blumlein's approach on stereophonic system.

As far as I know you won't be able to have a good effect with only volume control.
> 3 votes

# Answer
True 3D positional sound is entirely possible, however, not using the simple effects at your disposal. You need to be well versed in digital signal processing and a sub-field of that called head relational transfer function.

HRTF basically seeks to emulate how sound is transferred through the air and your body, neck, ear lobes and head into your ears (your brain uses these subtle hints in order to position sound in 3-dimensional space). This works because, with headphones, the sound is delivered directly into your auditory canal: skipping any other mediums (such as your head). 5.1/7.1 headphones (which are complete snakeoil) might actually hinder HRTF because they introduce your outer ear into the equation.

Unfortunately HRTF is prohibitively expensive to simulate. For example, I evaluated MyEars and while my machine (Intel Core2 Extreme) could cope with with the samples running alone (and yes, it was **extremely** convincing) I couldn't use it in games. Mid-range sound cards (such as Creative X-Fi's) have HRTF processors and this will give you true 3D positional sound in games that support it (DirectSound in Windows 7 dropped support for hardware acceleration, so you will need to use OpenAL).

For a good example of what HRTF can actually achieve, this recording was done with a modelled head with embedded microphones (it isn't simulated HRTF, it's recorded): once again it will only work with headphones.

If you wish to use 3D positional sound simply use OpenAL \- don't bother trying to roll it yourself.

Some more examples (made using simulated HRTF):
> 3 votes

---
Tags: sound-effects
---


# Question
Title: Basic game architechture best practices in Cocos2D on iOS
Consider the following simple game: 20 squares floating around an iPhone's screen. Tapping a square causes that square to disappear.

**What's the "best practices" way to set this up in Cocos2D?**

Here's my plan so far:

* One Objective-c `GameState` singleton class (maintains list of active squares)
* One `CCScene` (since there's no menus etc)
* One `CCLayer` (child node of the scene)
* Many `CCSprite` nodes (one for each square, all child nodes of the layer)
* Each sprite listens for a tap on itself. Receive tap =\> remove from `GameState`

Since I'm relatively new to Cocos2D I'd like some feedback on this design. For example I'm unsure of the `GameState` singleton. Perhaps it's unnecessary.

# Answer
> 2 votes
Looks good. But you don't really need a CCScene class. Just implementing the scene-method listed below in your CCLayer works fine. And the need to let the singleton maintain a list of active squares is indeed unnecessary, unless you have a good reason to keep it.

```
// Scene with layer method
+(CCScene*) scene {
    CCScene* scene = [CCScene node];
    MyLayer* layer = [MyLayer node];
    [scene addChild:layer];
    return scene;
}

```

# Answer
> 1 votes
the design seems good although I would not use the singleton but add the sprite as children of the layer and remove each sprite from its father when touched (this would also make it disappear). I guess this design is good to start but you will probably want to add some menu so you will have more scenes. In that case you can use the singleton to store the information you need among the different scene (i.e. score, etc.).

---
Tags: architecture, cocos2d-iphone, touch, ccsprite
---


# Question
Title: How do I make a vector exactly reach a line?
Let's say a vector starts at Point P and points in the direction of v. How do I make sure that this vector exactly reaches the line? Its end should be exactly on the line, and not cross it.

# Answer
> 5 votes
You should calculate the intersection point (IP) between the two lines.

```
      (X - Ax)     (Y - Ay)
EQ1 = --------  =  --------   =>   (X-Ax) * (By-Ay) - (Y - Ay) * (Bx - Ax) = 0;
      (Bx - Ax)    (By - Ay)

      (X - Px)     (Y - Py)
EQ2 = --------  =  --------   =>   (X-Px) * (Vx) - (Y - Py) * (Vy) = 0;
         (Vx)        (Vy)

```

Solve the two equations and you get IP (X,Y).

Maybe you'd need to check that IP is between A and B... before continue...

Then you build a new line with this equation:

```
  (P + V) = P + t*(IP-P)   => t = V / (IP - P)

   t = (IP.X-P.X != 0)
        ? (V.X / (IP.X - P.X))
        : (V.Y / (IP.Y - P.Y));

  if t>1 then (P+V) has overpassed the line

```

EDIT:

Remember:

```
1) You have to calculate IP. the intersection point
2) You should check that IP is between A and B
3) You had the vector V, and now have the vector (IP-P),
4) You can choose betwwen two options:
   a) Now you can compare the vector lenghts to now if V is greater that (IP-P)
   b) Calculate t as I described before...
           if t==0 => V=(0,0);
           if t=1 => V=(IP-P)
           if (t>0 && t<1) length(V) < length(IP-P)
           if (t>1) length(V) > length(IP-P)

```

# Answer
> 2 votes
## You should:

1. Find an (X, Y) point of intersection of your line and a support line for the vector.
2. Extend your vector by the distance from its end to than point you've found.

### Example:

1. Find the (X, Y) point: solve the

`(X - Ax) * (By - Ay) - (Y - Ay) * (Bx - Ax) = 0`

and

`(X - Px) * Vx - (Y - Py) * Vy = 0`

equations.
2. Your new vector will be **Your old vector** (both components) plus **YVN** * **Dist**;

* where **YVN** is **Your old vector** normalized (one-unit length);
    * where **Dist** is distance between **N** and **V**;
    * where **N** is your newfoundland **point**.

---
Tags: mathematics, algorithm, vector
---


title: Random Sprite Speed

text:
# Question
Title: Random Sprite Speed
I followed the Rain Catcher tutorial from libGDX and I made some modifications to the code, allowing the rain drops to appear faster. But I cant figure out how to make the raindrops fall at random speeds.

How can I make **random** raindrops fall at **different** speeds? I also want the raindrops to **accelerate** when it gets closer to the bottom.

# Answer
The first thing to do, would be to specify a velocity component for the raindrop class; which specifies how fast the raindrop falls. To apply this, try the following (assuming the velocity component is called yVelocity):

```
// Take this line
raindrop.y -= 200 * Gdx.graphics.getDeltaTime();
// Replace with something like
raindrop.y -= raindrop.yVelocity * Gdx.graphics.getDeltaTime();

```

You can set the yVelocity in the constructor of the raindrop using the random function. (See here for an example of how to use the random function to get a value within a range).

If you want only specific random raindrops to have a random speed applied to then; use the random function to determine whether the constructed raindrop is allowed to have a random speed applied, by checking that the random value falls within a certain range.

The following example applies a random velocity to roughly 1 in 10 raindrops.

```
if (Math.random() >= 0.9) {
    raindrop.yVelocity = //Random velocity calculation here;
}
else {
    raindrop.yVelocity = 200;
}

```

To have the raindrops move faster as they travel down the screen, simply increase yVelocity by a gravitational constant in the update call for each raindrop. :)

EDIT: I would recommend that you made Raindrop a class of it's own, as using rectangle directly in that fashion severely restricts what properties you can apply to the raindrops.
> 4 votes

---
Tags: java, android, libgdx
---


# Question
Title: How to run my game outside of visual c++
I am having trouble running my game. It works fine when I run it from Visual C++, but when I try to open the .exe, it complains that it can't find SDL.dll.

What should I do in order to play the game?

# Answer
> 5 votes
IIRC Visual Studio uses a different current directory than the executable.

To fix, include SDL.dll in the same directory as your .exe file, along with anything else you may need. A symlink for this is a good fix, although I think there's also a setting in VS to choose the path.

# Answer
> 0 votes
Find the path to the SDL.dll you're using, let's say it's `C:\Path_To_DLL`.

Possibly, you've added this path in some VC++ directories dialog. So Visual Studio tweaks your `PATH` environment variable before you run the game through it.

Or you've set the working directory for debugging your project to this path: by default all DLLs in the working directory can be loaded.

You've got several solutions:

* As Pubby described, copy SDL.dll or symlink to it in the directory from which you're running your game "externally".
* Start your game from a batch file where you add this path yourself to your path environment variable:

```
RunMyGame.bat:
set PATH=%PATH%;"C:\Path_To_DLL"
start MyGame.exe

```
* Add this path to your global environment variables, in Windows 7 look for "environment variables" in the Windows menu. Then you can just launch your game normally.

# Answer
> 0 votes
Also, consider the possibility of use a installer project offered by Visual Studio. Easy to use and gives you all the necessary stuff to install your games in every MS platform.

# Answer
> 0 votes
Just make sure Visual Studio is set up to run and debug the executable from the directory it is in, and make sure the SDL.dll is also in that directory.

---
Tags: c++, sdl
---


title: Applications of calculus?

text:
# Question
Title: Applications of calculus?
I understand that basic calculus is applicable to game development, particularly physics. Problem is, I'm not entirely sure how. So, what can I use it for? I'm most concerned about what's on the AP tests, as I hear I won't need much more than that;

AP Calculus - AB

I'm particularly interested in hearing examples in terms of gameplay elements.

# Answer
In a game, one of the most basic systems you may come across is Euler's Method. It's a good way of approximating the result of an integration over time. Here is a simple example:

```
Velocity = Velocity + (Acceleration * ElapsedTimeSinceLastUpdate);
Position = Position + (Velocity * ElapsedTimeSinceLastUpdate);

```

Bare in mind that integrating a function of acceleration gives you the function of velocity and integrating the function of velocity gives you the function of position.

This is useful for doing many actions over a period of time.

One of the more common ways I have used calculus however, is simply to prove that an equation I have come up with will work as I intend before I go to the trouble of implementing it.

For example, I once made an equation of velocity which would change an objects orientation over a fixed time period until it had moved to a new desired orientation (it was a bell curve so it would ease in and out of the animation).

By integrating the equation over the fixed period I could show that it would always result in the total change in angle I required. This meant that, with some simple calculus on paper, I could be sure it was worth implementing before I went ahead. It also meant that I had an equation of position which could simply be queried relative to the time since the start of the animation so I wouldn't have to constantly add the velocity onto the position.
> 6 votes

# Answer
Also, 3d programming is relies heavily on multivariable calc and linear algebra. And many complex simulations like fluids use calculus.
> 2 votes

---
Tags: mathematics
---


# Question
Title: Implementing Separating Axis Theorem (SAT) and Minimum Translation Vector (MTV)
I was following codezealot's tutorial on SAT and MTV and trying to implement it myself but I've come a cropper when it comes to getting the correct MTV. Here is my example: (Cue pretty pictures...)

I'm well aware how to obtain the length of the MTV and the axis on which it lies. However I can't work out whether the length should be 'positive' or 'negative' to push the object in the correct direction.

In the example we are separating the objects by moving the 'red' of the 'blue', the top example is moving the object negatively and the bottom moving it positively.

Please help I'm really struggling with this.

Here is my actual implementation.

# Answer
> 3 votes
Well I worked out a way but I'm not sure if it's the best way:

What I did was once I'd found the smallest overlap is check if x1 \< x2 if so the length must be positive else the length must be negative.

It's worked so far and given me satisfactory results.

# Answer
> 4 votes
The solution is to simply turn around the displacement vector (multiply it by -1) if it's pointing towards the shape from which the object needs to be pushed away.

To find out if the displacement vector is pointing towards the shape, you first have to get the general direction from object a to object b by subtracting their centers from each other. After that, you check the dot product between the displacement vector and the direction(a,b) vector that you just created. If it's \> 0, the displacement vector and direction(a,b) are pointing in the same direction, hence you need to flip the displacement vector.

# Answer
> 0 votes
From what is understood, this overlap value should always be positive. The actual direction of the force should be derived from the projection vector (the MTV axis).

Note the interactive example on the page referenced by codezealot (figure 5): http://www.metanetsoftware.com/technique/tutorialA.html

It seems like the actual direction is the MTV axis pointed by where the centers of the objects meet along the axis. Figure 5 of that tutorial is the best illustrator of this. Move the object around and watch the centers of the objects vs an invisible line drawn parallel with the axis from the center of both objects. The direction of the vectors change when the centers cross that line.

---
Tags: collision-detection, physics, vector, collision-resolution, separating-axis-theorem
---


title: A* PathFinding Poor Performance

text:
# Question
Title: A* PathFinding Poor Performance
I'm getting poor performance in-game due to my path-finding algorithm. The farther I get from my NPC, the worse the framerate gets.

Ok, I updated my code and implemented the openList as a min-heap and the closed list as an associative array. As far as I know, it's not possible to grow binary heaps in D so I had to allocate enough space on my openList so that my game wouldn't crash.

Unfortunately, when I fired up my game to test pathfinding, the performance was still bad, despite the openList being sorted by fScore.

I'm not entirely sure what i'm missing. As far as I've read, the main areas for performance are the data structures and the heuristic to an extent.

The heuristic i'm using is Manhattan distance, since my nodes are based upon tiles. My data structures are a min-heap, sorted by fScore, lowest at the front, and an associative array, which I believe is implemented as a hash table in D.

Where is all the performance going?

Are my data structures implemented and used right?

Would it help performance to implement tie breaking with Manhattan Distance?

```
struct Node
{
bool walkable;      //Whether this node is blocked or open
vect2 position;     //The tile's position on the map in pixels
int xIndex, yIndex; //The index values of the tile in the array
Node*[4] connections; //An array of pointers to nodes this current node connects to
Node* parent;
int gScore;
int hScore;
int fScore;
}

class AStar
{
private:
bool[Node] closedList;

Node currentNode;           //The current node being processed

Node[] Path;        //The path found;

const int connectionCost = 10;

Node start, end;

//.... other functions omitted here//

public:
void FindPath( vect2 vStart, vect2 vEnd, Node[] PathGraph )
{
    Node[] a;
    a.length = 3000;
    auto openList = BinaryHeap!(Node[], "a.fScore > b.fScore")(a, 0);
    closedList.clear;

    SetStartAndEndNode( vStart, vEnd, PathGraph );
    SetStartScores( start );
    openList.insert( start );

    while( currentNode.position != end.position )
    {
        currentNode = openList.front();
        openList.removeFront();

        if( currentNode.position == end.position )
            break;
        else
        {
            closedList[currentNode] = false;

            for( int i = 0; i < currentNode.connections.length; i++ )
            {
                if( currentNode.connections[i] is null )
                    continue;
                else
                {
                    if( IsInList( closedList, *currentNode.connections[i] )
                       && currentNode.gScore < currentNode.connections[i].gScore )
                    {
                        currentNode.connections[i].gScore = currentNode.gScore + connectionCost;
                        currentNode.connections[i].fScore = currentNode.connections[i].gScore + currentNode.connections[i].hScore;
                        currentNode.connections[i].parent = &currentNode;
                    }
                    else if( IsInList( a, *currentNode.connections[i] )
                            && currentNode.gScore < currentNode.connections[i].gScore )
                    {
                        currentNode.connections[i].gScore = currentNode.gScore + connectionCost;
                        currentNode.connections[i].fScore = currentNode.connections[i].gScore + currentNode.connections[i].hScore;
                        currentNode.connections[i].parent = &currentNode;
                    }
                    else
                    {

                        currentNode.connections[i].gScore = currentNode.gScore + connectionCost;
                        currentNode.connections[i].hScore = abs( currentNode.connections[i].xIndex - end.xIndex )
                            + abs( currentNode.connections[i].yIndex - end.yIndex );
                        currentNode.connections[i].fScore = currentNode.connections[i].gScore + currentNode.connections[i].hScore;
                        currentNode.connections[i].parent = &currentNode;
                        openList.insert(  *currentNode.connections[i] );
                    }
                }
            }
        }
    }

    writeln( "Current Node Position: ", currentNode.position );
    writeln( "End Node Position: ", end.position );

    //if( currentNode.position == end.position )
    //{
    //    //writeln( "Current Node Parent: ", currentNode.parent );
    //   //GeneratePath();
    //   //ReversePath();
    //}
}

```

}

This is my first attempt at A\* so any help would be greatly appreciated.

# Answer
> 2 votes
Like others have said, simplify your algorithm. It's ok to make a crude implementation and use interpolation to smooth it out later. Maybe also increase the size of each search block and if something is past a certain distance, don't pathfind. And it would probably be best if you cache your path unless your position changes and only recalc if the player moves away from the path.

---
Tags: ai, path-finding
---


# Question
Title: Games with rubbing/scratching as interaction?
I'm brainstorming a game aimed for touchscreen. Its primary interaction involves a lot of rubbing and scratching with the finger to the on screen objects, sort of like Fruit Ninja, but a bit more work than a single swipe. I recall there are somewhat similar operation in Rayman Raving Rabbid that uses Wiimote to draw shapes.

At this stage, the interactions in my mind looks repetitive and unappealing. I'm trying to find similar examples that appear repetitive but still fun to play. Besides these two, are there any others?

# Answer
Go out in the real world and observe things with rubbing or scratching. Proceed to translate into game ideas.

Things that come to mind...

* Pet a cat
* Scratch a dog's ear
* Itch (Itching with Friends?)
* Lottery tickets
* Polishing silver
* Washing dishes
* Wash floors / wipe down counters
* Sex (self, with others)
* Spot of food on shirt just before meeting
* Runny nose
* Bathroom
* How does my monitor get so messy? What's with these fingerprints! Ugh - it's not a touch screen!
* Brush teeth
* Wash hair (lather, rinse, repeat)
* Chipping old paint
* Washing cars
* Butler ("Sir, a speck of lint on your shoulder *flick flick*")
> 5 votes

# Answer
A lot of DS games use this mechanic, Cooking or Crafting Mama would be good examples, and lots of other girl's games. I think key ways to make this mechanic fun are to have particles/good feedback while rubbing and a rewarding reveal once the rub has finished.

Tim's suggestion is spot on, the "fun" from doing these things is how it mimics real life.
> 1 votes

---
Tags: game-design, game-mechanics
---


# Question
Title: What's an appropriate difficulty scale for weapon efficacy vs difficulty to obtain?
I'm writing up a design document for a voxel based adventure game, similar to minecraft, but fixing a lot of fundamentally broken game mechanics, or at least updating those mechanics to be more suited to an adventure game.

I'm considering creating a weapon scale from 1-10, where weapons at 1 are least powerful, and weapons at 10 are most powerful. I was considering making the materials to make the weapon most common for the level 1 weapons, and 10x less common for the most powerful weapon, but if you look at minecraft, diamonds only occur in 0.1% of blocks and they still feel too common, unless you're prone to dying of course.

In keeping with the adventure focus, would it be better to have the higher tiers of weapons only come from monster drops, or from a combination of a rare monster drop and a mineable item, or are there other common game mechanics I could use to have a super powerful weapon that's also hard to get, but worth your time to get?

To state the question another way, for the time investment, should a weapon that's 10x as powerful take 10x as long to obtain, or 20x or higher? **Are there any studies that show any correlation between "fun" in how long players will grind for an item and an appropriate time investment scale for obtaining equipment?**

# Answer
> 11 votes
I'm going to answer this orthogonally:

> **Whatever you choose will be wrong.**

No matter how carefully you crunch the math, or read the studies, the numbers that you will choose before play-testing will be wrong.

The only way to determine what the appropriate amount of grind for the particular game, play style, users and interface is to actually try it and iterate, while maximising for player fun (or your profit...)

> **Corollary: Make sure that changing these numbers is easy!**

What this means is that these numbers are going to be changed. A lot. So you better make sure that you don't have to re-compile your game or dig through your code for the balancing magic numbers.

## Option 1

Pick whatever feels right when you're implementing, but put it into a reloadable config file. (`.ini`, JSON, XML, S-Exprs, whatever tickles you best...) And make sure that you can reload your config without having to re-write most of your game.

## Option 2

Make the probability of an item a direct function of its level. That way, you can modify the function later on, and you don't have to deal with a bunch of variables. For example:

```
#
# Power on a scale up to 10.
#
# Examples of probability scaling function
#

def probability_of_v1(power):
  """ series """
  a, b, c, d = (1,4,16,210)
  return a - x/b + (x^2)/c - x^3/d

def probability_of_v2(power):
   """ linear """
   return 1 - (power/10)

def probability_of_v3(power):
   """Sinusoidal, starts at 1, is 0 at power=10"""
   return 0.5 * cos( x / pi ) + 0.5

#
# Then, use your function instead of your probability
# when dropping loot or creating gems
#
class Monster:
  # ...
  def on_die(self):
    if random.random() < probability_of(self.power):
      self.drop_loot()
    else:
      pass
  # ...

```

Try the equations out online to see what they look like.

# Answer
> 7 votes
It's hard to give a definitive answer, as this is very dependent on how you want the game to play.

However, Terraria did experiment with these ideas that you mention. They increased the amount of materials needed to create weapons, armour etc. (this was somewhat balanced out by the fact that materials were often found in sizeable clusters). They also implemented rare and common monster drops too, which were only obtainable via drops.

It would be worth your while to research Terraria a bit more, to see how it feels to have these mechanics in place; then I'm sure you will be better positioned to make the decision on how you want to balance item drops and material distribution.

# Answer
> 4 votes
There isn't a right answer. Some good games are hard, some are easy. Some gamers like recurring challenge, some like quick rewards. I think that the right answer lies with finding your potential crowd, first. Once you have an alpha version, find someone of the general mindset you hope your game's crowd will have, and let them play it. As long as you code correctly, adjusting the variables later on shouldn't be hard, and play-testing and balancing are stages that you should have, even if you think you've hit the golden ratio or not.

So don't sweat the numbers while you're programming - there's no theoretical right answer, and later on you'll have concrete testers' answers.

But, if you still want to try to hit magic numbers, studies have shown that grinding (mining, in this case) is only effective as long as it is within the player's set time expectation. The more a player spends time, the longer he can wait for the next reward, but it should always be within a reachable time-frame, no more then a magnitude greater then the last time-frame before the last reward. So, I think that a 10x increase in time is suitable, but I don't think that the difference between two weapon levels should be 10x - the gap between levels is left quite wide.

Good luck!

---
Tags: game-design, game-mechanics
---


# Question
Title: What kind of questions should I ask players in a survey after the game?
I'm finishing a HTML5 browser game, and I'd like to have some player feedback. I was planning to make players take a short survey at the end of the game. Is this the best approach? How long should it be? Should I just let them write about the game instead of answer questions?

What are good questions to ask and how?

For example, do I let them write about physics, do I let them just choose "GOOD" or "BAD" or do I have a scale from 1 to 10?

# Answer
> 4 votes
This question is a bit case-specific (and vague at that), but an interesting topic.

In general, I think most players (esp. for a casual game) wouldn't really be able to pick out what is and is not physics in the game, much less give you any useful feedback on it. This probably holds true for most aspects of a game. Even if you were to ask them how much they like the graphics, how are you going to use that feedback constructively?

Lets use your example, and say you collect a thousand responses to a rating of 1-10 for physics, and that you get an average of 7.0. What would you do with this? The only conclusion you could really draw from that (and you'd be basing it on low quality information) would be that you should sort-of spend more time on your physics implementation.

I like what Realm of the Mad Gods does. After you play for a bit, it gives you a really simple popup that asks two things: rate how fun the game is on a scale from 1-5, and explain what you like least about the game. I think the average person would do a much better job assessing how much fun they had than assessing the quality of something they really don't understand. And asking specific, simple questions about things that stand out (what did you like the least?) does two things: (1) it gives you a chance to gauge the quality of the response, and (2) it points you in a specific direction with a specific purpose.

# Answer
> 5 votes
Ideally I would recommend a video recording of both player's face and his gameplay. In my experience this tells much more than any survey.

But I guess that's impossible, I usually recommend 5(Very Bad, Bad, Normal/No opinion, Good, Very Good) or 3(Bad, Normal/No opinion, Good), 10 in my experience tend to confuse people unless they are professional gameplay/prototype/alpha testers.

Questions about technical aspects might be dangerous, since players don't always know what hooked them up to a game, so I wouldn't ask about things like physics unless it's a physics puzzle like Angry Birds game, but I wouldn't ask about physics in say racing game.

If testers aren't paid I would also recommend to make a list of 3-6 most important questions, and put everything else in "optional part".

# Answer
> 4 votes
I have done a fair amount of play-testing, and those surveys tend to ask general what do you think of the game, and then go into specific details about specific things they are probably concerned about.

if your concerned about what people think of the physics in a platformer then don't ask "how would you rate the physics" ask "what did you think of how the character jumped/fell"

you can use scale values, but the data needs to be usable. if you just ask about physics, or graphics it is likely that Sallies Mom doesn't know what your talking about, or what it affects, and even if your giving a scale question then put something for "didn't notice" "don't know" some times if some one doesn't notice something as odd they will just think it is normal, and wont even register it.

then by asking specific questions like "what do you think about X" if you get a high density of complaints then it is something you might want to take a serious look at.

though remember that art is primarily for the artist, and then for the customer.

---
Tags: community-management
---


title: Creating thrusters on a ship in Unity3D

text:
# Question
Title: Creating thrusters on a ship in Unity3D
So, I'm using the legacy particle "small flames". Basically what I want it to do is always emit below the ship, so when the ship turns and such it still looks like the thrusters are firing.

I know adjusting the World Velocity Y can adjust what direction the particles throw, but what I'm wondering is how do I always get what direction the back of the ship is facing, so I know what direction to emit the particles in? It doesn't have to use World Velocity, it could use rotation or some such, I just can't figure this out.

# Answer
As we talked about in the comments, turning off "simulate in world space" will likely fix the issue.

http://unity3d.com/support/documentation/Components/class-EllipsoidParticleEmitter.html
> 2 votes

---
Tags: c#, unity, particles
---


# Question
Title: Erasing part of lines in libgdx with ImmediateModeRenderer
Hi i'm using the `ImmediateModeRenderer renderer = new ImmediateModeRenderer10();` to render a line with the next block

```
renderer.begin(matrix, GL10.GL_LINES);
    renderer.color(color.r, color.g, color.b, color.a);
    renderer.vertex(x0, y0, 0);
    renderer.color(color.r, color.g, color.b, color.a);
    renderer.vertex(x1, y1, 0);
renderer.end();

```

But know I want to erase some part of that line when I drag the mouse over it, are there any ideas ?

# Answer
If you want to erase part of the line when you drag the mouse over it, there's two ways:

### The cheating way

Have a background with a solid color, and have the mouse create lines/shapes of that color over your existing line. The player will be given the illusion of the line having been erased, though this approach might fall down on its face if you're trying to do anything reasonably complex.

You could also have a background with a texture, and give it an identical foreground (which is completely transparent, and mouse clicks add to its transparency mask).

### The non-cheating way

Detect where the mouse has intersected the line and break the line in two pieces, leaving you drawing multiple lines after multiple erasures (all parallel).

To detect this, each frame, you should determine the vector between the mouse's current position and its position in the previous frame and determine if the line of this vector intersects with the line you've drawn. If so, split the line on the intersection point into two lines, then shorten both slightly (otherwise your erasing will appear to do nothing, since both lines are still perfectly joined).
> 3 votes

---
Tags: opengl, rendering, libgdx
---


# Question
Title: How do I break an image into 6 or 8 pieces of different shapes?
I am working on puzzle game, where the player can select an image from iPhone photo gallery. The selected image will save in puzzle page and after 3 second wait the selected image will be broken into 6 or 8 parts of different shapes. Then player will arrange these broken parts of images to make the original image.

I am not getting idea how to break the image and merged so that player arrange the broken part. I want to break image like this below frame. I am developing this game in cocos2d.

# Answer
> 5 votes
Since you have pre-made break patterns. All you really need to do is collect a sub-image for each one to show.

This would likely be easiest to do with a rectangle for each shape. The rectangle should encompass the entire shape. Now break the image up into these rectangles. There will be overlap. Now apply an alpha mask to each rectangle to hide everything but the shape it's encompassing.

For example some of the rectangles would look like this:

Then, for example, the texture for the black rectangle would be the portion of the image that is contained by the black rectangle. Then when that is masked out, only the shape portion of the image would remain.

---
Tags: ios, cocos2d-iphone, objective-c
---


# Question
Title: Android APK export duplicating libgdx assets folder
I'm developing a game using libgdx targetting Java desktop and Android. For the assets I have a "data" folder inside the "assets" folder in the Android project. Then, I link it from the desktop project.

My problem comes when I export, my .apk contains:

```
assets
com
lib
data
META-INF
res
AndroidManifest.xml
resources.arsc
classes.dex

```

This means my data files are duplicated in "assets/data" and "data" being the first one the only relevant one. This increases my APK size from 5 to 10MB which is kind of annoying. In my file system I only have the "assets/data" folder, no trace of the intruder there.

Does someone have any ideas why is this happening? How can I solve it?

PS: I've tried deleting the intruder manually opening the apk with 7zip but that destroys the checksum and prevents updates to be properly installed (needs complete reinstall).

# Answer
> 1 votes
Finally I found the source of the problem. The Android project was linking against the desktop one to fetch the code and the libgdx libraries. I guess the APK exported saw that and simply copied the whole thing. This includes the link to the data folder in the desktop project, therefore the undesired duplicity.

Solution:

Just create a different project layout:

* mygame: shared code and base libs.
* mygame-desktop: desktop started, linked assets, desktop specific libs.
* mygame-android: Android Activity, original assets, Android specific libs.

---
Tags: java, android, libgdx
---


# Question
Title: Where to start the coding of online leaderboards?
I NEVER, EVER did ANY sort of network code in C++, I don't know even the libraries that exist, but a popular demand for my game is online leaderboards...

So, what sort of libraries I should research into?

My game is multiplatform (win, gnu, mac), uses C++, ClanLib 1.0 and Lua. Also the engine is zlib (so proprietary stuff that I cannot release source don't work)

# Answer
> 6 votes
First question, how much do you care about cheating? Making a simple webapp for leaderboards is probably pretty easy, but it will instantly be spammed out of existence. I would look at curl as a decent async HTTP library that you should be able to integrate into just about any client code. For the server side, I assume you have no budget for dedicated servers, so Google App Engine might be a good match if you know either Python or Java.

# Answer
> 3 votes
It all begins with protocol design. What do you need to transmit over the wire? What kind of handshakes and verification mechanisms are needed? It could be as simple as a network packet is sent every time a game is over. It would simply contain the username with the score, for example `{ "Joel", "33" }`

The problem is that how do you confirm the score was achieved in a legitimate way? Perhaps someone simply analyzed your protocol packets with a network analyzer and concluded that only a username with the score is sent. Then he manually creates this packet and sends it. This is what coderanger meant by "getting spammed out of existence".

As for storing the leaderboard itself, I would recommend using a database, like SQLite. This gives you thread-safe and concurrent saving/access mechanism to the leaderboard. The underlying database takes care of synchronization.

For the networking code itself, you need two parts. Something to send the data to the server and something that consumes and processes it at the server side. As coderange mentioned, it could be something as simple as HTTP/XML/JSON HTTP GET/POST and then a web server running on server side would consume that in a web service. The good part is that you don't have to deal with any of the networking code for the server's side as that is taken care of by the web server.

# Answer
> 1 votes
From my experience there are multiple steps you will have to go through. Choosing C++ libs is not the most pressing of them. There are more important things you will have to consider.

## Hosting

Concerning the hosting of your leaderboard you will have to make a choice. Either you rent servers and you can chose the technologies you want and do what you want. Or you rent hosting space and you will have to work with the techs at your disposal. Or you will use one of the cloud solutions and have to work with the constraints and advantages of those.

It's all a question of cost time investment and reusability. If you already have server you can try to host your leaderboards there, if you already use a hosted site you can start prototyping with that.

Personally I would recommend renting a server or a virtual server at first.

This question deserves a thread of its own and should be answered independently if you have a hard time dealing with it.

## Service

Which server technologies you will use is up to you and depends heavily on the hosting solutions you will choose.

**DB**

Of course you can start with an SQL storage, MySQL is pretty cheap efficient and simple to use, supported by most hosting providers. This is the solution I have been using. But beware when it comes to scalability you might regret using it later.

There are other better solutions. ERLANG based DB servers like CouchDB are quite popular. One of them, **RIAK** is simple to distribute across multiple servers, efficient, uses JSON and is used by big names like Mozilla and GitHub.

**Back-end**

You will not give access to your data storage directly from your client apps. You will need to write an application to manage authentications, authorizations, some logics and DB access.

Java, PHP and perl are often used to write web services which provide these functions, are well supported by hosting providers and have strong dev communities.

But if you want to avoid the overhead of a full fledged HTTP server like Apache you should use **nodeJS**. It is a very efficient low footprint and fast solution. Used by e-bay, Microsoft and Linked-In. It integrates very nicely in setups that use JSON for data exchange.

## Design

Your leaderboard design will start with the data storage. What do you want to store. How do you want to store it and for how long?

You want to store the scores of course (time, distance, points...), but with that do you have multiple levels? then you will need to store the level IDs, do you support multiple platforms? If so the difficulty of the game might be different on different platforms for technical or demographical reasons, will you store that too...

How do you want to sore it? Do you want to keep only the best scores, replacing all previous ones done by the player on the same platform/level/context? Or will you store everything to keep track of all the possible scores? Will you hold on to discarded previous scores for data mining?

Once you answered these questions you can start thinking about the implementation.

## Protocol

You will want to transfer data from and to the clients. For this you will have to create a good communication protocol.

The choice of the underlying protocols is secondary in this step (HTTP, TCP, UDP). Whatever your choice is you will have to craft your own protocol carefully so you will be able to handle errors, changes in the protocol, application updates, etc...

So make sure your server application can handle providing data to applications which are updated and applications which run older versions as well.

Make sure to protect the data transferred to and from the server. Be careful about protecting score uploads, you can use hash keys, encryption and other mechanisms to protect your server from cheaters.

Wherever you chose to send binary or text (JSON, XML) data is up to you. But for flexibility and compatibility I would recommend JSON. Avoid XML. Use binary if you really need/want it.

This topic deserves more attention and you might have more questions...

## Client

The client will have to integrate with your solution. You should not chose your server tech and protocol layers based on the client's language. You should integrate your server solution to your game.

If you chose JSON over HTTP there are libs for that.

There are C/C++ libs for JSON, I would recommend using them. You can write your own if you like. I wrote a small JSON lib in a matter of hours. It's now used in games across dozens of platforms.

Concerning HTTP in C++ use something more modern than CURL. **cpp-netlib** should do.

Beware of the character encodings etc when sending the data though.

## Authentication

To be able to store and display best scores for your users they will have to be identified somehow. There are multiple ways.

The simplest being none. Use the Enter Name Here field to display the names on the leaderboard.

You can also ask the players to register... this is often a process which discourages players.

One way I used a lot is Facebook authentication. This way you can pass the auth data to or through your server and get data about the friends and serve personalized leaderboards i.e. Global leaderboard, friends leaderboard...

# Answer
> 0 votes
Client side: The application or game uses a http lib like libcurl or the sfml-network package. Server side: A simple solution with php and mysql, postgresql or sqlite3. The php files are hidden or inaccessible to the user.

---
Tags: c++, networking, online, leaderboards
---


title: Game Sprite Editting Help(PNG-XNB)

text:
# Question
Title: Game Sprite Editting Help(PNG-XNB)
I converted my project's .xnb files to .png files using a program and I can't seem to find a way to transform .png back to .xnb. I don't want to lose the work I've done. How can I change the images back?

P.S. GXView shows an error when I try to save as .xnb

# Answer
You can convert PNGS to XNBs by adding them to your content project in your XNA solution. You do this by right-clicking on the content project in the project explorer (right side) in Visual Studio and choosing Add-\>Existing. Now each time you build the solution (F5) the XNB files are created.

As far as I know you can not (easily) manually create XNB files from PNGs (or other assets) because XNB files are associated with a specific game, XNB files are a sort of protected/compressed archive for a series of assets and thus can contain more than 1 file.

About GXView, I don't know that program, but if you think that software could help you, but gives an error, could you post the error message, maybe we can help you out.
> 8 votes

# Answer
Not sure exactly what you are trying to do here. Are you modding an XNA based game such as Terraria? Anyways check XNA 4.0 Content Compiler.
> 0 votes

---
Tags: 2d, textures
---


# Question
Title: How do I implement delta-only data packet updates in UDP?
**Edit:** My current system is going to be to send constant player updates every 1/20th of a second, each containing the player's status and position. I will also send another packet (or as many needed) every 1/20th of a second with the information of all the bullets, using this format to save space (the number representing the space in a packet):

```
1: Owner's ID
1: Type
1: Amount of bullets (so I don't have to include this info each time)

3: X coord
3: Y coord

```

I am currently writing a co op game to play at LANs, and have run into the issue of dealing with many entities and game updates. I only have implemented player movement, and the packets sent include the player's position for 3 ticks (as packets are sent and received every 3 ticks).

I have also implemented a system to keep track of the delay between client and server (sending the tick the server/client is at and comparing it to with the receiver's local tick).

This has worked thus far, however I have run into trouble with sending bullet information. It would be unfeasible to send the position of the bullet every update, as I would only have room for ~160 bullets + players per packet.

I thought of just sending the information that a bullet has been created and enough information for the client to simulate the bullet flying, such as velocity, angle, lifetime, and owner, and sending information when the bullet has been destroyed (via impact, lifetime, or otherwise). This got me thinking if it is possible to only send the keystates of a client to other clients via the server, to reduce the space required for co-ordinates and to increase smoothness of movement(floats will be used in this case instead of the current ints, as I have found difficulty transmitting floats).

This raises the concern of packet loss, and that with it the game could easily go out of sync. I have read of sending acks, however I am unsure if this will give me the wanted result. I have also read about sending a full game state ever so often, and this seems to me to be the best solution. What should I do to fix the issue of space and to reduce the space required for transmitting movement? And if it's the full game state solution, how often should I resync the clients? 5 seconds? 10 seconds? How do other games do it? I have read that the steam engine almost never does this, however it has many systems set in place to prevent packet loss and resending lost packets and I feel that I am unable to code all that.

# Answer
First, don't send input-state.. send the computed output (eg, position and possibly velocity) instead. Keeping all participants in sync will be *much* simpler that way.

If you're just sending position, deltas aren't going to necessarily get you a smaller packet size. You're still going to have to send a 3 (or 2 for a 2D game) values, but the difference is that the origin is from the last guaranteed-known position. What this *does* get you is the ability for more precision in less bits.. the further from the origin you are, the more bits of precision you need to accurately represent a position, and it's more likely that a player is closer to its last position than to the scene's origin.

Unless your scenes are quite big, however, i wouldn't worry about trying to shave a few bits off there, and would stick to an absolute position with three floats, or the like.

Where I might shave things off if you're worried about bandwidth usage, however, is by having different messages for position vs. other state updates. As you start adding other state that needs to be synced between machines, send that extra data less frequently, and in a different message than your position updates.

As far as amount of space per-packet goes, I'd recommend not trying to fit everything in a single UDP packet. Send position, bullet creation, and other data as discreet messages, which are carried in UDP packets. (One message per packet is the simplest way to go, and probably the easiest to start with. If you find yourself sending lots of very small packets, you can optimize by batching up as multiple messages per packet later on.) Then, you can still send your position messages at a fixed rate, but you can send events like bullet creation as soon as they happen, instead of adding 3 ticks of latency to them.

"I have read of sending acks, however I am unsure if this will give me the wanted result."

If you're using UDP, you're going to need to implement *some* sort of acks or retransmission control for your game, as there are some messages you will need to make sure get through (eg, bullet creation). There are a number of networking middleware libraries that will implement this for you, but it's also not too hard to implement a basic version on your own.
> 4 votes

# Answer
Delta's are a very very rare thing in networking in games as far as I can tell. They almost always run into syncing issues. Most of the time when you see a person do some funny sliding or the like, its not because a delta system is being used and then corrected at intervals. In general its because of a momentary packet loss of some kind, even if its just delayed data, and then a forced correction on top of the predictive side of the networking. So I actually suggest that you look into manners of packet compression as opposed to delta networking.

Some things to consider:

* Only send updates for things that actually updated this frame.
* Do send the updates right when they happen.
* Consider some kind of bit packer. I personally recommend Arithmetic Encoders. The article here was very valuable in creating a couple of versions of these over the years. They work fairly well at compressing numerical data with out too much overhead processing.

I do want to once again caution against using a 'just send critical events' sort of system.. Every time I have dealt with a system like that it has caused a significant amount of effort to try and keep in sync and at the end of the day has always been changed into an exact system.
> 2 votes

# Answer
Concerning delta updates you have to do something like this:

1. Send the latest gamestate (A)
2. Store the current gamestate (A)
3. next time you send an update you get the delta between the gamestate (A) and current gamestate (B)
4. Store the current gamestate (B)
5. When you receive an ACK for a gamestate you release all previous versions. ex ACK (B) release gamestate (A)
6. When it's time to send the current gamestate (C) send the delta between (B) and (C)
7. Store (C)

This is a single player scenario. You have to keep count of which gamestate is the latest version on which client. And you release all gamestates older than the latest one acknowledged by all clients.

There is data you should consider sending more often than other if you don't want to use deltas. Fundamentally the client apps must always receive data from the latest server tick about:

* Current player positions
* Changes on health/situation

They should receive as often as possible data about:

* impacts and movement (animations) within perception range (visual and sound)
* game objects visual/animation data.

If your bullets/projectiles are visible then the creation time, and data like type, position and direction are enough. Your client should know which type travels at which speed. Also you can do bulk updates ex:

30 new bullets created would become an array of \[owner, time, position, direction\] you don't need the type and other data as you can get those from the time created and owner. You must then also timestamp weapon switches.

If you still have trouble with packet sizes then compress the data sent from the server.
> 0 votes

---
Tags: c++, networking
---