# Question
Title: Choosing the correct network protocol for my type of game (its Wc3 Warlock style)
I need to code a little game for a school project.

The type of the game is like the Warcraft 3 map "Warlock", if anyone doesnt know it, here is a short description: up to ten players spawn into an arena filled with lava, the goal of each player is to push the other players into the lava with spells (basically variations of missiles, aoe nukes, moba spells etc)
http://www.youtube.com/watch?v=c3PoO-gcJik&feature=related

we need to provide multiplayer-support over the internet, for that reason I am looking for the best network protocol for this type of game (udp, tcp, lock step, client-server...)

what the requirements are:
\- same/stable simulation on all clients
\- up to ten players
\- up to ~100 missiles on the field
\- very low latency since its reaction based (i dont know the method wc3 used, but it was playable with the old servers)

what would be nice (if even possible, since the traffic might be too big):
\- support for soft bodies over the network (with bullet physics), but this is no real requirement

I read several articles about the lock step method used for RTS games, this seems to be great, but does it fit for real-time action games too (ping-related)?

If anyone has run into the same problems/questions like me, I would be very happy about any help

# Answer
The TCP vs UDP debate is full of subjective arguments, speculation, and flawed benchmarks. "Is the TCP protocol good enough for real-time multiplayer games?" has some answers. Browse through our networking tag to see more questions that might have answers to further help you. This is really a case where you need to do your research, understand what each protocol gives you and what its potential negatives are, hypothesize on which one is better for your purpose and execute on it, and then either live with the decision, or experiment/backpedal to decide if the other protocol would have been better. Then write a postmortem and post it on the internet, so that we can have a bit more quantitative data to feed into the TCP vs. UDP debate.

In other words, **do some research, and then just pick one.**

The same applies to client/server vs peer-to-peer network architectures. They have pros and cons which are a little too much to list in an answer, and you could quickly do some searching and find this information to make your decision. A game *could* be made either way, and you should decide which one you think is best for your purpose. I think I can safely say, though, that client-server will be much easier to enforce a "same/stable simulation on all clients" situation than peer-to-peer.

For the sake of decisiveness, I would recommend using TCP so that you don't need to go through the trouble of implementing TCP's reliability and ordering on top of UDP, and client-server so that you don't need to figure out how to synchronize the peers, deal with bad data, etc. Alternatively, you could look into game-oriented network libraries that are out there and choose one of them to use, if you're comfortable with that.
> 2 votes

---
Tags: networking, protocol
---


# Question
Title: Object detection in bitmap JavaScript canvas
I want to detect clicks on canvas elements which are drawn using paths. So far I have stored element paths in a JavaScript data structure and then check the coordinates of hits which match the element's coordinates. Rendering each element path and checking the hits would be inefficient when there are a lot of elements. I believe there must be an algorithm for this kind of coordinate search, can anyone help me with this?

# Answer
You should probably take a look at engines that already do that like:

But I'm pretty sure they maintain some state relative to position and shape and check against those for every frame update.
> 2 votes

---
Tags: algorithm, javascript, data-structure
---


# Question
Title: Trouble with AABB collision response and physics
I have been racking my brain trying to figure out a problem I am having with physics and basic AABB collision response. I am fairly close as the physics are mostly right. Gravity feels good and movement is solid. The issue I am running into is that when I land on the test block in my project, I can jump off of it most of the time. If I repeatedly jump in place, I will eventually get stuck one or two pixels below the surface of the test block.

If I try to jump, I can become free of the other block, but it will happen again a few jumps later. I feel like I am missing something really obvious with this. I have two functions that support the detection and function to return a vector for the overlap of the two rectangle bounding boxes. I have a single update method that is processing the physics and collision for the entity.

I feel like I am missing something very simple, like an ordering of the physics vs. collision response handling. Any thoughts or help can be appreciated. I apologize for the format of the code, tis prototype code mostly.

The collision detection function:

```
public static bool Collides(Rectangle source, Rectangle target)
    {
        if (source.Right < target.Left ||
            source.Bottom < target.Top ||
            source.Left > target.Right ||
            source.Top > target.Bottom)
        {
            return false;
        }

        return true;
    }

```

The overlap function:

```
public static Vector2 GetMinimumTranslation(Rectangle source, Rectangle target)
    {
        Vector2 mtd = new Vector2();

        Vector2 amin = source.Min();
        Vector2 amax = source.Max();
        Vector2 bmin = target.Min();
        Vector2 bmax = target.Max();

        float left = (bmin.X - amax.X);
        float right = (bmax.X - amin.X);
        float top = (bmin.Y - amax.Y);
        float bottom = (bmax.Y - amin.Y);

        if (left > 0 || right < 0) return Vector2.Zero;
        if (top > 0 || bottom < 0) return Vector2.Zero;

        if (Math.Abs(left) < right)
            mtd.X = left;
        else
            mtd.X = right;

        if (Math.Abs(top) < bottom)
            mtd.Y = top;
        else
            mtd.Y = bottom;

        // 0 the axis with the largest mtd value.
        if (Math.Abs(mtd.X) < Math.Abs(mtd.Y))
            mtd.Y = 0;
        else
            mtd.X = 0;

        return mtd;
    }

```

The update routine (gravity = 0.001f, jumpHeight = 0.35f, moveAmount = 0.15f):

```
public void Update(GameTime gameTime)
    {
        Acceleration.Y = gravity;
        Position += new Vector2((float)(movement * moveAmount * gameTime.ElapsedGameTime.TotalMilliseconds), (float)(Velocity.Y * gameTime.ElapsedGameTime.TotalMilliseconds));
        Velocity.Y += Acceleration.Y;

        Vector2 previousPosition = new Vector2((int)Position.X, (int)Position.Y);

        KeyboardState keyboard = Keyboard.GetState();
        movement = 0;

        if (keyboard.IsKeyDown(Keys.Left))
        {
            movement -= 1;
        }

        if (keyboard.IsKeyDown(Keys.Right))
        {
            movement += 1;
        }

        if (Position.Y + 16 > GameClass.Instance.GraphicsDevice.Viewport.Height)
        {
            Velocity.Y = 0;
            Position = new Vector2(Position.X, GameClass.Instance.GraphicsDevice.Viewport.Height - 16);
            IsOnSurface = true;
        }

        if (Collision.Collides(BoundingBox, GameClass.Instance.block.BoundingBox))
        {
            Vector2 mtd = Collision.GetMinimumTranslation(BoundingBox, GameClass.Instance.block.BoundingBox);

            Position += mtd;

            Velocity.Y = 0;
            IsOnSurface = true;
        }

        if (keyboard.IsKeyDown(Keys.Space) && !previousKeyboard.IsKeyDown(Keys.Space))
        {
            if (IsOnSurface)
            {
                Velocity.Y = -jumpHeight;
                IsOnSurface = false;
            }
        }

        previousKeyboard = keyboard;
    }

```

This is also a full download to the project. https://www.box.com/s/3rkdtbso3xgfgc2asawy

P.S. I know that I could do this with the XNA Platformer Starter Kit algo, but it has some deep flaws that I am going to try to live without. I'd rather go the route of collision response via an overlay function.

Thanks for any and all insight!

# Answer
I have found the solution myself.

Basically, I reordered to have all input, velocity adjustments and position adjustments before the collision detection and response correction. Once I did that, it was able to correct my position appropriately. I had my jump handling at the end of the update, and I think that was interfering with collision response adjustments. I also quit applying gravity unless I wasn't colliding with anything, or if I was colliding, only apply gravity if it wasn't on the Y axis.

I am not jumping about with zero sticking!
> 2 votes

---
Tags: 2d, collision-detection, physics, platformer, aabb
---


# Question
Title: How to determine the end of list has been reached?
I'm trying to animate my object according to a set of recorded values from kinect skeleton stream by saving the (x,y,z) stream from the skeletal data into a list and then set my objects x and y position from the x,y of the list. However, once the list end has been reached it starts to animate again from the start. I don't want that - I just want the model position to keep going in the positive X direction. Is there any way I can check if end of the list has been reached and to just update the model position in x direction?

Or is there any other way to continue moving my sprite once the points in the list are over... i dont want it to start animating all the way again..

```
   protected override void Update(GameTime gameTime)
        {

            //position += spriteSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;

            //// TODO: Add your update logic here
            using (StreamReader r = new StreamReader(f))
            {
                string line;
                Viewport view = graphics.GraphicsDevice.Viewport;
                int maxWidth = view.Width;
                int maxHeight = view.Height;

                while((line = r.ReadLine()) != null)
                {

                    string[] temp = line.Split(',');

                    int x = (int) Math.Floor(((float.Parse(temp[0]) * 0.5f) + 0.5f) * maxWidth);
                    int y = (int) Math.Floor(((float.Parse(temp[1]) * -0.5f) + 0.5f) * maxHeight);

                    motion_2.Add(new Point(x, y));
                }

            }

                position.X = motion_2[i].X;
                position.Y = motion_2[i].Y;

            i++;

            a_butterfly_up.Update(gameTime);

            a_butterfly_side.Update(gameTime);

            G_vidPlayer.Play(mossV);

            base.Update(gameTime);
        }

```

# Answer
> 3 votes
Problem solved. . . I have used int count; instead of i in the above code

```
        if (++count >= motion_2.Count)
        {
            position.X--;

            if (position.X < -200)
            {
                count = 0;
            }
        }

        else
        {
            float x = (float)((motion_2[count].X * 0.5f) + 0.5f) * maxX);
            float y = (float)(((motion_2[count].Y * -0.5f) + 0.5f) * maxY);

            position.X = x;
            position.Y = y;
            scale = (float)motion_2[count].Z;

        }

```

---
Tags: c#, xna-4.0
---


# Question
Title: Multithreaded game fails on SwapBuffers in render thread at exit
The render loop and windows message loop run on separate threads. The way the program exits is that after PostQuitMessage is called in WM\_DESTROY the message loop thread signals the render loop thread to exit. As far as I can tell before the render loop thread can even process the signal it tries SwapBuffers and that fails.

My question, is there something about how Windows processes WM\_DESTROY and WM\_QUIT, in maybe DefWindowProc that causes various objects associated with rendering to go away even though I haven't explicitly deleted anything? And that would explain why the rendering thread is making bad calls at exit?

# Answer
> 3 votes
I've run into something sort of similar, and the quick answer is that once windows starts processing the quit, you don't have a lot of time. Controls and resources start getting destroyed immediately, and it is entirely possible that by the time your thread gets around to referencing the resource, it's already extinct.

I got around this by intercepting the WM\_QUIT (IIRC) message and sending a command to the thread to shut things down. The thread then informed the main window when it is time to actually close, after all cleanup had been completed.

# Answer
> 5 votes
When the main thread signals the rendering thread to terminate, you can use a mutex and condition to wait for the rendering thread to exit before allowing the main thread to proceed. You need to make sure this is the first thing you do on shutdown - before you delete anything related to rendering.

# Answer
> 2 votes
> the message loop thread signals the render loop thread to exit. As far as I can tell before the render loop thread can even process the signal it tries SwapBuffers and that fails.

And therein lies your problem: your "message loop thread" should *be* your "render loop thread". They should be the same thread.

Attempting to do rendering outside of the main thread is a recipe for disaster. Especially when it comes to closing the window.

---
Tags: opengl, windows, multithreading, winapi
---


# Question
Title: How do I multiply pixels on an SDL Surface?
Okay so I'm able to put blank pixels into a surface and also draw gradient pixels rectangles,etc

But I don't know how to multiply the pixels on a surface so I was hoping someone could provide me information on this topic.

I was thinking you could get the members pixel and then * it by 2 but that didn't provide results I wanted so I'm now thinking that you have to actually get to the position in bytes in one location to the left and one location to the right and then store it in memory and then * that by 2 am I correct or what?

If so what is it that allows me to do that and how do I do that?

For those who want an explanation I need a PNG Loaded on an SDL Surface to be bigger in size through code rather then image sequence.

for example I alter the pixels on the surface in such a way to make the pixels multiply increasing the size of the png and the SDL Surface.

# Answer
I found this code which seems to do what you want :

http://fvirtman.free.fr/recueil/02\_03\_10\_resize.c.html

With the **nearest** algorithm, we fill each pixel of the scaled image using the *nearest* pixel from the source image. This leads to many possible artifacts.

With the **linear** algorithm, the goal is to look for each pixel of the scaled image where we are in the source image (this can be between 4 source pixels for example), and do a *linear* interpolation of the colors of the pixels around the position (which is a real number) in the original image. It's all about smoothing.

You also can look here for more explanation and another scaling algorithm : http://www.brockmann-consult.de/beam/doc/help/general/ResamplingMethods.html

Here is an bilinear interpolation code commented :

```
float sourceWidth=192.0f;
float sourceHeight=128.0f;

float scaledWidth=sourceWidth*1.5f;
float scaledHeight=sourceheight*1.5f;

// First we need to find a ratio between the source image and the scaled image
// We already know it's 1.5

float ratioX=scaledWidth/sourceWidth;
float ratioY=scaledHeight/sourceHeight;

// Then we need to loop through each scaled image pixel

for(int i=0;i<scaledWidth;i++)
{
    for(int j=0;j<scaledHeight;j++)
    {
        // Time to get the real number position on the source image

        float sourceX=(float)i/ratioX;
        float sourceY=(float)j/ratioY;

        // Then we find the four pixels around our position

        int minX=floor(sourceX);
        int minY=floor(sourceY);
        int maxX=minX+1;
        int maxY=minY+1;

        // We need to check if the bottom-right pixel is out of the source image

        if(maxX>=sourceWidth)
            maxX--;

        if(maxY>=sourceHeight)
            maxY--;

        // Now we get the distance between the top-left source pixel and
        // The real number position

        float dX=sourceX-(float)minX;
        float dY=sourceY-(float)minY;

        // And for each color component (R,G,B) we apply the formula
        // You can find it in the second link I posted

        // I assume I have both GetPixelComp and SetPixelComp functions
        // And both images represented as source and scaled

        for(char k=0;k<3;k++)
        {
            unsigned char component=(unsigned char)
            (GetPixelComp(source,minX,minY,k)*(1-dX)*(1-dY)+ // Top-Left
            GetPixelComp(source,maxX,minY,k)*dX*(1-dY)+ // Top-Right
            GetPixelComp(source,minX,maxY,k)*(1-dX)*dY+ // Bottom-Left
            GetPixelComp(source,maxX,maxY,k)*dX*dY); // Bottom-Right

            SetPixelComp(scaled,i,j,k,component);
        }
    }
}

```

I hope it helps you understand the principle :)
> 3 votes

---
Tags: sdl, pixel
---


# Question
Title: In a casual top-down racing game, should collisions affect the car's engine?
Is there a way to deter players from colliding with obstacles in a top-down casual racer which keeping the game fun and lighthearted and yet make player's skill matter?

Should collisions affect car engine performance in a casual racing game? If so, in what way could it be done that keeps it fun?

Please use references (to other games) and examples in your answers.

# Answer
> 10 votes
The "slow-down from the collision" has always been enough to discourage me from driving carelessly in racing games. If you hit a wall head-on, you're immediately at a dead stop. You'll be passed by any cars that were within 10-20 sec of you, depending how many seconds it takes your car to get back up to speed once you're positioned back onto the track.

Also, if you introduce a health bar and the car can become totaled or no longer driveable, it may make the game less playable for children (who crash a lot).

# Answer
> 5 votes
First of all, i'm sorry for any gramar erros. English is not my first language. feel free to edit my answer if you find it necessary.

In my oppinion, you have to consider the type of game you are trying to create.

If you are making a game more similar to reality, slowing the speed of the car and and screw it up a bit would make the gameplay more fun and realistic.

But, if you are making a casual game, using a funnier type of penallity, like blowing the car, or making the car spin around, would fit better in the game.

It's worth Remembering Mario kart, when a car sliding off the track, he was brought back by a koopa in a cloud. This kind of penality was great with the language of the game, and no matter if you stay several positions behind, because you could always get some itens and get back to first position.

But this same kind of penality would not work in need for speed, because you would lost too much time, and could not go back to first position.

Always consider the kind of game you are making and try to find a penality that causes the player some problem, but that is not impossible to get over.

# Answer
> 4 votes
I will take part in your survey :)

> What is the way it is done in your favorite racing game?

I prefer when the car is slowed down or stopped and damage is applied to the car. After enough damage, the car's handling or top speed is reduced.

> How is it done in other successful racing games?

I don't play a lot of racing games, but the ones I'm familiar with will cause a slow down + damage. Unless the accident is really bad, then the car will be destroyed on impact.

> Do you think temporarily disabling the engine for a second is too severe?

For a full second? Not if the car can maintain existing momentum. If the car had to stop for a second, then get back up to speed it may be a problem. You'd have to play test it and see what felt right.

> If I do go that route, how would I convey the 'engine is disabled' to the player in a subtle and easily understood way?

You could flash an engine icon at the top of the screen and/or play sounds of a sputtering engine. Or sounds of an engine revving up out of gear.

> Is this 'too much' of a penalty?

You can change the time of the delay based on the severity of the impact. So players will know that a severe penalty was their own fault.

> Would the slow-down from the collision be sufficient to discourage the player from driving too carelessly?

I guess that depends on the player. If the slowdown was significant enough, they wouldn't drive carelessly any more. But if it's too much, they might not play anymore.

> Which one is more fun?

Blowing up the car when it takes too much damage is typically rated 3 funs above just slowing the car down.

> Should I consider a health-bar and affect engine performance for 'low health' status?

Since you don't mention if the racing game is realistic or cartoony, I'll assume cartoony. Yes, have a health bar. The engine should slow down and make coughing noises when it's very damaged.

> Could you offer examples of games that handle this well and one that do it poorly?

I don't remember the specific names of the games, but I know there was one racing game where when you hit something and slowed down, the AI racers were always *right behind you* to overtake you. No matter how much of a lead you had on them. Don't do it that way.

> Please share your experience with racing games obstacles and reference games you feel perform well in this aspect.

Again, I don't remember the specific names. But there was one that would just slow you down and have realistic body damage to the vehicle when the car was hit.

> I would also like to hear how you feel we should penalize or reward for colliding with other vehicles?

Same deal, cars should be damaged based on the severity of the crash. For example a head on collision would be devastating, but a side swipe would be barely anything.

> Should enemy vehicles be destroyable? Should they slow down severely when they hit the back of your car or would that make the gameplay imbalanced?

Yes! Take them out of the race. Enemy vehicles should have all the same penalties as your car. You should be able to side swipe them to make the crash into other cars or trees.

# Answer
> 0 votes
Slow down is important for physics simulation. Especially if there are more then 2 colliding objects.

At high speed most racing games handle collision in non-physics way otherwise car angular velocity was too high. They ignore

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


# Question
Title: Learning OpenGL GLSL - VAO buffer problems?
I've just started digging through OpenGL and GLSL, and now stumbled on something I can't get my head around this one!? I've stepped back to loading a simple cube and using a simple shader on it, but the result is triangles drawn incorrectly and/or missing. The code I had working perfectly on meshes, but was attempting to move to using VAOs so none of the code for storing the vertices and indices has changed.

What I have for creating the VAO and buffers is this

```
//Create the Vertex array object
glGenVertexArrays(1, &vaoID);

// Finally create our vertex buffer objects
glGenBuffers(VBO_COUNT, mVBONames);

glBindVertexArray(vaoID);

    // Save vertex attributes into GPU
    glBindBuffer(GL_ARRAY_BUFFER, mVBONames[VERTEX_VBO]);

    // Copy data into the buffer object
    glBufferData(GL_ARRAY_BUFFER, lPolygonVertexCount*VERTEX_STRIDE*sizeof(GLfloat), lVertices, GL_STATIC_DRAW);

    glEnableVertexAttribArray(pos);
    glVertexAttribPointer(pos, 3, GL_FLOAT, GL_FALSE, VERTEX_STRIDE*sizeof(GLfloat),0);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mVBONames[INDEX_VBO]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, lPolygonCount*sizeof(unsigned int), lIndices, GL_STATIC_DRAW);

glBindVertexArray(0);

```

And the code for drawing the mesh.

```
glBindVertexArray(vaoID);
glUseProgram(shader->programID);

GLsizei lOffset = mSubMeshes[pMaterialIndex]->IndexOffset*sizeof(unsigned int);
const GLsizei lElementCount = mSubMeshes[pMaterialIndex]->TriangleCount*TRIAGNLE_VERTEX_COUNT;
glDrawElements(GL_TRIANGLES, lElementCount, GL_UNSIGNED_SHORT, reinterpret_cast<const GLvoid*>(lOffset));

// All the points are indeed in the correct place!?
//glPointSize(10.0f);
//glDrawElements(GL_POINTS, lElementCount, GL_UNSIGNED_SHORT, 0);

glUseProgram(0);
glBindVertexArray(0);

```

Eyes have become bleary looking at this today so any thoughts or a fresh set of eyes would be greatly appreciated.

# Answer
> 6 votes
The size of your GL\_ELEMENT\_ARRAY\_BUFFER looks wrong:

```
lPolygonCount*sizeof(unsigned int)

```

Based on the rest of your code it's highly probable that should be:

```
lElementCount*sizeof(unsigned short)

```

You're also binding mVBONames\[INDEX\_VBO\] as your GL\_ELEMENT\_ARRAY\_BUFFER, which is going to overwrite the data you previously loaded to your GL\_ARRAY\_BUFFER - perhaps you meant to use mVBONames\[INDEX\_IBO\] or something similar instead?

Other than that your VAO code looks good.

# Answer
> 0 votes
The element array is not part of the VAO. Only the vertex attribute arrays get saved to it. Make sure to bind the element array buffer before the draw call.

```
glBindVertexArray(vao);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_vbo);
glDrawElements(...);

```

---
Tags: c++, opengl, shaders, glsl
---


# Question
Title: How to do the Geometry Wars gravity well effect
I'm not talking about the background grid here, I'm talking about the swirly particles going around the Gravity Wells! I've always liked the effect and decided it'd be a fun experiment to replicate it, I know GW uses Hooke's law all over the place, but I don't think the Particle-to-Well effect is done using springs, it looks like a distance-squared function.

Here is a video demonstrating the effect: http://www.youtube.com/watch?v=YgJe0YI18Fg

I can implement a spring or gravity effect on some particles just fine, that's easy. But I can't seem to get the effect to look similar to GWs effect. When I watch the effect in game it seems that the particles are emitted in bunches from the Well itself, they spiral outward around the center of the well, and eventually get flung outward, fall back towards the well, and repeat.

**How would I make the particles spiral outward when spawned? How would I keep the particle bunches together when near the Well but spread away from each other when they're flung outward? How would I keep the particles so strongly attached to the Well?**

EDIT:
http://www.youtube.com/watch?v=1eEPl8kOXN8 \<- Video
https://dl.dropbox.com/u/49283213/gw.gif \<- GIF of the particle path

I disabled the randomization within GW to make the particle effect easier to see, here's a minute video where you can see a blue-green drain sending out it's bunch of particles. The red particles are from the explosions that normally appear all over the place. Some observations I made from the video:

* The particles are emitted from the center (or near center) of the drain
* All particles are being forced into a clockwise motion around the center so some sort of tangential motion is being applied, you can easily see this when the red explosion particles get close to the drain.

# Answer
I finally did it, a satisfactory replication of the particle behavior.

http://www.openprocessing.org/sketch/73624

The effect IS a standard gravity effect with a twist, when the particles get within a certain range a force is applied on the tangent normal. this causes the particles to "orbit" in a rather unstable fashion. The particles in the processing sketch don't burn out, but at the apex of their orbit this is when they would burn out and another bunch would be released. Thanks all for your help, even if it didn't really provide me with any new information, it's highly appreciated that you'd put the time and effort you did into your answers. Thanks again!
> 0 votes

# Answer
From the video showed it just seems to be plain gravity to me. Most people think gravity makes things flying downwards, but looking at it from a more far away perspective it makes things fly in a elliptical or spiral kind of motion around the center. The particles are always accelerated towards the center, however fly beyond it until the gravity forces it to come back, again and again. Some particles fly so far that the gravity doesn't affect them so much anymore and end up burning out before changing their direction.

Each particle has a X and Y velocity, to which each frame the gravity is added to, depending on the angle and distance to the center. The gravity always adds velocity into the direction (angle) of the center.

So you have for the particle: position, velocity
For the gravity well you have: position, strength

From the positions you can calculate the angle between the particle and the gravity well. To calculate the angle you'll need the deltas between the two coordinates.

```
dx = particle.x - gravity.x; dy = particle.y - gravity.y
angle = atan2(dy, dx)

```

This angle is the angle of the velocity vector that needs to be added.

The amount of force that is applied depends on the distance. To be exact it decreases by the square of the distance. So if something is twice as far away only a fourth of force is applied. For the distance the deltas are required too.

```
distance = sqrt(dx*dx + dy*dy)
force = gravity.strength / distance*distance

```

Now you have the force and the angle you just need to apply them:

```
particle.velocity.x += force * sin(angle)
particle.velocity.y += force * cos(angle)

```
> 7 votes

# Answer
it seems to me that what is drawn is segments, not points. So i guess the Well ejects a point of the circle, with a high speed and a speed vector tangent to the circle. And another point is thrown just after, which is linked to the first one to draw a segment. Then i think laws of physics (Newton) are applied with a strong gravity, which explains the speed decrease. So i guess you have to integrate on time to do this.

with : C the center of the well, R its radius.
P1 the point we're looking at
K being a 'big' constant that you choose with some trials (mass of the well).
vel0 is the initial velocity vector, tangential to the circle.
vel0 must be high(do trials too)
pos0 the initial position, on the circle, at time t0.
: d the distance beetween C and P1
: Vn the normed vector C P1

```
accx= - Vnx * K * 1 / square(d)   ; accy = - Vny * K * 1/square (d)
velx = accx*(t-t0) + vel0x   ;   vely = accy(t-t0) + vel0y
posx= (1/2)*accx*square(t-t0) + vel0x*(t-t0) + pos0x   ;
posy= (1/2)*accx*square(t-t0) + vel0y*(t-t0) + pos0y

```

Init : Most easy way to go to spawn a new point is to choose an angle A, then :

```
  pos0x= Cx +R *cos(A)  ; pos0y = Cy + R*sin(A)
  vel0x = v0*sin(A)   vel0y =  - v0*cos(A)     v0= float constant.

```

update : *for each iteration* you have to compute :

```
d= square root( square(P1x-Cx)+square(P1y-Cy) )
Vnx= (P1x-Cx)/d   ;   Vny=(P1y-Cy)/d
acc (accx,accy) and finally pos (posx, posy)  as described above.

```

no need to compute speed.
maybe the game use some kind of friction, then the equation would be different.
notice that you use several times cos(A) and sin(A), so store them.

so if you spawn a lot of points linked two by two and at the same time you change initial angle A to have the segment source rotate around the well, you come pretty close from the solution i guess.

Edit : i think you should give a try to this without friction first, it might be ok. friction is a force which is proportionnal to speed, but having reversed vector direction. so the equation becomes :

```
    Acc = Gravity force + Friction Force.

```

with Friction Force = - constant * Vel. this i don't know how to integrate, so i would go for a step by step integration :

```
   Vel(t+dt) = vel(t) + acc(t)*dt,
   pos(t+dt)= pos(t)+ vel(t)*dt.

```

there WILL be numerical stability issue, but since the life time of particules is short, this should not be an issue.
> 2 votes

---
Tags: particles, graphic-effects, special-effects
---


# Question
Title: Are there tools available for building hierarchical sprite-based objects in games like Vector Man or Gunstar Heroes?
> **Possible Duplicate:**
> Tools for 2D skeletal animation

I'm looking for a tool that would let me build multi-part sprite objects of the kind you can find in Sega Genesis games like Vector Man and bosses like Gunstar Heroes. Not only are they built with multiple sprites, but they're animated on a kind of really basic skeletal model.

Are there any tools out there that builds that sort of thing?

# Answer
You can check Spriter: http://www.brashmonkey.com/spriter.htm
> 3 votes

---
Tags: animation, sprites, tools, editors
---


# Question
Title: Is it the class that slows down the game?
My framerate lastime exceeds 1000 now the highest is 15. I have thousands lines of code in one class(I was still fresh last time and did not think of putting it in another class) Is it the class that makes the game slower?

# Answer
How to **identify** the issue:

To find out what is slowing down your game (also known as bottleneck), you could use Profiling.

http://en.wikipedia.org/wiki/Profiling\_%28computer\_programming%29

It is not classes that slow down frame rate, it is the amount of processing time it takes to complete the instructions in the code (for instance instructions that reside inside functions).

Using Profiling could help you check how much time is spent running each function and how many times each function is being ran.

Here are some suggestions on how to use Profiling with Java: https://stackoverflow.com/questions/2422289/any-recommended-java-profiling-tutorial

Then you would know for sure what is slowing the code down.

How to **improve** speed:

After you find the part of the code that is causing the slowdown, consider how to refactor the code. You may need to consult others or you might find out that you could use the resources in a new efficient way for the same result.

http://en.wikipedia.org/wiki/Code\_refactoring
> 4 votes

---
Tags: java, slick, frame-rate
---


# Question
Title: Why is the framerate (fps) capped at 60?
**ISSUE**

I recently moved a project from my laptop to my desktop(machine info below). On my laptop the exact same code displays the fps(and ms/f) correctly. On my desktop it does not. What I mean by this is on the laptop it will display 300 fps(for example) where on my desktop it will show only up to 60. If I add 100 objects to the game on the laptop I'll see my frame rate drop accordingly; the same test on the desktop results in no change and the frames stay at 60. It takes a lot(~300) entities before I'll see a frame drop on the desktop, then it will descend. It seems as though its "theoretical" frames would be 400 or 500 but will never actually get to that and only do 60 until there's too much to handle at 60. This 60 frame cap is coming from no where.

I'm not doing any frame limiting myself.

It seems like something external is limiting my loop iterations on the desktop, but for the last couple days I've been scratching my head trying to figure out how to debug this.

**SETUPS**

Desktop:

* Visual Studio Express 2012
* Windows 7 Ultimate 64-bit

Laptop:

* Visual Studio Express 2010
* Windows 7 Ultimate 64-bit

The libraries(allegro, box2d) are the same versions on both setups.

**CODE**

Main Loop:

```
while(!abort) {
    frameTime = al_get_time();
    if (frameTime - lastTime >= 1.0) {
        lastFps = fps/(frameTime - lastTime);
        lastTime = frameTime;
        avgMspf = cumMspf/fps;
        cumMspf = 0.0;
        fps = 0;
    }

    /** DRAWING/UPDATE CODE **/

    fps++;
    cumMspf += al_get_time() - frameTime;
}

```

> **Note**: There is no blocking code in the loop at any point.

**Where I'm at**

My understanding of `al_get_time()` is that it can return different resolutions depending on the system. However the resolution is never worse than seconds, and the double is represented as \[seconds\].\[finer-resolution\] and seeing as I'm only checking for a whole second `al_get_time()` shouldn't be responsible.

My project settings and compiler options are the same. And I promise its the same code on both machines.

My googling really didn't help me much, and although technically it's not that big of a deal. I'd really like to figure this out or perhaps have it explained, whichever comes first. Even just an idea of how to go about figuring out possible causes, because I'm out of ideas.

Any help at all is greatly appreciated.

**EDIT:**

**Thanks All. For any others that find this to disable vSync(windows only) in opengl**:

First get "wglext.h". It's all over the web.

Then you can use a tool like `GLee` or just write your own quick extensions manager like:

```
bool WGLExtensionSupported(const char *extension_name) {
PFNWGLGETEXTENSIONSSTRINGEXTPROC _wglGetExtensionsStringEXT = NULL;

_wglGetExtensionsStringEXT = (PFNWGLGETEXTENSIONSSTRINGEXTPROC) wglGetProcAddress("wglGetExtensionsStringEXT");

if (strstr(_wglGetExtensionsStringEXT(), extension_name) == NULL) {
    return false;
}

return true;
}

```

and then create and setup your function pointers:

```
PFNWGLSWAPINTERVALEXTPROC       wglSwapIntervalEXT = NULL;
PFNWGLGETSWAPINTERVALEXTPROC    wglGetSwapIntervalEXT = NULL;

if (WGLExtensionSupported("WGL_EXT_swap_control"))
{
    // Extension is supported, init pointers.
    wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT");

    // this is another function from WGL_EXT_swap_control extension
    wglGetSwapIntervalEXT = (PFNWGLGETSWAPINTERVALEXTPROC) wglGetProcAddress("wglGetSwapIntervalEXT");
}

```

Then just call wglSwapIntervalEXT(0) to disable vSync and 1 to enable vSync. I found the reason this is windows only is that openGl actually doesn't deal with anything other than rendering it leaves the rest up to the OS and Hardware.

Thanks everyone saved me a lot of time!

# Answer
This is called vsync (vertical sync), which traditionally means that your rendering rate is synchronized with the vertical refresh rate of your monitor to avoid tearing. Nowadays LCD screens don't have "vertical" refresh rates, just simple refresh rates, but it's the same thing.

As others have said in the responses, your video card driver settings cause this. Things to look out for:

* vsync can be overridden in the driver settings
* windowed applications will most likely have vsync disabled
* enabling/disabling vsync from your app can be problematic (partly because of the previous two points), but changing the global settings is usually simple
> 7 votes

---
Tags: c++, windows, game-loop, frame-rate, allegro
---


# Question
Title: Story and news-feed ideas for social network games
I am currently working on a educational and fun 2-in-1 game. As I am not a professional, I need advice on story and news-feed. The goal is simple-get richer, the story is about a worker who is trying to get over his/her financial problems and become rich.

During the whole gaming process there is a news-feed (every day there are a couple of fresh news about what is going on). The news are fresh and individual so I need to write about 2000 pieces of news for 2 year gaming, maybe more.

The problem is that I am not sure whether repetitive news can interest in this game. What can be done to make the news-making process easier but not boring from the point of view of the player?

# Answer
Not being able to substitute words like in English is not a real problem, because while in English you have this problem less often, it is still there:

"There was a **man** named %name%. **He** liked kids..." - female names won't work here.

Instead you could try to have fun with a more complex approach.

"There was a **%person1.sexAndAge%**. **%person1.personalPronoun%** liked kids... But they didn't like **%person1.personalPronounGenitive%**."

Now if you create a random object:

```
var person1 = {}
person1.age = random(80)+10;
person1.sex = randomFromList( ['man', 'woman'] );
if ( person1.age < 20 ) person1.ageDescription = 'young';
else if ( person1.age > 50 ) person1.ageDescription = 'old'; //sorry to all guys here above 50!
if ( person1.sex == 'man' ) {
   person1.personalPronoun = 'he';
   person1.personalPronoun = 'him';
   if ( person1.ageDescription == 'young' ) person1.sexAndAge = 'boy';
   else person1.sexAndAge = 'man';
}
if ( person1.sex == 'woman' ) {
   person1.personalPronoun = 'she';
   person1.personalPronounGenitive = 'her';
   if ( person1.ageDescription == 'young' ) person1.sexAndAge = 'girl';
   else person1.sexAndAge = 'woman';
}

```

Now, whatever random functions will return, the sentence will work (at least grammatically!)

* There was a **boy**. **He** liked kids... But they didn't like **him**.
* There was a **woman**. **She** liked kids... Buth they didn't like **her**.

but you're limited and you can't add "old man" to your sexAndAge possible values:

* There was a **old man** ...
* should be: There was **an** old man...

This is easy to solve, but it complicates your code even more. You could also go a step further and make functions randomizing a group of people, e.g. a married couple, where there would be only like 1% chance that this is a gay marriage. Then you could make a story about a %person1.name% being in love with %person2.nameLocative%. You should write a few stories, some variants of these stories and see what functionality you need.
> 2 votes

# Answer
Maybe you can use some type of natural language generation to create news based on certain input. It wouldn't have to be state of the art (this is a complex field with lots of research) but could be based on a certain sentence pattern with some different synonyms that can replace each other for different types of news. Wikipedia has an article on this which might be a good place to start. Just keep in mind that since news are very similar in structure you can keep it very simple by sticking to certain patterns.
> 1 votes

---
Tags: game-design, social, storyboard
---


# Question
Title: I prefer C/C++ over Unity and other tools: is it such a big downer for a game developer?
We have a big game project using Unity at school. There are 12 of us working on it. My teacher seems to be convinced it's an important tool to teach students, since it makes students look from the high level to the lower level.

I can understand his view, and I'm wondering: Is unity such an important engine in game development companies? Are there a lot of companies using it because they can't afford to use something else? He is talking like Unity is a big player in game making, but I only see it fit small indie game companies who want to do a game as fast as possible.

Do you think Unity is of that much importance in the industry? Does it endanger the value of C++ skills?

It's not that I don't like Unity, it's just that I don't learn anything with it, I prefer to achieve little steps with Ogre or SFML instead.

Also, we also have C++ practice exercises, but those are just practice with theory, nothing much.

# Answer
Unity is a perfectly valid solution in this context. Imagine for a second having 12 people, most of whom are still in the process of learning C++, writing a large and complex game application using it. In the amount of time spent debugging alone you will probably have been able to write *another* game in Unity.

I'm not saying knowing how to use C++ is not important - it is, especially if you plan on joining the 'mainstream' gaming industry. But perhaps your instructor is correct in this case - use this project as a learning experience in how to think about architecting a game, and have fun doing it. In the process, try to hone your C++ skills using exercises or even go so far as to write small games in the meantime using SFML or some other basic framework.

When it is all done, you will have learned a lot, probably become a better programmer, and your next project can be tackled in C++ with a lot more confidence.
> 36 votes

# Answer
Unity is growing in popularity in the industry, mostly in smaller companies. However, it is an excellent teaching environment. It is an important teaching tool, but not particularly common among mainstream companies. It's okay that you don't prefer it.

Let me note something here, though, as I often see a confusion among programming students. "C++ skills" are not very useful in the long run. What you should be seeking out are "programming skills" and "design skills." If you understand programming language concepts and how a software system is put together, then language doesn't really matter. I don't consider myself an amazing developer, but I can pick up a new language and produce useful code in a day or two, because I understand the fundamentals.

Learning Unity will make you better at C++.
> 44 votes

# Answer
The core issue, from what I can see, is not C++ or Unity3D, but rather **do you need a high-level solution or a low-level solution**.

A low-level solution is one which you get dirty with the processes of handing input, managing memory or loading the models. A high-level solution is which you get one neat package, like Unity3D.

To me, whether to use Unity3D (or any other game engine) or C++ depends on the goals of your game and project.

* Use Unity3D, if development time has to be quick and/or your game is not performance intensive or is not on the high end of graphical/computational performance. If you wish to concentrate on the game-play, and the default tools that Unity3D provide is all right, you may wish to consider using Unity3D
* C++ with other libraries, if you have longer development time, the game requires more computational/graphical power, or employs some technology that Unity3D cannot incorporate.

The good thing about Unity3D is that it still employs scripting languages which mirror real world development (C# or JavaScript). The OOP and software engineering concepts you learn (Singletons, facade, state machines, decorators, composition) can be applied in Unity3D. It helps to take care of the cookie-cutter processes such as resources management, scene graph, model loading, rendering, saving of scenes and etc. Even better, if there is a functionality you need which Unity3D don't provide, you can do DLL coding.

Where does that leave C++? C++ is a language, and there are many programming concepts you do in C++ you can do in Unity3D, sans memory management or perhaps templates ( With Unity 3.2, the language specs have improved to cover closures, for example).

So as I have stated, it's not really C++ vs. Unity3D. It is more of "C++ plus libraries/SDK or roll your own engine" vs. Unity3D. It depends on your goals and objectives. For high-end games or games where you need control over the rendering pipeline or input, you may want to use C++ plus an engine which allows you to mess under the hood. If not, I go with Unity3D as my default choice for 3D games.

However, knowledge with Unity3d is not under the hood experience, but it is a good place to start for learning the overall process of developing games. For instance, you probably will need a semester worth of studying to write a renderer and load a model in OpenGL, plus a basic scenegraph and input. You get that done in Unity3D in less than a day.
> 10 votes

# Answer
> Are there a lot of companies using it because they can't afford to use something else?

Yes, but "afford" is so much more than just straight up dollar values.

Yes, the feature set that Unity Pro gives you at the cost they charge is ridiculous, especially considering the fact that it's seat licenses instead of per-title licenses.

But on top of that, it's a really easy tool to use. You're not spending as much *time* training artists and designers how to use the art pipeline. It's easy to say "just drag in your textures and models and they're good to go.

On top of that, it's one of the very few tools that actually let's you do 3D in a browser with any kind of regularity. They support pretty much every shader platform from fixed function to DX9+ as well as Mac and Windows. That tech alone is *invaluable* if you want to target the growing "browser based game" market.

From a programming side of things, what you get from Unity is a firm grasp of component design (compared to rolling your own C++ engine, which is usually too heavy on the inheritance side), as well as a very quick and visual environment to try out game code. You'll hopefully learn good design practices by using Unity, that you can take over to future C++ engines.

Sure, it's fine to have a preference of one language over another. Personally I prefer C# over C++. But what language you use is really driven by the project requirements more so than anything else. Developers can't really afford to be fanboys since you don't want to lock yourself out of a market because you happen to not like the tools or language for one reason or another.

Besides, once you really learn a second language you can see that it's mostly just picking up new syntax and paradigms, and it really isn't that hard usually to add new tools to your tool belt. Yes, you should learn and understand C++, but on a high level you need to understand good design first.
> 9 votes

# Answer
No, Unity3D in no way endangers C++ skills. In fact, knowing C++ is way more important for a game programmer.

Unity3D is a really great tool for game development. I really like it myself, and would recommend it for almost any game, especially for small teams. But Unity3D itself is written in C++; and you have to know C++ (and also a bunch of other low-level stuff) to really understand how it works.

Even if you use Unity3D, only C++ skills and low-level understanding of principles and algorithms involved would allow you to use it to its full potential. This applies to other game engines too, by the way.

And to do a really good job, to squeeze every last bit of performance out of your platform of choice, and cram as many state-of-the-art effects and algorithms as possible, you can't use anything but C/C++. With bits of assembler, probably.
> 8 votes

# Answer
I went to the University of Pennsylvania's Computer Graphics and Game Technology Master's Program, where we did all of our projects at the lowest levels, with projects in C++, OpenGL, CUDA, etc. Our projects included physics-based animation, architecting character animation and IK, representing various forms of Bezier curves... you know, really baseline stuff that leverages expertise in programming, linear algebra, and calculus.

Then, I downloaded Unity and found that everything that I worked my butt off to create was bottled up in this free suite that anyone can use.

Was I annoyed by it? A little, admittedly, but I found that having that understanding from school makes me that much more dangerous when I utilize tools like Unity. I currently work in games, where we bring games from concept to market in less than a year, and I'm still the go-to guy when it comes to "that math stuff." My advice to you is go through the motions; you'll be absolutely invaluable when you enter the industry.
> 5 votes

# Answer
As far as I can tell, it depends on your target platform, AAA games and console (XBOX, Wii, etc) games will typically be in C++ to get maximum performance, however if you'r writing a browser based game Unity is also frequently used.

However as to your question, I think its simply to do with that tools like Unity give you a large standardized framework to work in, which in a project of half a year can make the difference between half baked prototype and pretty fleshed out game.
> 3 votes

# Answer
I might be late in replying but this will help some of the people having this confusion..

Initially I'm a c++ programmer, who used to hate using third party engines (for example unity) as, I don't feel like there is much learning process involved in terms of low level programming.

After trying unity, I came across the following things that is must for a Game developer.Here i'm listing not specifically to unity but listing out the advantages of going in HIGH LEVEL Perspective.

1. Understanding how to design at high level is more important than bothering about low level optimizations.
2. Engines which have Entity system of architecture (component based architecture) will help in learning how exactly this architecture will be helpful.
3. You will know the latest technology (at-least the terminology) and you will be at-least up to date with the industry regarding Graphics.- this is the main reason I choose to try unity!
4. Skipping time spending on different resource importer tools.(of-course i will still love to write my own 3d importers in c++ as it will be more fun in free time)

Above are some of the reasons for choosing high level engine. But at the same time, You should not stop learning C++ as its the most required and useful lang for a perfect Game dev.

First understand visualizing in the high level and do some quick prototypes with Unity and use that experience in designing a good game in c++.

Soon I will be back to c++ as i had gained a good experience at higher level with unity :)

Good luck!
> 0 votes

# Answer
C4 Engine is good alternative for learning game programming with C++

There is Academic license as well http://www.terathon.com/c4engine/licensing.php
> 0 votes

---
Tags: unity
---


title: Help, i cant reference my vars!

text:
# Question
Title: Help, i cant reference my vars!
I have a sub-class(let's call it sub) and it contains all the function of an object in my game. In my main class(Let's call it main), i connect my sub to main. (Example sub

### Code:

```
s = new sub();

```

Then I put my sub function at the update method.

### Code:

```
s.myFunc();

```

Becuase in my sub, i have booleans, integers, float and more. The problem is that I don't want to connect my main class to use my main's int, booleans and others. If i connect it, it will have a stack overflow. This is what I put in my sub:

### Code:

```
package javagame;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.state.StateBasedGame;

public class Armory {
   package javagame;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.state.StateBasedGame;

public class Store {
    public Integer wood;
    public Float probePositionX;
    public Float probePositionY;
    public Boolean StoreOn;
    public Boolean darkBought;
    public Integer money;
    public Integer darkEnergy;
    public Integer lifeLeft;
    public Integer powerLeft;
    public void darkStores(GameContainer gc, StateBasedGame sbg, GameContainer gc2)
    {
        Input input1 = gc.getInput();

        //Player need wood to enter(200) If not there will be an error.
        if(wood>=200)
        {

            //Enter Store!
            if(input1.isKeyDown(Input.KEY_Q))
            {
                //Player must be in this cord!
                if((probePositionX>393 && probePositionX<555) && (probePositionY< 271 && probePositionY>171))
                {
                //The Store is On
                StoreOn=true;
                }
            }

        }

    }

}

```

In my main (update function) I put:

### Code:

```
s.darkBought = darkBought;
s.darkEnergy = darkEnergy;
s.lifeLeft = lifeLeft;
s.money = money;
s.powerLeft = powerLeft;
s.probePositionX = probePositionX;
s.probePositionY = probePositionY;
s.StoreOn = StoreOn;
s.wood = wood;
s.darkStores(gc, sbg, gc);

```

The problem is when I go to the place, and I press q, nothing shows up. It should show another image. Is there anything wrong???

# Answer
This is off topic for the site so I hope it gets moved to Stack Overflow.

Your question isn't well written and I don't really understand it, but this does stand out to me: After pressing Q, you set StoreOn to true.

In your "update function" however, you say this:

```
s.StoreOn = StoreOn;

```

Where `s.StoreOn` is a completely different variable to `StoreOn`. I'm not even sure why you're setting it, but if `StoreOn` is false, you're constantly setting `s.StoreOn` to false, either in the very frame following you pressing Q, or before that frame is even over.

---

I'm not sure what you're doing and I'm not sure you're sure either. The language in your title ("Help, I can't reference my vars!") being completely weird and not making much sense in the context says a lot. After all, you can get at your variables just fine apparently, it's just that you've got weird behaviour, so I'm not sure what you mean and you're probably not sure either.

It seems you're out of your depth and you don't really understand what you're doing very well, so the best advice I can give you is go back and complete some basic tutorials on Java programming. It looks like you're struggling, and you're missing a lot of basics. You could really, really do with learning those basics, so go back to basics and learn them.

Do a tutorial.
> 3 votes

---
Tags: java, slick
---


# Question
Title: Confuse with OpenGL, SFML, and its library
I am a beginning to enter the world of game development.

Lately, I researched that "**OPENGL**" is one of the tools to use in graphics, then I found out about "**SFML**" (I think that its a library or something that uses opengl).

I am so confuse because all books/ sites said using "GLUT", but many people/fellow developers said that I must use a more updated one like "SFML" but sfml has few/none tutorials.

What I am trying to say is "how to create own library or something like your own glut or sfml", and why does opengl has no source code? And how can I use the EXACT(not glut/sfml) opengl in my c++ program?

I am so confuse....

# Answer
> 1 votes
OpenGL is just here to provide a link between your code and your graphics hardware, and to get it possible to OpenGL to draw on screen you have to create a *rendering context*.

GLUT and SFML both create this rendering context, in a portable way.

GLUT hasn't been updated for too long and shouldn't be used, you should use SFML or GLFW for example.

OpenGL can be used in a lot of ways, that's why it must be learnt separately, all it needs to work is a rendering context (like SFML's Window).

---
Tags: opengl
---


# Question
Title: How do you set up PhysFS for use in a game?
After my recent question on GD I've been advised to use PhysFS to pack all my game data in 1 file. So I have, and the decission wasn't light, because I've tried out every library in my answers but none contained *a single good tutorial* whatsoever, in fact PhysFS is the poorest documented library I've ever seen.

After attempting to set up PhysFS in my game I realized it's not as simple as adding the headers to the project, it appears something much more complicated, in fact after my first attempt to install PhysFS the compiler ran out of memory to display errors, it reached the critical count of 50 errors.

So basically what I'm asking here is: How can I set up PhysFS on my game? I'm using Code::Blocks IDE on Windows XP SP3;

# Answer
> 3 votes
You want to know how to compile and link against PhysFS. First, you need to create the binaries to link against. I'll assume you're using MinGW with C::B.

## Creating the PhysFS binaries (with C::B IDE, MinGW on Windows)

1. Unzip your PhysFS archive into a directory (e.g. C:\physfs-2.0.2)
2. You want to download CMake as per INSTALL.TXT in the directory. Once installed, open the CMake GUI and point the first field (Where is the source code:) at your directory (C:/physfs-2.0.2).
3. Create a directory for the binaries (doesn't matter where, I created one on the desktop) and point the second field (Where to build the binaries:) at that.
4. Click "Generate". Under the drop-down for generators, I chose "CodeBlocks - MinGW Makefiles" - assuming you're using CodeBlocks with MinGW and MinGW is installed to its default location, this will work. Otherwise, you'll have to click "Configure" and play with the settings.
5. Assuming no errors, navigate to your directory and open PhysicsFS.cbp. Try to build it - chances are, you'll get an error about an unused variable. If you do, expand the virtual folder "CMake Files" in the project file structure and open "CMakeLists.txt".
6. On line 47, remove '-Werror' from ADD\_DEFINITIONS(). Try to build the project again - this time, it should work. You now have files in your project directory: libphysfs.a, libphysfs.dll, libphysfs.dll.a.
7. Create a folder for your binaries, e.g. "C:\physfs-2.0.2\bin" and copy them there.

## Linking against the PhysFS binaries

1. In the Code::Blocks settings, you need to now add "C:\physfs-2.0.2\\" as a compiler search directory and "C:\physfs-2.0.2\bin" as a linker search directory. This can be done either locally to the project or globally to the IDE, depending on your needs.
2. Finally, right click on your project, choose "build options", go to "linker settings" and under "other linker options" add **-llibphysfs** at the end.
3. Now, in your project where you want to use PhysFS, make sure to #include physfs.h, but don't actually put the file (or any of the physfs files) in your project.
4. Try building your project and (assuming there are no errors in your code) it should compile.

---
Tags: c++, distribution
---


title: Randomly spawning bitmaps on cnvas

text:
# Question
Title: Randomly spawning bitmaps on cnvas
I need some ideas in order to finish algorithm. I'm randomly placing objects (bitmaps) on canvas without overlapping. Time needed to finish it is my problem. When I need to spawn for example 80% of canvas it takes to long. So i was thinking : I should make some change when the bitmaps take off 50 % of canvas. I want to tell algorithm that it should generate new locations (x,y) where it is free space.

My question is : How to render new location (x,y) in place where is free space.

In summary:

Things I know :

* object location (x,y)
* 4 corners (x,y) of object
* object width, height
* canvas width, height

Any suggestions?

Thanks for ideas. Now I've got problem.

---

OK, thanks for ideas. I've got a problem.

Link to picture: Picture with grid

I'm incrementing number of objects in cell after each adding object to grid. In the picture there are 9 possible locations for object. Should I check 9 conditions which tells where I should increment number of objects in cell? I assume that if object is on both cells than I increment number of objects in both cells.

# Answer
> 2 votes
**Divide your world (screen) into a grid.**

If all objects are not bigger then 20x20 px, then if you divide your screen into 40x40 grid tiles, you can just:

* every time when you add an object, set grid cell's state it occupies as "taken"
* every time when you remove an object, set the cell it was on as "free"
* when adding an object randomly, place it on one of free cells.

Edit: in regards to your question:

*I'm incrementing number of objects in cell after each adding object to grid. In the picture there are 9 possible locations for object. Should I check 9 conditions which tells where I should increment number of objects in cell? I assume that if object is on both cells than I increment number of objects in both cells.*

Yes, you want to register one object to all grid cells it occupies. One way of doing this would be creating a grid of arrays of objects:

```
const NUMBER_ROWS:int = 3;
const NUMBER_COLS:int = 3;
var grid:Array = [];
//init an empty grid
for ( var row:int = 0; row < NUMBER_ROWS; row++ ) {
   for ( var col:int = 0; col < NUMBER_COLS; col++ ) {
      grid.push ( [] );
   }
}
//create object
var object: SomeClass = new SomeClass ();
//add the object to 4 cells:
grid[0][0].push ( object );
grid[1][0].push ( object );
grid[0][1].push ( object );
grid[1][1].push ( object );

//remove the object from upper two cells (it went down)
var index:int = grid[0][0].indexOf ( object );
grid[0][0].splice ( index, 1 );
index = grid[1][0].indexOf ( object );
grid[1][0].splice ( index, 1 );

```

# Answer
> 0 votes
1. Divide the canvas into many 'rectangular pieces'
2. Shuffle the order of the pieces
3. Add bitmaps based on the order of the shuffled collection

To divide the canvas into pieces, make the whole canvas your first rectangular piece, then recursively split it until each piece is small enough.

For example, starting with the canvas, do a coin toss to determine if you split it with a horizontal line or a vertical line. Randomize where that line passes. Now run the same function on the two pieces you created and the stopping condition will be that the new piece is small enough by your definition.

---
Tags: android, collision-detection, procedural-generation
---


# Question
Title: Separating UI and logic in Objective-C at iOS based Games
How to separate UI and logic in Objective-C based mobile games?

To develop games, I use Cocos2d library.

I need a good reference to separate my UI code from game logic code.

# Answer
The usual way to loosely couple complex objects in Objective-C is to use delegates with formal protocols.

In an iOS board game I'm working on, I have `@class PMGameState` which stores the board and controls how you can move on it. And I have a `@class PMGameView` that knows how to draw the board tiles. Each has a protocol associated with it:

```
@protocol PMGameStateDelegate <NSObject>
- (void)game:(PMGameState *)game didApply:(YUUPoint)position;
- (void)game:(PMGameState *)game didMoveFrom:(YUUPoint)a to:(YUUPoint)b;
- (void)gameDidWin:(PMGameState *)game;
@end

@protocol PMGameViewDelegate <NSObject>
- (void)gameView:(PMGameView *)view didTap:(YUUPoint)position;
- (void)gameView:(PMGameView *)view didSwipeTowards:(YUUPoint)position;
@end

```

And in the classes themselves, e.g.

```
@property (nonatomic, weak) id <PMGameViewDelegate> delegate;

```

Then, a controller implements both and mediates between them:

```
@interface PMViewController : UIViewController <PMGameStateDelegate, PMGameViewDelegate>

```

This controller is the delegate for both the game controller and the view. It handles `game:didMoveFrom:to:` and can tell the view to update that position. It handles `gameView:didTap:` and can tell the game controller how the player wants to move.

You can see many more examples of this style in Apple's own APIs. Almost all objects with non-trivial state or feedback use a formal protocol rather than inheritance or a big set of selector/target pairs.
> 3 votes

# Answer
Hmm...I'm not quite sure about this but I treat UI as MVC. I separate them into those domains. The game will only talk to the controllers so that you will not need to know anything about the view. That way the game logic, UI logic, and the view itself are all separated.

I actually did a CCView and CCViewController myself (though it needs more refinement). This helps me to change view whenever I want (esp. we have iPhone5 now).

The game itself has a different architecture. I'm using Component Design for the game.

I'm still not sure about this because I just made it up myself since it seems to work for me. If there are better approach, I'm open to it.
> 1 votes

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


# Question
Title: Where do you put assets on iOS 5.1 apps?
I'm starting with iOS 5.1 and I'm trying to figure out how to download/and load asset files to the iPad, such as sprites and sounds.

Previously I think I packed them into a .xib file for iOS 3, (wasn't .xib for general user interfaces?) but I'm not sure if this practice is outdated with the new GLKit package.

# Answer
> 0 votes
Add all the assets via Xcode so that it will be included in the bundle. I think this is true since the older versions. Once you compile your build (specifically the .app). All your assets/resources will go inside the package.

I've already tried downloading assets from an external source and putting them in the Library folder. This is very useful when you want to add something dynamically or if you're going for the 50MB filesize limit.

---
Tags: ios, assets
---


title: Should iOS games use a Timer?

text:
# Question
Title: Should iOS games use a Timer?
No matter what frameworks we use -- Core Graphics, Cocos2D, OpenGL ES -- to write games, should a timer be used (for games that has animation even when a user doesn't do any input, such as after firing a missile and waiting to see if the UFO is hit)?

I read that `NSTimer` might not get fired until after scheduled time (interval), and `CADisplayLink` can delay and get fired at a later time as well, only that it tells you how late it is so you can move the object more, so it can make the object look like it skipped frame. Must we use a Timer? And if so, what is the best one to use?

# Answer
For my game, I'm using one global timer for everything. This runs the game loop. I'm always in sync with the frame rate because I'm computing for delta (time difference between the current frame and previous frame). That way no matter how slow/fast your hardware is, it will only either look slow/fast but everything is still in sync.

I rarely use timer to wait for something. It's very unreliable for me.

For me I'm using cocos2d's schedule: method which can run as fast as it can. I read that cocos2d timer performs better than an NSTimer (not sure).
> 1 votes

# Answer
You don't necessarily have to use a timer but I would definitely recommend using time based animation. Find a high resolution timer (I don't program on iOS so you'll have to google for that) and just set a start time where things occur at intervals based off that start time.
> 0 votes

# Answer
For the specific case you're asking about, it would be far better to let the animation complete callback determine when to run your next bit of code. This way, it'll always exactly match when that missile hits that UFO.
> 0 votes

# Answer
`Timer`s in any language can hang up. That's why I always have some `Updateable` class that uses a given library's `Timer`. In the constructor for `Updateable`, you can tell `Updateable` the interval in which it should call a `virtual` (overridable) function.

In order to account for slow downs, `Updateable` needs to store the last time in which the `Timer` fired. Then, when the `Timer` fires again, `Updateable` simply subtracts the current time from the previous time. That is your deltaTime. You then store the previous time, and the process continues.

Here is some code for my solution in Qt and C++

```
    // This class handles is an abstraction between Timer objects and their logic.
    class UpdateComponent : private QObject {

        Q_OBJECT

        public:
            UpdateComponent();
            boost::signals2::signal<void (float)> onUpdate;

        private Q_SLOTS:
            void onTimerUpdate();

        private:
            QTimer* m_timer;
            QDateTime m_previousDateTime;
            static const int UPDATE_INTERVAL = 17; // This can be changed through the constructor, for example.  This means let the timer fire every 17 milliseconds, or roughly, 60 times per second.
    };

    // Constructor
    UpdateComponent::UpdateComponent() {
        m_timer = new QTimer(); // Create a new QTimer

        connect(m_timer, SIGNAL(timeout()), this, SLOT(onTimerUpdate())); // Tell m_timer to call this class's function, onTimerUpdate().

        m_timer->start(UPDATE_INTERVAL); // Start the timer.  It will now begin to fire every ~17 milliseconds.
        m_previousDateTime = QDateTime::currentDateTime(); // Store the previous time.
    }

    // Fired by the timer every UPDATE_INTERVAL (17 milliseconds)
    void UpdateComponent::onTimerUpdate() {
        QDateTime currentDateTime = QDateTime::currentDateTime(); // Store the current time.
        qint64 deltaTimeMilliseconds = m_previousDateTime.msecsTo(currentDateTime); // Find the delta time in milliseconds.
        m_previousDateTime = currentDateTime; // Make the previous time the current time.

        float deltaTime = deltaTimeMilliseconds/1000.0f; // Convert the delta time into a float with the unit being seconds, instead of milliseconds.
        onUpdate(deltaTime); // This is boost::signals2::signal's way of saying, call everyone that is listening to onUpdate, and pass the parameter deltaTime.
    }

```

Here is a class that will listen to `UpdateComponent`'s `onUpdate(float)` function.

```
    class Updateable {

        public:
            Updateable();
            Components::UpdateComponent* getUpdateComponent();

        protected :
            virtual void onUpdate(float deltaTime) = 0;
            Components::UpdateComponent* m_updateComponent;
    };

    Updateable::Updateable() {
        m_updateComponent = new UpdateComponent();
        m_updateComponent->onUpdate.connect(boost::bind(&Updateable::onUpdate, this, _1));
    }

    UpdateComponent* Updateable::getUpdateComponent() {
        return m_updateComponent;
    }

```

Any class that is `Updateable` can implement the `virtual` function `onUpdate(float deltaTime)`. `onUpdate(float deltaTime)` is called automagically in the derived class, such that its sole parameter tells you the time, in seconds, since the last time the timer was fired. Note that an `Updateable` object *tries* to fire as close to the specified interval as possible, but we make up for any slow-downs or speed-ups. 90% of the timer, you should be getting the interval you specified; however, that 10% of the time where there is a slow-down, or if a `Timer` prematurely fires, we account for it.
> 0 votes

# Answer
CADisplayLink callbacks are called on the UI thread, so if your game logic is taking a long time, you'll run into problems.

A solution is to have your game run on a second thread, and use the CADisplayLink callback to signal that thread to do a frame.

This way, your UI thread is free to always handle touches and CADisplayLink callbacks.

It does mean you'll need to synchronize access to input data via a mutex though.
> 0 votes

---
Tags: opengl-es, ios, cocos2d-iphone
---


title: Best practice for image compression

text:
# Question
Title: Best practice for image compression
Which is the best format or best technique to compress images without loss of quality for iPhone/iPad games?

# Answer
The commonly used formats are PNG and PVR.

The PNG (Portable Network Graphics) format is compressed but lossless. It's a commonly used format (basically any image-editing software can write to PNG).

The PVR (PowerVR) format is a format that is much closer to the native memory structure of images on the GPU of the iPhone. Therefore it also allows for some byte-orderings that are available on the GPU but not usually used in image-processing, such as RGBA4444 (4 bits instead of 8 bits per channel). Of course a reduction in bits per channel also means a quality-loss... it's highly dependent on your type of image if this quality loss will be noticeable or not.

The PVR format is faster to read to the GPU and it gives you more control over how much memory your texture will consume. PNG is ubiquitous and much easier to work with. Almost any image editing software can read/write it and there are tools like ImageOptim that allow even further compression/optimization of PNGs.

**Update** Just to clarify if that wasn't clear from what I have written above: Further optimizing and compressing a PNG will *only* result in smaller file-size, eg. less disk-space that's being used. That can be important if you aim for a small app-package size (eg. to stay below the 50mb limit to download over cellular networks). Usage of graphics-memory is also important and if you want to optimize graphics-memory consumption, then your only option is to use PVR (unless you load PNGs and convert them to other formats/byte-orderings dynamically... but that's another story).

As long as you aren't facing any texture memory issues, PNG is far easier to work with.
> 8 votes

# Answer
You need to have a good eye so that you can get the most out of your textures.

* I always compare RGBA4444 with RGBA8888. If the difference is not that noticeable, I use RGBA4444 instead. It saves a LOT of memory.
* If quality seems to degrade RGBA4444, apply Dithering. See if it's workable.
* If I need to compress the project's total filesize. I'm looking for any texture that can be in JPEG. JPEG's filesize is very small compared to PNG but tradeoff is you're gonna lose a lot of processing. It'll be slower. I'm using this for textures that do not have any alpha channel. Also, only use this for something that is seldom used or textures that are loaded once and it'll stay long on the screen (like splashscreen, background). Never use JPEG if you need to draw it frequently on the screen.

Anyway, only do this if you have problem with memory/filesize. In my case, we have tight schedule so we optimize beforehand as long as quality will not degrade.
> 1 votes

---
Tags: iphone, image, compression
---


# Question
Title: rotate sprite and shooting bullets from the end of a cannon
> **Possible Duplicate:**
> How to Align Gun with Bullets

Hi all i have a problem in my Andengine code,

I need , when I touch the screen, shoot a bullet from the cannon (in the same direction of the cannon) The cannon rotates perfectly but when I touch the screen the bullet is not created at the end of the turret

This is my code:

```
private void shootProjectile(final float pX, final float pY){
    int offX = (int) (pX-canon.getSceneCenterCoordinates()[0]);
    int offY = (int) (pY-canon.getSceneCenterCoordinates()[1]);
    if (offX <= 0)
            return ;
    if(offY>=0)
                    return;

    double X=canon.getX()+canon.getWidth()*0,5;
    double Y=canon.getY()+canon.getHeight()*0,5 ;
    final Sprite projectile;
    projectile = new Sprite( (float) X, (float) Y,
                    mProjectileTextureRegion,this.getVertexBufferObjectManager() );

    mMainScene.attachChild(projectile);

    int realX = (int) (mCamera.getWidth()+ projectile.getWidth()/2.0f);
    float ratio = (float) offY / (float) offX;
    int realY = (int) ((realX*ratio) + projectile.getY());

    int offRealX = (int) (realX- projectile.getX());
    int offRealY = (int) (realY- projectile.getY());
    float length = (float) Math.sqrt((offRealX*offRealX)+(offRealY*offRealY));
    float velocity = (float) 480.0f/1.0f;
    float realMoveDuration = length/velocity;

    MoveModifier modifier = new MoveModifier(realMoveDuration,projectile.getX(), realX, projectile.getY(), realY);
    projectile.registerEntityModifier(modifier);
}

@Override
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {

    if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_MOVE){

        double  dx = pSceneTouchEvent.getX() -  canon.getSceneCenterCoordinates()[0];
        double  dy = pSceneTouchEvent.getY() -  canon.getSceneCenterCoordinates()[1];

        double  Radius = Math.atan2(dy,dx);
        double Angle = Radius * 180 / Math.PI;
        canon.setRotation((float)Angle);

        return  true;

    }
    else if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN){

        final float touchX = pSceneTouchEvent.getX();
        final float touchY = pSceneTouchEvent.getY();

        double  dx = pSceneTouchEvent.getX() -  canon.getSceneCenterCoordinates()[0];
        double  dy = pSceneTouchEvent.getY() -  canon.getSceneCenterCoordinates()[1];

        double  Radius = Math.atan2(dy,dx);
        double Angle = Radius * 180 / Math.PI;

        canon.setRotation((float)Angle);
        shootProjectile(touchX, touchY);
    }

    return false;
}

```

Anyone know how to calculate the coordinates (X,Y) of the end of the barrel to draw the bullet?

# Answer
If the base (point of rotation) of the cannon is `(CannonBaseX, CannonBaseY)`, and the length of the cannon barrel is `Radius`, then:

```
BulletX = CannonBaseX + Radius * Cos(Angle);
BulletY = CannonBaseY + Radius * Sin(Angle);

```

This may vary a bit depending on your coordinate system; it assumes an angle of 0 is pointing straight to the right, and that positive angles proceed counterclockwise, and that (0,0) is the upper left corner of the screen. If you have a different system, you may need to transform the parameters somewhat.
> 1 votes

---
Tags: java, android, sprites, rotation, andengine
---


# Question
Title: Real life example of an agile game development process outputs
I'm trying to learn about applying agile methodologies to game development. But seems to be impossible to find real life examples.

There seems to be plenty of material discussing how 'in principle' agile is applied to a game. But that is NOT what I am looking for. I have the Keith book.

What I AMlooking for are real EXAMPLES of things like;

1. Initial user stories
2. Final user stories (complete, covering the entire game requirements)
3. Acceptance criteria
4. Task list
5. Sprint backlogs (before and after each sprint)

The agile books seem to have some limited examples, many of which seem contrived or limited. In this era of open source software, there must be a publicly available documented example of the process applied to a real game.

I am asking specifically about games because they are so different from normal applications. Regular applications are built to all users to complete specific tasks in order to get stuff done(book a room, print a report etc). People play games for much less tangible reasons, so I think the process is significantly different.

\[it doesn't have to be scrum, it could be any process, just needs to be a real life example game and be reasonably complete\]

# Answer
> 6 votes
Ken,

Thanks for checking out my book. It's true that the examples are somewhat simplified and made generic, but they are not contrived. I'd like to have a specific game's backlog (product and sprint) to show, but every studio (including the one I worked at) hasn't allowed theirs to be released due to proprietary concerns, but I haven't really pressed that for the reasons below.

The most difficult thing for developers adopting user stories (and most of the \> 100 studios I've worked with that have adopted agile practices use them) is that they aren't meant to serve the same purpose as detailed requirements specifications. User stories are really "placeholders for conversation" more than documentation to record details up front. This "individuals over process" aspect of them are very difficult for developers to adopt and most flat out repudiate this idea up front.

However, over time as teams refine their practices and their communication, the desire to have extremely detailed specifications, acceptance criteria, traceability, etc. etc, get replaced by improved daily communication, better sharing of vision and even improved trust and respect. Trust and respect can work and it can look like this: http://blog.agilegamedevelopment.com/2012/04/valves-culture-self-organization-and.html

I don't ask teams to buy this idea up front. I tell them to "go ahead and document to the level of detail you are familiar with and comfortable with up front". Just be honest and transparent about finding ways to improve this over time.

Part of the benefit that I had early in my career was observing Miyamoto work directly on early N64 titles with our studio. He was all about direct communication and "finding the fun" (his phrase) in a game through iteration. He would NOT read documentation. The story is in the book.

Good luck, Clinton Keith www.ClintonKeith.com

---
Tags: game-design
---


# Question
Title: (int) Math.floor(x / TILESIZE) or just (int) (x / TILESIZE)
I have a Array that stores my map data and my Tiles are 64X64. Sometimes I need to convert from pixels to units of tiles. So I was doing:

```
int x
int y

public void myFunction()
{
    getTile((int) Math.floor(x / TILE_SIZE), (int) Math.floor(y / TILE_SIZE)).doOperation();
}

```

But I discovered by using (I'm using java BTW) `System.out.println((int) (1 / 1.5))` that converting to an int automatically rounds down. This means that I can replace the (int) Math.floor with just x / 64.

But if I run this on a different OS do you think it might give a different result? I'm just afraid there might be some case where this would round up and not down. Should I keep doing it the way I was and maybe make a function like convert(int i) to make it easier? Or is it OK to just do x / 64?

# Answer
Personally, I would write the code just as:

```
unsigned int x
unsigned int y

public void myFunction()
{
    getTile(x / 64, y / 64).doOperation();
}

```

since being a tilemap, you can use it (and thus assume) using positive-only values. This does not affect readability because x and y are declared as unsigned int, quite close to the block, and every programmer knows whether the language performs or not an integer division with the / operator when it is applied to two integers (most of them do). In fact, such a geometrical scenario is probably one of the few ones that shows that integer divisions can be useful.

Moreover, thinking about omptimization of such a snippet represents, in my opinion, one of those cases of "unnecessary preventive optimization": you can often assume that such operations will not be a bottleneck of your code, and thus take actions only when profiling shows the opposite. Performance of casting operations can be difficult to evaluate, in general: they largely depend not only on the language, but also on the compiler, which can remove unnecessary casts, or "translate" them in worse/better assembler.
> 2 votes

# Answer
Using Math.floor should not greatly decrease performance for your game and it makes the code more readable (self commented) and easy to understand.

Java logic will behave the same in any platform, the only difference between platforms is performance.

I think you could use this to define your tile size (to make the code more readable and easier to modify).

```
public static final int TILE_WIDTH  = 64;
public static final int TILE_HEIGHT = 64;

```

now

```
getTile((int) Math.floor(x / TILE_WIDTH),
        (int) Math.floor(y / TILE_HEIGHT)).doOperation();

```
> 2 votes

# Answer
I guess it safe to assume it is never negative, given that doing so would be reading outside the confine of the array. If that the case, simply rotate the bits 6 times which gives the same results but is far faster than using the int divide counterpart.

```
int x
int y

public void myFunction()
{
     getTile(x >> 6, y >> 6).doOperation();
}

```
> 2 votes

---
Tags: java, mathematics, tiles
---


# Question
Title: Comparing a saved movement with other movement with Kinect
I need to develop an application where a user (physiotherapist) will perform a movement in front of the Kinect, I'll write the data for the movement in the database and then the patient will try to imitate this motion. The system will calculate the similarity between the movement recorded and executed.

My first idea is to store the position of the recorded points and then compare them in the execution time to the patient's movement. I know that this approach is too simple, however, because I imagine that in people of different sizes the skeleton is recognized differently, so the comparison is not reliable.

My question is about the best way to compare a saved motion with a movement executed (on the fly).

# Answer
> 3 votes
You can calibrate the Kinect before using it. Like letting the patient stretch his arms, stand straight, just let him do some predefined poses. From this data you can calculate his skeleton and then use relative data to compare it.

Another possible way would be to focus on angles at the joints. This may be a bit more unrelated to body size, but I don´t know if this can provide all the information you need.

# Answer
> 0 votes
I would see this answer on SO which explains both the algorithms, code, and theory for how to do this, along with an example project.

---
Tags: movement, kinect, motion-control
---


# Question
Title: iOS persistant storage with update function
im developing a game which has different levels and i need to store all levels and its elements (position, image, sounds,..) into a file/database. The levels will be updated so i need a function that checks online for a update and downloads a database dump and additional files.

I was planing to store all the persistent data into a SQLLite database, but not quite sure how to do the update part - to pack the database dump and the files together (in a .zip or with a xml). Can this be done any other way (as secure as possible)?

thanks!

# Answer
I would recommend using your own binary format if you want efficient storage.

Creating and packaging deltas for levels should be done on the server side. The clients should be able to only read the deltas and apply them.

If you are comfortable with SQL and sqlite storage is good and efficient enough for you, there is no reason why not use it. You can package the deltas in any fashion you like and after retrieval apply them to the DB. This process could even be simplified if the server uses a similar database to store the levels.

For each entry you can store a "level validity start version id" and "level validity end version id". On the server side you can then simply use the version the client sends, pack the changes and apply them on the client.

Using sql commands directly in the exchange protocol is not a good idea. If one of the versions of the client application end-up using a different version of sqlite or if you need to change the storage system you will end-up with a bag of hurt. Use your own format.

If you need to secure the transfer you can use any encryption available to you.
> 2 votes

# Answer
Seems that your game doesn't need to store much data. I recommend that your save data can be easily converted to an NSDictionary (you can easily convert it to XML/plist). This way you won't have to worry about exporting the data elsewhere (in your case in a server).

In my projects, I have a protocol where you can do these: \- Get the NSDictionary representation of the class (for exporting) \- Update the class' instance variables with an NSDictionary \- Instantiate a class using an NSDictionary.

It works like NSCoding where you can do it in hierarchy. This may add a bit of complexity but will offer you lots of flexibility.

I always make it so that I'll have full control on how my data is being stored and processed. (That's why I'm not fond of using CoreData)

Just a question, why do you need to store images and sounds? Isn't that part of your assets/resources? I recommend you save what only really needs to persist.
> 2 votes

# Answer
Parse library \[1\] addresses exactly the problem of data persistence in mobile apps. It frees you from the "burden" of mantaining and query a database efficiently, and it should be quite easy to use since it is JSON friendly. Pricing allows you not to pay anything for trying it, or as long as your app becomes is not popular yet. Maybe it can really help you.

\[1\] https://parse.com/
> 0 votes

---
Tags: ios, storage
---


# Question
Title: Workflow with Flash Pro CS6 and FlashDevelop: Using fla and swc to store assets
I am using this tutorial:

http://www.flashdevelop.org/wikidocs/index.php?title=AS3:FlexAndFlashCS3Workflow

In the past older versions of Flash Pro I was able to complete these steps:

* right-click on the symbol in the Library panel, select "Linkage..." dialog,
* check "Export for ActionScript" and fill in the symbol name (ie. MySymbol\_design or assets.MySymbol\_design),
* do not change the base class (ie. flash.display.MovieClip).

Right now, I am stuck at that part. Any hints?

What I wish to do is:

1. Use fla for the artist to store assets.
2. Publish to swc
3. Extract the assets in FlashDevelop by creating an instance of their class.

... How is this done in CS6?

To clear things up, this is what I see when I right click a Flash symbol:

# Answer
It appears as you right-clicked a symbol on stage. You should right-click the symbol in your library panel instead. There you have "Properties" where you can mark a symbol to be exported for Actionscript. If you don't place the symbol on stage, you'll also have to tick the "export to first frame" option.
> 1 votes

---
Tags: actionscript-3, assets, flashdevelop
---


title: Spriting Animation Method

text:
# Question
Title: Spriting Animation Method
http://www.kickstarter.com/projects/539087245/spriter

At 3:00 they discuss that there is a method used to separate the parts of character into individual sprites and move them saving production time and video memory. What is this method called I am thinking that I want to implement it for my game but need to do more research. Thanks alot =)

# Answer
> 2 votes
It's called 2D skeletal animation. Essentially you're animating a skeleton that has sprites for the body parts placed on top of it. This allows you to reuse animations for different characters and characters can have multiple sets of armor, weapons, etc.

There are a number of questions on the site already about it:

Tools for 2D skeletal animation

How Plants vs Zombies animation is done?

Tips on combining the right Art Assets with a 2D Skeleton and making it flexible

And some other good resources:

http://www.catalinzima.com/2011/06/2d-skeletal-animations/

http://www.thecareergamer.com/braaaains-zombieville-usa-tech-review/

Enjoy your research.

---
Tags: animation, cocos2d-x
---


title: Using copyrighted sprites

text:
# Question
Title: Using copyrighted sprites
> **Possible Duplicate:**
> How closely can a game resemble another game without legal problems

I was thinking about making a pacman clone, I know there is a similar question here Using Copyrighted Images , but I know i can't use the original art from the game because it belongs to Namco, so if I design a character that has the shape of the slice circle it will look exactly like pacman, maybe if I use green instead of yellow? Also if the game plays like the original pacman, it is wrong? I just want to make the game as a personal project and and publish it in my site without getting in trouble

# Answer
> 4 votes
ZorbaTHut's answer is probably what you seek, but nevertheless I'd like to enhance it a bit.

# Jessica Hische's "Inspiration vs. Imitation"

> Something that I sadly hear too much is that “it’s not illegal to copy someone’s style”. Sure, if you create an illustration that is completely derivative of someone else but not a direct rip-off or tracing, they might have a hard time suing you. That doesn’t make it OK to make derivative work.

What Jessica is trying to emphasize throughout her post is that there is a difference between being inspired by some art and trying to imitate/copy/trace it (tracing is the process of "following"/tracing the outline of some art, and then simply colouring it or at least changing it slightly).

# Creating open-source fan-made games legally.

> As for what portions of a game can and cannot be protected:
>
> 1. The concept of a game cannot be protected -- you can make as many games as you want about plumbers who smash things with their face.
> 2. The code itself is protected by copyright, but you only violate copyright by duplicating said code -- in other words, you looked at their code and replicated it, or used their code verbatim somehow.
> 3. The code itself could conceivably contain algorithms that are patented, which would be protected -- If the algorithm is core to the game in some way, you'd have to figure out an alternative implementation that achieves the same thing, and it can't be a trivial transformation of the original algorithm.
> 4. Artistic elements -- graphics, sound, music, level design, etc -- are protected by copyright at a minimum. You can't replicate these things verbatim.
> 5. Some artistic elements that are unique and highly recognizable are also protected by trademark -- trademark protects firms from replicas that are meant to pass themselves off as the original -- You can make graphics for a blue plumber that likes to jump on tortoises just fine, but he better not have a mustache, be named "Nario", and speak with an Italian accent. Trademark is essentially about counterfeiting, its still a violation even when you change small things if the purpose is to deceive customers, or otherwise mooch of the good name of the authentic item.

# Conclusion

I found some wonderful site on fangame copyright issues long ago that I couldn't find again right now, but the author's final advice would be something like this:

> If you are in doubt whether what you've created is violating copyright, DON'T use it.

# My comment:

If you really have to (completely) copy art, characters or mechanics from another game, then your game isn't really worth publishing to the world. Bring in your own twist, invest in your game's design, create new and exciting characters, storyline and mechanics, even use "programmer's art" in order to express yourself!

Thus, why use dots and a yellow/blue/whatever sliced pizza as a character? Create a chipmunk collecting nuts, create a farmer collecting eggs while being hunted by angry chickens (lol), something different, something exciting! :)

---
Tags: javascript, sprites, php, copyright
---


# Question
Title: Deleting a game object causing an access violation
I tried doing this but it cause an access violation.

```
void GameObjectFactory::Update()
{
     for( std::list<GameObject*>::iterator it=gameObjectList.begin() .....
          (*it)->Update();
}

void Bomb::Update()
{
     if( time == 2.0f )
     {
         gameObjectFactory->Remove( this );
     }
}

void GameObjectFactory::Remove( ... )
{
     gameObjectList.remove( ... );
}

```

My thoughts would be to mark the object to be dead then let the factory handle it the on next frame for deletion. Is it the best and fastest way? What do you think?

# Answer
> 8 votes
> My thoughts would be to mark the object to be dead then let the factory handle it the on next frame for deletion. Is it the best and fastest way? What do you think?

Why wait until the next frame? Just remove it at the end of the current frame. But I wouldn't worry about it being the "fastest" way, unless you're dealing with lots of dead objects every frame. If you *are*, you should be using an object pool.

But yes, a flag or putting a reference to it in a separate list, whatever. Shouldn't matter. Implementing one or the other should be trivial to do and if you really care you can put some performance benchmarks on it and really get the only definitive answer to your question.

# Answer
> 2 votes
How about using `std::remove_if`?

```
bool shouldBeRemoved (GameObject* val) { return (val->time >= 2); }
std::remove_if(gameObjectList.begin(), gameObjectList.end(), shouldBeRemoved);

```

# Answer
> 0 votes
I think it is possible you are changing the list while you are still iterating over the list.

To avoid this, instead of deleting the unused (dead) objects. Create a new helper list and add the live objects to that new helper list, when the loop is over, remove the old list from memory and have it's pointer point to the helper list. This could help avoid any bugs that occur because you are iterating over and modifying a list in the time.

1. Create new helper list
2. Add each 'live' object to that new list as you iterate over it.
3. kill the old list
4. Have the old list's pointer, point to the new list.

---
Tags: c++, data, architecture
---