# Question
Title: Knockback enemy based off of direction sprite is facing
Today I am trying to make it so if I hit the enemy then the enemy will be knocked backwards in the direction the sprite is facing. I am rotating the sprite around 360 degrees using a joystick on the screen and wanted to know the best practice or ways to accomplish this. I have come up with a few ideas but none of them make use of the sprites angle he is facing just a check to see if I hit the bottom then move him upward and so forth. I am just stumped on how to apply the sprites angle to the enemies x and y coordinate and move him accordingly. Has anyone tried this and have suggestions or things to look for?

# Answer
You'll need to turn the angle of rotation into a 2d vector which represents the direction the sprite is facing. You can then add or subtract this 2d vector onto the sprites position to move it forward or backwards in the direction it's facing.

You can generate the vector with something as simple as using cos() and sin() for the X and Y components of this vector. (you'll need to ensure you don't mix degrees and radians when passing into these functions - plus ensure that when the angle is Zero that your sprite is facing directly right, although you could fix this by adding a constant onto the angle passed into cos/sin to adjust for any rotation that exists in the sprite).
> 3 votes

---
Tags: android
---


# Question
Title: I'm looking for a paper from Teknikus.dk
I'm looking for this great paper about Verlet integration: http://www.teknikus.dk/tj/gdc2001.htm

I've found this link on many websites, forums, blogs, everyone is recommending it !

The website is down for more than one week.

# Answer
The Wayback Machine to the rescue!
> 3 votes

# Answer
@The Communist Duck already posted a Wayback Machine link, but here's another version of the article that appeared on Gamasutra.
> 1 votes

---
Tags: physics, graphics-programming, graphic-effects
---


# Question
Title: How do you triangulate an arbitrary polygon?
I need to triangulate a polygon for rendering in OpenGL ES on Android (no GLU triangulation available).

Is there an already known algorithm for polygon triangulation? The polygon can be convex or concave (with no holes).

# Answer
There are several algorithms out there. One of the most commonly used algorithm is the ear clipping algorithm. Here's a page with some more detail about this triangulation algorithm.
> 12 votes

# Answer
There are some algorithms and implementation of polygon triangulation on these books:

* Computational Geometry: Algorithms and Applications. Chapter 3: Polygon Triangulation.
* Computational Geometry in C. Chapter 1: Polygon Triangulation.
> 1 votes

---
Tags: android, rendering, opengl-es, triangulation
---


title: Particle and Physics problem

text:
# Question
Title: Particle and Physics problem
This was originally a forum post so I hope you guys don't mind it being 2 questions in one.

I am making a game and I got some basic physics implemented. I have 2 problems, 1 with particles being drawn in the wrong place and one with going through walls while jumping in corners.

Skip over to about 15 sec video showing the 2 problems : http://youtube.com/watch?v=Tm9nfWsWfiM

So the problem with the particles seems to be coming from the removal, as soon as I remove that piece of code it instantly works, but there shouldn't be a problem since they shouldn't even draw when their energy gets to 0 (and then they get removed)

So my first question is, how are these particles getting warped all over the screen ?

Relevant code :

Particle class :

```
class Particle
{
    //Physics
    public Vector2 position = new Vector2(0,0);
    public float direction = 180;
    public float speed = 100;
    public float energy = 1;
    protected float startEnergy = 1;

    //Visual
    public Sprite sprite;
    public float rotation = 0;
    public float scale = 1;
    public byte alpha = 255;
    public BlendMode blendMode
    {
        get
        {
            return sprite.BlendMode;
        }
        set
        {
            sprite.BlendMode = value;
        }
    }

    public Particle()
    {
    }

    public virtual void Think(float frameTime)
    {
        if (energy - frameTime < 0)
            energy = 0;
        else
            energy -= frameTime;

        position += new Vector2((float)Math.Cos(MathHelper.DegToRad(direction)), (float)Math.Sin(MathHelper.DegToRad(direction))) * speed * frameTime;
        alpha = (byte)(255 * energy / startEnergy);
        sprite.Rotation = rotation;
        sprite.Position = position;
        sprite.Color = new Color(sprite.Color.R, sprite.Color.G, sprite.Color.B, alpha);
    }

    public virtual void Draw(float frameTime)
    {
        if (energy > 0)
        {
            World.camera.DrawSprite(sprite);
        }
    }
// Basic particle implementation
    class BasicSprite : Particle
    {
        public BasicSprite(Sprite _sprite)
        {
            sprite = _sprite;
        }
    }

```

Emitter :

```
    class Emitter
{
    protected static Random rand = new Random();
    protected List<Particle> particles = new List<Particle>();

    public BaseEntity target = null;
    public Vector2 position = new Vector2(0, 0);
    public bool Active = true;
    public float timeAlive = 0;
    public int particleCount = 0;
    public int ParticlesPerSeccond
    {
        get
        {
            return (int)(1 / particleSpawnTime);
        }
        set
        {
            particleSpawnTime = 1 / (float)value;
        }
    }
    public float dieTime = float.MaxValue;

    float particleSpawnTime = 0.05f;
    float spawnTime = 0;

    public Emitter()
    {

    }

    public virtual void Think(float frametime)
    {
            spawnTime += frametime;

            if (dieTime != float.MaxValue)
            {
                timeAlive += frametime;
                if (timeAlive >= dieTime)
                    Active = false;
            }

            if (Active)
            {

                if (target != null)
                    position = target.Position;

                while (spawnTime > particleSpawnTime)
                {
                    spawnTime -= particleSpawnTime;
                    AddParticle();
                    particleCount++;
                }

            }
            for (int i = 0; i < particles.Count; i++)
            {
                particles[i].Think(frametime);
                if (particles[i].energy <= 0)
                {
                    particles.Remove(particles[i]); // As soon as this is removed, it works
                    particleCount--;
                }
            }
    }

    public virtual void AddParticle()
    {

    }

    public virtual void Draw(float frametime)
    {
        foreach (Particle particle in particles)
        {
            particle.Draw(frametime);
        }
    }
}
class BloodEmitter : Emitter
{
    Image image;

    public BloodEmitter()
    {
        image = new Image(@"Content/Particles/TinyCircle.png");
        image.CreateMaskFromColor(new Color(255, 0, 255, 255));
        this.dieTime = 0.5f;
        this.ParticlesPerSeccond = 100;
    }

    public override void AddParticle()
    {
        Sprite sprite = new Sprite(image);
        sprite.Color = new Color((byte)(rand.NextDouble() * 255), (byte)(rand.NextDouble() * 255), (byte)(rand.NextDouble() * 255));

        BasicSprite particle = new BasicSprite(sprite);
        particle.direction = (float)rand.NextDouble() * 360;
        particle.position = position;
        particle.blendMode = BlendMode.Alpha;
        particles.Add(particle);
    }
}

```

The seccond problem is the physics problem, for some reason I can get through the right bottom corner while jumping. I think this is coming from me switching animations but I thought I made it compensate for that.

Relevant code : PhysicsEntity :

```
    class PhysicsEntity : BaseEntity
{
    // Horizontal movement constants
    protected const float maxHorizontalSpeed = 1000;
    protected const float horizontalAcceleration = 15;
    protected const float horizontalDragAir = 0.95f;
    protected const float horizontalDragGround = 0.95f;

    // Vertical movement constants
    protected const float maxVerticalSpeed = 1000;
    protected const float verticalAcceleration = 20;

    // Everything needed for movement and correct animations
    protected float movement = 0;
    protected bool onGround = false;
    protected Vector2 Velocity = new Vector2(0, 0);
    protected float maxSpeed = 0;
    float lastThink = 0;
    float thinkTime = 1f/60f;

    public PhysicsEntity(Vector2 position, Sprite sprite) :
        base(position, sprite)
    {

    }

    public override void Draw(float frameTime)
    {
        base.Draw(frameTime);
    }

    public override void Think(float frameTime)
    {
        CalculateMovement(frameTime);
        base.Think(frameTime);
    }

    protected void CalculateMovement(float frameTime)
    {
        lastThink += frameTime;

        while (lastThink > thinkTime)
        {
            onGround = false;

            Velocity.X = MathHelper.Clamp(Velocity.X + horizontalAcceleration * movement, -maxHorizontalSpeed, maxHorizontalSpeed);
            if (onGround)
                Velocity.X *= horizontalDragGround;
            else
                Velocity.X *= horizontalDragAir;

            if (maxSpeed < Velocity.X)
                maxSpeed = Velocity.X;

            Velocity.Y = MathHelper.Clamp(Velocity.Y + verticalAcceleration, -maxVerticalSpeed, maxVerticalSpeed);

            lastThink -= thinkTime;
            DoCollisions(thinkTime);
            DoAnimations(thinkTime);
        }
    }
    public virtual void DoAnimations(float frameTime)
    {

    }
    public void DoCollisions(float frameTime)
    {
        Position.Y += Velocity.Y * frameTime;
        Vector2 tileCollision = GetTileCollision();
        if (tileCollision.X != -1 || tileCollision.Y != -1)
        {
            Vector2 collisionDepth = CollisionRectangle.DepthIntersection(
                new Rectangle(
                    tileCollision.X * World.tileEngine.TileWidth,
                    tileCollision.Y * World.tileEngine.TileHeight,
                    World.tileEngine.TileWidth,
                    World.tileEngine.TileHeight
                )
            );
            Position.Y += collisionDepth.Y;
            if (collisionDepth.Y < 0)
                onGround = true;

            Velocity.Y = 0;
        }

        Position.X += Velocity.X * frameTime;
        tileCollision = GetTileCollision();
        if (tileCollision.X != -1 || tileCollision.Y != -1)
        {
            Vector2 collisionDepth = CollisionRectangle.DepthIntersection(
                new Rectangle(
                    tileCollision.X * World.tileEngine.TileWidth,
                    tileCollision.Y * World.tileEngine.TileHeight,
                    World.tileEngine.TileWidth,
                    World.tileEngine.TileHeight
                )
            );
            Position.X += collisionDepth.X;
            Velocity.X = 0;
        }
    }
    public void DoCollisions(Vector2 difference)
    {
        CollisionRectangle.Y = Position.Y - difference.Y;
        CollisionRectangle.Height += difference.Y;
        Vector2 tileCollision = GetTileCollision();
        if (tileCollision.X != -1 || tileCollision.Y != -1)
        {
            Vector2 collisionDepth = CollisionRectangle.DepthIntersection(
                new Rectangle(
                    tileCollision.X * World.tileEngine.TileWidth,
                    tileCollision.Y * World.tileEngine.TileHeight,
                    World.tileEngine.TileWidth,
                    World.tileEngine.TileHeight
                )
            );
            Position.Y += collisionDepth.Y;
            if (collisionDepth.Y < 0)
                onGround = true;

            Velocity.Y = 0;
        }

        CollisionRectangle.X = Position.X - difference.X;
        CollisionRectangle.Width += difference.X;
        tileCollision = GetTileCollision();
        if (tileCollision.X != -1 || tileCollision.Y != -1)
        {
            Vector2 collisionDepth = CollisionRectangle.DepthIntersection(
                new Rectangle(
                    tileCollision.X * World.tileEngine.TileWidth,
                    tileCollision.Y * World.tileEngine.TileHeight,
                    World.tileEngine.TileWidth,
                    World.tileEngine.TileHeight
                )
            );
            Position.X += collisionDepth.X;
            Velocity.X = 0;
        }
    }

    Vector2 GetTileCollision()
    {
        int topLeftTileX = (int)(CollisionRectangle.TopLeft.X / World.tileEngine.TileWidth);
        int topLeftTileY = (int)(CollisionRectangle.TopLeft.Y / World.tileEngine.TileHeight);
        int BottomRightTileX = (int)(CollisionRectangle.DownRight.X / World.tileEngine.TileWidth);
        int BottomRightTileY = (int)(CollisionRectangle.DownRight.Y / World.tileEngine.TileHeight);

        if (CollisionRectangle.DownRight.Y % World.tileEngine.TileHeight == 0) // If your exactly against the tile don't count that as being inside the tile
            BottomRightTileY -= 1;
        if (CollisionRectangle.DownRight.X % World.tileEngine.TileWidth == 0) // If your exactly against the tile don't count that as being inside the tile
            BottomRightTileX -= 1;

        for (int i = topLeftTileX; i <= BottomRightTileX; i++)
        {
            for (int j = topLeftTileY; j <= BottomRightTileY; j++)
            {
                if (World.tileEngine.TileIsSolid(i, j))
                {
                    return new Vector2(i, j);
                }
            }
        }

        return new Vector2(-1, -1);
    }
}

```

Player :

```
   enum State
{
    Standing,
    Running,
    Jumping,
    Falling,
    Sliding,
    WallSlide
}

class Player : PhysicsEntity
{
    private State state
    {
        get
        {
            return currentState;
        }
        set
        {
            if (currentState != value)
            {
                currentState = value;
                animationChanged = true;
            }
        }
    }

    private State currentState = State.Standing;
    private BasicEmitter basicEmitter = new BasicEmitter();
    public bool flipped;
    public bool animationChanged = false;

    protected const float jumpPower = 600;

    AnimationManager animationManager;
    Rectangle DrawRectangle;
    public override Rectangle CollisionRectangle
    {
        get
        {
            return new Rectangle(
                Position.X - DrawRectangle.Width / 2f,
                Position.Y - DrawRectangle.Height / 2f,
                DrawRectangle.Width,
                DrawRectangle.Height
            );
        }
    }

    public Player(Vector2 position, Sprite sprite) :
        base(position, sprite)
    {
        // Only posted the relevant bit
        DrawRectangle = animationManager.currentAnimation.drawingRectangle;
    }

    public override void Draw(float frameTime)
    {
        World.camera.DrawSprite(
            Sprite,
            Position + new Vector2(DrawRectangle.X, DrawRectangle.Y),
            animationManager.currentAnimation.drawingRectangle
        );
    }

    public override void Think(float frameTime)
    {
        //I only posted the relevant stuff
        if (animationChanged)
        {
            // if the animation has changed make sure we compensate for the change in with and height
            animationChanged = false;
            DoCollisions(animationManager.getSizeDifference());
        }
        DoCustomMovement();
        base.Think(frameTime);
        if (!onGround && Velocity.Y > 0)
        {
            state = State.Falling;
        }
    }

    void DoCustomMovement()
    {
        if (onGround)
        {
            if (World.renderWindow.Input.IsKeyDown(KeyCode.W))
            {
                Velocity.Y = -jumpPower;
                state = State.Jumping;
            }
        }
    }
    public override void DoAnimations(float frameTime)
    {
        string stateName = Enum.GetName(typeof(State), state);

        if (!animationManager.currentAnimationIs(stateName))
        {
            animationManager.PlayAnimation(stateName);
        }

        animationManager.Think(frameTime);

        DrawRectangle = animationManager.currentAnimation.drawingRectangle;
        Sprite.Center = new Vector2(
            DrawRectangle.X + DrawRectangle.Width / 2,
            DrawRectangle.Y + DrawRectangle.Height / 2
        );
        Sprite.FlipX(flipped);
    }

```

So why am I warping through walls ?

I have given this some thought but I just can't seem to find out why this is happening.

Full source if needed : source : http://www.mediafire.com/?rc7ddo09gnr68zd (download link)

# Answer
2 things that might be up.

1) When you remove the particles, that loop is going to skip the "next" particle after one that's been removed in the loop that processes them. This is because you iterate through the list using "i", but during that loop you also remove items from the array, shifting future entries down, but then also increment "i" which then skips what was effectively the one after the one you just deleted (that's now in our slot).

2) I might have missed it, but I didn't see the code when I had a quick look above that handled the actual "how far inside a block" test. What I'm wondering is that based off the depth inside you decide which way to push the colliding object out. You don't seem to take into consideration the velocity of the player at the time (i.e. was he moving down and is now colliding) which you could then also use to judge if he should be pushed back upwards when colliding. Instead I'm guessing you decide which direction to move the player based on which edge it's closest to of the tile. If the player is moving fast enough then you might get so far inside a tile that you think he should be pushed out the bottom.
> 2 votes

# Answer
Your particle problem is because you're removing elements while looping by index. Unless you adjust the index when you remove, you'll skip over a particle the next time the loop comes around.

Let's say you have particles `[a, b, c, d]`. The loop will do this:

1. Set `i` to 0.
2. Update `particles[0]`
3. Check it's energy. Let's say it's less than zero now.
4. Remove `particles[0]`. This shifts `[b, c, d]` up so that `b` is now at index zero.
5. Loop around and increment `i` to 1.
6. Update `particles[1]`. This is now *c* and not *b*. So we skip *b* entirely which is your bug.

A simple fix is:

```
for (int i = 0; i < particles.Count; i++)
{
    particles[i].Think(frametime);
    if (particles[i].energy <= 0)
    {
        particles.Remove(particles[i]);
        i--; // <-- Shift the index up too since the particles have shifted.
        particleCount--;
    }
}

```

`Remove()` can do a lot of work, though (it's `O(n)`). If you want something more efficient, do all of the removes in one step like this:

```
// First update all of the particles.
for (int i = 0; i < particles.Count; i++)
{
    particles[i].Think(frametime);
}

// Now remove all of the dead ones in one pass by overwriting them with
// the remaining lives ones.
int dest = 0;
for (int i = 0; i < particles.Count; i++)
{
    if (particles[i].energy > 0)
    {
        particles[dest] = particles[i];
        dest++;
    }
}

// Now trim the excess off the end.
particles.RemoveRange(dest, particles.Count - dest);

```

Also, you don't need `particleCount`. Lists already know their size.

I'll leave your other question to others to answer. :)
> 2 votes

---
Tags: c#, physics, animation, debugging
---


# Question
Title: Coming up with manageable game ideas as a hobbyist game developer
I'm trying to come up with ideas for games to develop - as per the advice on this question I've started jotting down and brainstorming my ideas as I get them, and it has worked relatively well - I now have a growing collection of ideas that I think are relatively original.

The trouble is that I'm a solo hobbyist developer so my time is limited (and I have short attention span!) I've decided to set myself a limit of 1 working week (i.e. 35-40 hours) to develop / prototype my game, but all of the ideas that really spark my imagination are **far** too complex to be achievable in that sort of time (e.g. RTS or RPG style gameplay), and none of my simpler ideas really strike me as being that good (and whenever I get a flash of inspiration I invariably end up making things more complicated!)

Am I being too picky - should I just take one of my simpler ideas and have a go?

# Answer
> 39 votes
You need training. Consider entering a Game Jam. It's a friendly competition where you have to create a game in a very limited time frame, usually 48h. Quite often, a theme is given at the beginning of the jam. The prize is your own finished game.

Such a tight deadline is an excellent exercise on "thinking small". You learn what are your strenghts and limitations, when it comes to creating a game that quickly; you learn what kinds of elements you have to cut off of your designs; you see where do you spend too much time in development and where do you need to polish more, etc.

Right now some possibilities are:

* Ludum Dare, the coming weekend. One of the most famous.
* Experimental Gameplay. Once a month, you have 7 days to create an "experimental" game.
* Klik of the month. Restricted to games made in Klik'n'Play only, and the competition is only 2h long.
* Game Prototyping Challenge. Honestly I don't know much about this one, but it's starting on Monday the 13th and lasts till the 20th.
* Global Game Jam, at the end of January. This one is massive, takes place in many cities around the world simultaneously.

# Answer
> 16 votes
I've been doing a lot of reading and listening to pod casts recently, and a lot of successful developers stress making a bunch of games as one of the best paths towards success as a game developer/designer. I've repeatedly heard comments along the lines of "Don't try to make your dream game initially, just make ANYTHING."

I had recently been having some of the same issues you mentioned, but I decided to try using my hour lunch break at work to create a simple game each day. Admittedly, an hour is obviously not long, but if you are sufficiently experienced in some type of game tool (Flash for me, or Unity), it should be possible to make something during this time period. I've done it five times now, and the crazy thing is that I have five new game ideas done.

They have horrible graphics, are buggy, and often not incredibly fun to play, but the cool thing is that I have an idea now of the possible success of five new game mechanics, and I've lost less than 5 hours. One of the five seems like it could actually be a fun game, so I might spend more time to actually make it into something.

Yesterday, I happened to have found a link to a guy who made one mini-game or interactive program each day for 219 days! (see http://interactionartist.com/index.php?page=allgad) Imagine having 219 ideas and prototypes in less than a years time. Sure, a lot of them will be junk (many of his are less than stellar), but incredibly, many of them will quite possibly be fun and interesting ideas.

Creating something within a super-constrained time frame forces you to focus on the core mechanic of the game, the idea that makes it special. Sure, to have a commercially successful game you need polish and high production value, but "you can put makeup on a pig, but it doesn't change the fact that it's a pig" lol. How much better to spend a tiny amount of time on each concept, then you can focus on polishing the ideas that seem to actually have merit.

Doing so will increase your confidence ("Wow, I have X ideas functional in only Y hours?"), increase your portfolio, and increase your skill as a designer. Good luck!

# Answer
> 14 votes
Even the biggest games are made up of a series of smaller systems.

If you are really excited about a big concept, split your big game idea up into all its different component system. If you can't finish a system in a week, split it further. Then make small prototype games of each one of these components.

Don't worry about hooking them in together, just build each one as quickly as possible to see if the idea is viable.

# Answer
> 9 votes
This is a very common problem, and there are a few exercises to get around it that I ask of my students.

Try this thought exercise: take one of your designs that's too big, and ask what you would do if you had to cut 90% of the features.

Here's another idea: change your design so that the game could be played to completion in 5 to 15 minutes. Can you use clever design to restrict the scope of the game so that the play time is incredibly short -- a competitor of Minesweeper more than Final Fantasy?

Identify the "core" of the game -- what's the one thing the player does over and over that's fun, that really drives the gameplay (or alternately, the one unique mechanic that makes your game stand out from the genre)? Implement that only, consider everything else as fluff.

You can approach this two ways, either as a serious attempt to reduce a genre to its essentials, or as a parody of the genre that lampoons the inherent banality of the core mechanics.

# Answer
> 5 votes
Do a remake!

Pick a simple game you enojoy from the 80s/90s and give it some interface love, turn it into something shiny again.

# Answer
> 4 votes
If you have a brainstorm list of ideas you're part of the way there. Pick your favorite 2 or three and break down what you liked most about them.

E.g. RTS: liked building the buildings -\> make a game centered around only building buildings.

dungeon-crawlingRPG: liked the combat with monsters.
-\> make only the combat part. no character choice, no stat or equipment choice, just the killing.

Oh, and don't do it alone, get at least one other person in on it who can keep you sane. If at worst you can't get a developer, at least get someone you can bounce your ideas off of and who can play whatever simple prototype you make and who you can watch try to play it, or talk to while they play it. The second you have anything manipulatable (not balanced, not playable, just does something), get someone other than yourself to start manipulating it.

Set yourself a hard definition of "a working prototype" and a hard deadline of "max prototyping hours" and pause once you reach them. Set the gamelet down for a bit, like two days, and when you come back to it, re-examine whether you can make it fun and want to add another prototyping goal to it or prototype something new.

(I advise this because despite being continually full of ideas, I got myself embroiled in developing a single live, legacy game, and 7 years later I'm still trying to get it to a "fun to play" state.)

Luckily, fun doesn't -require- complexity, and often you can add complexity later around a simple core for more options when you find a promising base.

# Answer
> 2 votes
Creating sprites or models is time consuming, adding animations just increases the time exponentially. Do what you can to create your game without any of the cool animations or fancy graphics. A cube or circle are awesome placeholders.

Unity3d now has a store you can download lots of amazing free or cheap prototyping scripts/models/animations ($15 gets you a great prototype graphics set, and I've had a lot of fun with a free explosions kit).

# Answer
> 2 votes
Have you thought about going retro? Older games will obviously not have the bells and whistles you would expect, but the plus is that they have a much smaller code base. Try structured steps too, If you wanted to make a game like Asteroids, step one might be set up the basic enviornment with a spaceship that can move and fire in any direction. Step two, add rocks that you can destroy. For the next step, vary the size of the rocks, or add missiles to your ship's arsenal. The trick is, build a base app, expand on the idea, structure your versions so you can reuse the greatest amount of code possible for other projects. Create your own personal code and resource library (if your not interested in creating your own models/sounds search out sites like thegamecreators.com, otherwise blender.org is a good place to look. Blender is a (FREE)3D animation studio that is heavily supported and close to AAA quality. It has a built in game engine you can use to prototype ideas.). The the more assets you have in your code library the less you have to build from scratch later(you also lessen the chance of reinventing the wheel!).

# Answer
> 2 votes
Try to keep your projects small, even if the result is "unintrestingly simple" games. The code from those projects can then be reused or extended, resulting in more interesting projects. If you are impatient to get something finished soon, work *extra* hard on getting the game idea simple and stripped of everything but the really bare essentials.

I have been fighting with this as a hobby game developer myself. Having a family with kids, fairly bad discipline, and a bad habit just like everyone else to want to do *everything* at *once* (which seem to plague not just hobbyist game development but *all* software development), I find it hard to get any of my games created. So the years goes on but in this matter, time is on our side as I see it because:

1. I develop software for a living, and some of the things learned from that job is usable when developing games. As the years goes on, my skills toolbox increases. This is true also for hobby programmers "cranking out unintresting simple games" for the sake of exercising his/her programming skills.
2. The computer industry (hardware and software) moves on as well, so what was a dreadfully complex task in the 1980ies and 1990ies or even a few years ago might today be taken care of by some proven and reliable library someone else wrote. As hardware gets more powerful and cheaper over time, more high level tools, libraries and programming languages becomes an option when developing games.
3. I mature over these years as well (at least I hope so) and manage to restrain myself more and more to remove as much as possible from the game I try to create. I can imagine many programmers share that experience, that over time, it is easier to adhere to "keep it simple, stupid".

In my case, in any year, all these three factors will converge to the point I actually manage to write some playable incarnation of some of my ideas. For you Kragen, that point might already have been reached, if you manage to pick a simple enough game idea to write.

Good luck!

# Answer
> 1 votes
Firstly, I think you are being to hard on yourself. You need to start of with a project that certainly interests you but you should be keeping it small.

The reason I think you should keep it small to begin with is so you do not become unmotivated.

Games evolve as they are created, I think you should challenge yourself with a simplistic project and allow yourself to build it into something more over time. Don't put yourself on a time-table, this will hinder your project. It's done when its done. Which is essentially never!

It's OK not to have the coolest new idea for a game, a lot of ideas are used and reused. Blizzard hasn't made an original game in years, but they still make the best games.

One last thing on creativity. You need to be creative with what you have, not with what you don't have. We don't have experience, we don't have massive art teams, and we don't have the a large diverse team of people.

# Answer
> 0 votes
If you're piling so much stuff on your plate that you can't finish a game just bite the bullet and cut the thing into smaller chunks. If you keep the game short it really doesn't need so much stuff and if you're doing anything object oriented and you write your programs well you'll have this big library of your own code that you can copy from later if you really want something with a much more complicated structure.

But really that's just if the whole experience thing isn't enough to motivate you on its own.

# Answer
> 0 votes
I would suggest to start with something as simple as a board game or card game. Doing something like that can give you a real taste for game mechanics. Writing software comes later. Remember, games are about fun, not snazzy graphics.

---
Tags: game-design, time-management
---


title: Collision Resolution

text:
# Question
Title: Collision Resolution
Hey all, I'm making a simple side-scrolling game, and I would appreciate some input!

My collision detection system is a simple bounding box detection, so it's really easy to implement. However my collision resolution is *ridiculous*! Currently I have a little formula like this:

```
if (colliding(firstObject,secondObject))
  firstObject.resolve_collision(yAxisOffset);
if (colliding(firstObject,secondObject))
  firstObject.resolve_collision(xAxisOffset);

```

where yAxisOffset is only set if the first object's previous y position was outside the second object's collision frame, respectively xAxisOffset as well.

Now this is working great, in general. However there is a single problem. When I have a stack of objects and I push the first object against that stack, the first object get's "stuck," on the stack. What's I think is happening is the object's collision system checks and resolves for collisions based on creation time, so If I check one axis, then the other, the object will "sink" object directly along the checking axis.

This sinking action causes the collision detection routine to think there's a gap between our position and the other object's position, and when I finally check the object that I've already sunk into, my object's position is resolved to it's original position...

All this is great, and I'm sure if I bang my head against a wall long enough i'll come up with a working algorithm, but I'd rather not =). So what in the heck do you think I should do? How could I change my collision resolution system to fix this?

Here's the program (temporary link, not sure how long it'll last) (notes: arrow keys to navigate, click to drop block, x to jump)

I'd appreciate any help you can offer!

# Answer
> 1 votes
Figured it out!!!!!

Here's the new method:
first, I add an object that I wish to check collisions, with my add\_message\_to\_collision\_queue(); function. I then invoke my handle\_collisions() method:

```
bool player::handle_collisions() {
collisions tcol;

bool did_handle = false;
for (int temp = 0; temp < collideQueue.size(); temp++) {

tcol = get_collision(prevPos.x,y,get_img()->get_width(),get_img()->get_height(),
                     collideQueue[temp]->get_position().x,collideQueue[temp]->get_position().y,
                     collideQueue[temp]->get_img()->get_width(),collideQueue[temp]->get_img()->get_height());

if (prevPos.y >= collideQueue[temp]->get_prev_pos().y + collideQueue[temp]->get_img()->get_height())
  if (tcol.top > 0) {
    add_pos(0,tcol.top);
    set_vel(get_vel().x,collideQueue[temp]->get_vel().y);
    did_handle = true;
  }

if (prevPos.y + get_img()->get_height() <= collideQueue[temp]->get_prev_pos().y)
  if (tcol.bottom > 0) {
    add_pos(0,-tcol.bottom);
    set_vel(get_vel().x,collideQueue[temp]->get_vel().y);
    ableToJump = true;
    did_handle = true;
  }
}

for (int temp = 0; temp < collideQueue.size(); temp++) {
tcol = get_collision(x,y,get_img()->get_width(),get_img()->get_height(),
                     collideQueue[temp]->get_position().x,collideQueue[temp]->get_position().y,
                    collideQueue[temp]->get_img()->get_width(),collideQueue[temp]->get_img()->get_height());

  if (prevPos.x + get_img()->get_width() <= collideQueue[temp]->get_prev_pos().x)
    if (tcol.left > 0) {
      cout << "\nleft";
      add_pos(-tcol.left,0);
      set_vel(collideQueue[temp]->get_vel().x,get_vel().y);
      did_handle = true;
    }
  if (prevPos.x >= collideQueue[temp]->get_prev_pos().x + collideQueue[temp]->get_img()->get_width())
    if (tcol.right > 0) {
      cout << "\nright";
      add_pos(tcol.right,0);
      set_vel(collideQueue[temp]->get_vel().x,get_vel().y);
      did_handle = true;
    }

}

return did_handle;
}

```

then I clear the queue. pretty easy, and it works *perfectly*!!

# Answer
> 1 votes
I'm not sure I understand the problem, but looking at your code above you resolve collision by only moving the first object away. What if in certain conditions, it's the second object that needs to move away and not the first?

You might want to try resolving the collision by moving both objects away from each other at the same time by half of the offset, or even better by an amount proportional to their weight or size, this way a big box will only move a little bit while a small box will move a lot.

If you have several objects to resolve (as you mention a stack), you need to find a solution that works for all objects at the same time and not just for 2 at a time.

If you want a very good/accurate solution I recommend you get a good book on physics/collision for games and try something from there. This will probably take some time to implement and some of those system are quite hard to understand. Maybe also overkill for a simple game.

One thing you could probably try now is to iterate through your resolution code a few times every frame between all the object. Every iteration will move each object away a little bit and hopefully find a good solution in very few iterations. Of course you might never find a solution this way and it might become too expensive to iterate many times in a single frame. Might be worth a try though.

---
Tags: c++, collision-detection, game-design, sdl
---


# Question
Title: How to create a Ghost Replay feature in a game?
When you set a personal best lap time in a console racing game, you have the option to compete against your ghost.

How can this feature be created for a single player casual type game?

# Answer
> 10 votes
Ghosts are typically done by displaying a replay of a previous attempt. This replay is rendered with a non-collidable version of the players car so that you can't affect it. Since racing games often have a replay feature anyway this kind of comes along for free.

Here is a good starting point for building a replay system: http://www.gamasutra.com/view/feature/2029/developing\_your\_own\_replay\_system.php

Also there are a number of questions here on that topic:

# Answer
> 1 votes
It depends on the technology you're working with. Hence, we can't really discuss of the best way, since it might change from a technology to another. The the gross idea in my opinion would be the following:

1. Use an underlying data store to persist your data (XML, Cookies, Database, CSV, other...);
2. Work your data access to this underlying data store;
3. You need to keep information data about the best score of a player, so an identifier is required (email, input name, else...);
4. Associate this best score to the identifier one way or another.

In short, assuming the use of a database, we could have two tables:

1. Users/players data (identifier, email, etc.);
2. Best score board information data.

Then, you could save the user information along with individual scoreboard which could, if desired, contain date and time registry as to when this score has been achieved.

I hope this helps and that I have correctly understood the question. Otherwise, please tell so that I may edit my answer accordingly.

# Answer
> 1 votes
Its not easy to answer this question without having more information on your game. The answer from wkerslake works as long as the current playthrough with the ghost can not affect the determinism of the recorded ghost data. If the recorded data is a single car time trial in a static environment, you should be alright using that technique.

However in many games with ghost playback, such as Super Meat Boy, the position of the player can change the state of the level and AI. Clearly, you can't have the ghost affecting the world and AI, so it might be better to just record position + animation changes (and anything else visible) every frame for the main player. During playback, just render the ghost at the current location and animation frame without having it be in the world. This allows you to playback a ghost and not have the current player affect it.

---
Tags: architecture, game-recording
---


# Question
Title: Points on lines where the two lines are the closest together
I'm trying to find the points on two lines where the two lines are the closest. I've implemented the following method (Points and Vectors are as you'd expect, and a Line consists of a Point on the line and a non-normalized direction Vector from that point):

```
void CDClosestPointsOnTwoLines(Line line1, Line line2, Point* closestPoints)
{
    closestPoints[0] = line1.pointOnLine;
    closestPoints[1] = line2.pointOnLine;

    Vector d1 = line1.direction;
    Vector d2 = line2.direction;

    float a = d1.dot(d1);
    float b = d1.dot(d2);
    float e = d2.dot(d2);

    float d = a*e - b*b;
    if (d != 0) // If the two lines are not parallel.
    {
        Vector r = Vector(line1.pointOnLine) - Vector(line2.pointOnLine);
        float c = d1.dot(r);
        float f = d2.dot(r);

        float s = (b*f - c*e) / d;
        float t = (a*f - b*c) / d;
        closestPoints[0] = line1.positionOnLine(s);
        closestPoints[1] = line2.positionOnLine(t);
    }
    else
    {
        printf("Lines were parallel.\n");
    }
}

```

I'm using OpenGL to draw three lines that move around the world, the third of which should be the line that most closely connects the other two lines, the two end points of which are calculated using this function.

The problem is that the first point of closestPoints after this function is called will lie on line1, but the second point won't lie on line2, let alone at the closest point on line2! I've checked over the function many times but I can't see where the mistake in my implementation is. I've checked my dot product function, scalar multiplication, subtraction, positionOnLine() etc. etc. So my assumption is that the problem is within this method implementation.

If it helps to find the answer, this is function supposed to be an implementation of section 5.1.8 from 'Real-Time Collision Detection' by Christer Ericson.

Many thanks for any help!

# Answer
> 3 votes
I've tested your code on a little program with OpenGL on a 2D space and the algorithm seems correct.

You says that direction is a non-normalized vector. Review that the method positionOnLine uses a normalized vector to do his calculations. I've used:

```
Vector2Df positionOnLine( float d )
{
    // where m_direction is a normalized vector
    return m_point + m_direction * d;
}

```

More code:

My code is like this:

```
struct Line
{
    Line( const Vector2Df& p, const Vector2Df& d )
        : m_point( p )
        , m_direction( d )
    {
        m_direction.normalize();
    }

    Vector2Df positionOnLine( float d )
    {
        return m_point + m_direction * d;
    }

    Vector2Df   m_point;
    Vector2Df   m_direction;
};

// Lines creation
Vector2Df v1( 0.f, 0.f );
Vector2Df v2( 100.f, 100.f );

Vector2Df v3( 10.f, 0.f );
Vector2Df v4( 100.f, 110.f );

Line l1( v1, v2 - v1 );
Line l2( v3, v4 - v3 );

```

---
Tags: collision-detection, vector, linear-algebra
---


# Question
Title: XNA - Am I screwing up the LoadContent for Texture2D?
I've read forum threads and questions and I done just about everything. I need to know what am I screwing up here.

Here's the code in the constructor.

```
Content.RootDirectory = "GameStateContent";
//Content.RootDirectory = "Content";

```

And this is in the LoadContent method

```
 menu = this.Content.Load<Texture2D>("mainmenu");

```

And here's the image screen shot of the folder structure. https://i.stack.imgur.com/HnndE.png

Any helps on this?

Thanks.

# Answer
Your problem is that you are changing the root directory to the wrong thing!

Based on your screenshot, your content project is called "GameStateContent", and using the default template will be created in a directory called "GameStateContent". That is the directory to which Visual Studio will copy all the content files you drag onto that content project (if they are not there already).

But the **output directory** (the thing in brackets, in Solution Explorer) is still "Content". This is where the content project outputs the XNB files that it builds from your input files. So if you tell XNA that the content root directory is "GameStateContent" then it will be looking in the wrong place!

If you click the project and press F4 to bring up the properties window, you can change the root directory.

The `ContentManager` in XNA basically looks for XNB files in the directory you specify, next to the game executable. You can go in and look at that directory in your project output directory. It will probably be:

`GameState\bin\x86\Debug\Content`

Go in and have a look for it, check it has the right name and contains the right XNB files.

I don't understand why your *game* project has a "Content" directory (or bin and obj, for that matter). Or why there's another "Content" directory in your GameStateContent project. You can probably safely remove those.

Providing you haven't made any other strange changes, you should be able to simply set:

```
Content.RootDirectory = "Content";

```

and have it work.
> 10 votes

# Answer
Your images still need to go in the Content folder of your content project; and they have the same names as images in your GameState project, so I presume there will be a conflict there and you'll need to remove or rename one set of the images. I don't think you need to modify Content.RootDirectory, but you do need to make sure your GameState project references your GameStateContent project. Instructions here.

If I may ask, why do you need the separate content project?
> 0 votes

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


title: Multiple Vertex Buffers per Mesh

text:
# Question
Title: Multiple Vertex Buffers per Mesh
I've run into the situation where the size of my mesh with all its vertices and indices, is larger than the (optimal) vertex buffer object upper limit (~8MB). I was wondering if I can sub-divide the mesh across multiple vertex buffers, and somehow retain validity of the indices. Ie a triangle with a indice at the first vertex, and an indice at the last (ie in seperate VBOs).

All the while maintaining this within Vertex Array Objects. My thoughts are, save myself the hassle, and for meshes (messes :P) such as this, just use the necessary size (\> 8MB); which is what I do at the moment. But ideally my buffer manager (wip) at the moment is using optimal sizes; I may just have to make a special case then...

Any ideas? If necessary, a simple C++ code example is appreciated.

Note: I have also cross-posted this on stackoverflow, as I was not sure as to which it would be more suitable (its partly a design question).

# Answer
> 4 votes
To quote the best answer given on StackOverflow by datenwolf.

> 8MB of vertex data is quite a lot for a single model. I'm pretty sure this model could be split into individual meshes. Good places for splitting a mesh are sharp edges, since vertices along these edges have different normal vectors are thus not identical and cannot be shared.
>
> However more important than the VBO size is the size of the render batch passed to glDrawElements (or glDrawArrays). In my experience the optimal size for render batches are between 100 to 2000 triangles, before cache pressure kicks in. But you should measure that on your system yourself.
>
> In most OpenGL applications each distinct "object" visible has some between 100 to 3000 vertices. Complex models are broken down into parts. E.g. it makes little sense to send a complex character model as whole, since that would require all the skeletal and facial animation shaders to be processed on the whole mesh. At least in the games I contributed we've split characters into each leg, each arm and hands. The head portion is split into neck and back of the head; the whole facial area is a complete own mesh, but does not contain the eyes, jaw and tounge, those are animated separately

# Answer
> 1 votes
There are a couple of ways to reduce data. First see if you can drop from float to some other format. Can you use 16bit integers for position and store a scale per mesh? Can you compress normals? Two floats might work, or two integers, or use a format like GL\_INT\_2\_10\_10\_10\_REV. Compress other vertex data in similar fashion.

How do you render your data? Triangles? Try using triangle strips and reuse vertex data as much as possible. Use primitive restart if you cannot render your whole mesh in one strip. Use something like NVidia Mesh Tools to generate this data.

At least something to start with. =)

# Answer
> 0 votes
What you could do is divide the different *inputs* into different buffers- e.g., a buffer for posiiton, a buffer for normal, etc. This is similar to how Direct3D (don't know about OGL) achieves hardware instancing- they have a buffer for static data, and a buffer for per-instance data.

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


title: XNA - Moving Background Calculations

text:
# Question
Title: XNA - Moving Background Calculations
My question is relatively hard to explain(for me, at least), so I'll go one step at a time and just tell me in the comments if it's not clear enough.

So I'm making a "Defend Your Castle" type 2D game, where two players own a castle and create units that will move horizontally to try to destroy the opponent's base. Here's a screenshot of the game:

The distance between both castles is much bigger in a real game though, bigger than the screen's width actually.

Because the distance is bigger than the screen's width, I had to implement a simple 2D camera: `Camera2D`, which only holds a Location Vector2 (and I always make sure this camera is within the field area).

Then, I just move all the game elements(castles, units, health bars) by that location, so that if a unit is at (5, 0), and the camera's location is (5, 0), then the unit's position will be moved by 5 units to the left, making it (0, 0) on the screen.

At first, I simply used a static background with mountains and clouds(yeah, those are supposed to be mountains and clouds). Obviously, this looked awful: when you moved the camera, the background would stay immobile.

Instead, I'd like to make a moving background, kind of a "scrolling" one. But rather than making a background with the same width as the distance between the castles, I'd like to make one that is a little bit smaller(but still bigger than the screen's width). I thought this would create an effect of "distance" with the background(but it might just look awful, too).

Here's the background I'm testing with:

I tried different ways, but none of them seems to work. I tried this:

```
float backgroundFieldRatio = BackgroundTexture.Width / fieldWidth;//find the ratio between the background and the field.
float backgroundPositionX = -cam.Location.X * backgroundFieldRatio;//move the background to the left

```

When I run this with `fieldWith = 1600`, `BackgroundTexture.Width = 1500` and while looking at the rightmost area, the background is offset to the left by a too big amount, and we can see the black clear color in the back, as you can see here:

I hope I explained properly what I'm trying to achieve.

Thank you for your time.

*Note: I didn't know what to look for on Google, so I thought I'd ask here.*

# Answer
The solution to your problem is actually quite simple. Instead of calculating the ratio, you calculate the possible movement-distances for camera and background and interpolate them.

For the background this is going to be: `bgMovement = fieldWidth - backgroundWidth` (results in 100)

For the camera it's `camMovement = fieldWidth - viewPortWidth`.

Assuming that the camera x-coordinate is at the left, your background position would be:

`background.X = -cam.X + (bgMovement / camMovement * cam.X)` (assuming `cam.X` goes from `0` to `camMovement`)

**Update:** If you want to stick with the `backgroundFieldRatio` (which is probably more intuitive) you can calculate it like this:

`backgroundFieldRatio = (backgroundWidth - viewPortWidth) / (fieldWidth - viewPortWidth);`

This should give you the proper movement ratio to plug into your code (or the one proposed by Andrew Russell in his answer).
> 2 votes

# Answer
First of all, you've got a bit of a maths problem:

I can't be entirely sure from the code you've posted, but if `fieldWidth` is an `int` and not a `float`, then your `backgroundFieldRatio` will not be set correctly (you are dividing two integers and getting an integer result). **It will be set to `0.0f`**. Based on the results you are getting, I suspect this is the case.

Second of all, the way you are setting your object positions based on the camera is quite ugly.

Basically when you do parallax scrolling you have multiple 2D "cameras". You should set your camera position to *target* somewhere in world space

```
Vector2 cameraTarget;

```

You can have your parallax camera as:

```
float ratio = 0.9f;
Vector2 parallaxCameraTarget = cameraTarget * ratio;

```

Then just draw your parallax scene first using the parallax camera, and then draw your main scene on top using the main camera.

Now, **don't draw sprites like this:**

```
sb.Draw(texture, position - cameraTarget, Color.White); // BAD!

```

What you should do is create a translation matrix in your `Begin` call and simply draw all your sprites in World Space:

```
Matrix camera = Matrix.CreateTranslation(-cameraTarget.X, -cameraTarget.Y, 0f);
sb.Begin(SpriteSortMode.Deferred, null, null, null, null, camera);

sb.Draw(texture, position, Color.White);

```

That way you can modify how your camera works without having to adjust every single `Draw` call!
> 4 votes

# Answer
Sounds like you are indeed talking about parallax scrolling.

(it's not c# or XNA, but the skills are transferable)
You can read up on some simple scrolling backgrounds in an sdl tutorial actually
http://lazyfoo.net/SDL\_tutorials/lesson22/index.php

(one of my all time favorite tutorials)

Then you can make multiple layers, and move them relative to the camera's position.
> 1 votes

---
Tags: xna, 2d, c#
---


title: share distribution question

text:
# Question
Title: share distribution question
I just developed a facebook game(mifia like), but the graphics I made are not good, because it is reference with some existing photo, trace with AI, and coloring it.

Therefore, I invited my friend to join me, he is a graphic designer, owns a company with his friend (I know both of them), for the shares, I expect at least 70% for me, and at most 30% for them (both of them want to join).

Therefore, they give me a counter offer, 60% for me and 40% for them, of course, I feel their counter offer is unacceptable because they only build the image in part time, and all the other work just like coding, webhosting...etc, is what I do in full time. Why they said they worth 40% is that they will make a good graphic, they can provide a advertise channel(on local magazine), etc... Actually, I don't think the game need advertisement on local magazine because the game is not target for local...

Please give me some comments on this issue (is the share fair? what is the importance of the image of the game, is it worth more than 30%), or can anyone share the experience on this.

# Answer
> 1 votes
It works like this: more share you have -\> you more work for the company (idealy, doesnt have to). If they are good designers they could really help you in making beutiful design (and that matters). If they have design company, they propably know something about marketing (maybe more than you, if you are programmer). Thats something to consider if they could bring something good (and unique you dont have) to the project. If it is true, than 40% is not that bad. It should motivate them. And you still hava majority 60%.

And for the last. It is little typical to ask for bigger share and see what happens. Maybe they will be ok with 30%.

# Answer
> 2 votes
Share percentages and negotiations are something you're going to have to work out with your partners.

That said, this related question might help: Splitting profit - Equal share vs equity investment (work & money spent = share)

---
Tags: business
---


# Question
Title: Using components in the XNA Game State Management example?
In the game state management example at the App Hub, they say that if you want to use components in the example you can extend the GameScreen to host other components inside itself.

I'm having a very hard time trying to tie this up. I tried extending the GameScreen class by adding a public property of `public List<DrawableGameCompnent> components { get; set; }` and then add my components to that list when I initialize the current screen as well as looping over the components in the LoadContent, Update and Draw methods. However, this doesn't feel like the correct way to go - mainly because it doesn't work when I get to the implementation of my GameplayScreen.

Any thoughts?

# Answer
Edit: I was way off track and rethought my answer.

You're on the right track with each screen having a collection of components. In fact, there's a class just for that:

GameComponentCollection

Each screen can implement their own list the same as Game does. The screens shouldn't need to manipulate very much in other screens or the base game - they should be relatively confined. Things like Units, Map, Player, Lights, Cameras, Physics, Timers - they all go in the screen component collection.

Stuff in the Game.Components list are usually global functionality - ScreenManager, Input, Settings - things that get read from but not manipulated.

Wall of psuedo-ish code. I stripped down the AppHub example - figured it would be easier to add things in as I need functionality rather than start with a giant codebase - easier to learn that way for me.

```
class MyGame : Microsoft.Xna.Framework.Game
{
    GameScreenManager _gameScreens;

    // I make this static, seems easier?  Mine doesn't do much
    // other than provide some helpers and shortcuts
    static InputManager _input;
    public static InputManager Input { get { return _input } }

    public void MyGame()
    {
        // ... graphics initialization ...
        _gamescreens = new GameScreenManager();
        _gameScreens.Push(new MenuScreen(_gameScreens, _graphicsDevice));
    }
}

class GameScreenManager : Microsoft.Xna.Framework.DrawableGameComponent
{
    LinkedList<GameScreen> _screens;  // Not a 'stack', but we can use it as such

    public void Push(GameScreen screen)
    {
        _screens.AddFirst(screen);
    }

    public void Pop(GameScreen screen)
    {
        _screens.RemoveFirst(screen);
    }

    // ... Update is the same as draw... just updating() ...

    /// <summary>
    /// Draw the stack of game states
    /// </summary>
    public override void Draw(GameTime time)
    {
        // Here we just draw the top node, then recursively step down while
        // the screen is not BlockDraw.  This lets a screen hide or partially
        // let anything below it display (ie, a PauseScreen only partially
        // hides the GamePlayScreen
        _Draw(_screens.First, time);
    }

    /// <summary>
    /// Recursively draw the game state stack
    /// </summary>
    private void _Draw(LinkedListNode<Screen> node, GameTime time)
    {
        node.Value.Draw(time);

        // Only draw the screen below if the current one is not blocking
        if (!node.Value.BlockDraw)
           _Draw(node.Next, time);
    }
}

abstract class Screen
{
    // Game Screen Components (UnitManager, Lights, Sound, Cameras, Player, etc...)
    // These ones can implement IUpdateable and IDrawable, and the manager here
    // handles that
    // This could easily be GameComponentCollection instead - I just wrote my own
    // as I wanted to change a few things in it.
    protected GameScreenComponentManager _components;

    // Block updates to screens below.   Override in child classes if different
    public virtual bool BlockUpdate { get { retrun true; } }

    // Block draws to screens below.  Override in child classes if different
    public virtual bool BlockDraw { get { retrun true; } }

    // In the screen constructor create its own SpriteBatch, it's
    // own SoundManager to handle playing sounds, it's own Player class, etc.
    // In this way, levels get easier too - each level is it's own screen.
    // OnLevelFinish just instantiates the next, pops the current from the manager,
    // and pushes on the new one.
    public Screen(GameScreenManager _screenManager, GraphicsDevice device, ...Other Dependancies...)
    { }

    public abstract void Initialize();
    public abstract void Update(GameTime time);
    public abstract void Draw(GameTime time);
}

```

So this is a simplified outline of the key parts.

GameScreens can create and push new screens onto the stack, and also remove themselves. Ie, then Menu Screen can push on a Settings Screen or a GamePlayScreen.

As commented, screens manage their own resources and are passed the dependencies needed to create these resources (or, register some dependencies in the service locator and just pass that into each screen). You can even create a new XNA ContentManager for each screen - leave one accessible back down in the Game for shared assets (but only a few). That way, when a screen is removed, in it's Dispose it releases only that screen's loaded assets.
> 2 votes

# Answer
Chaps,

It is certainly possible (and common) to host DrawableGameComponents 'inside' other classes. Your container class can call their Initialize, Update and Draw methods directly (as described in Zolomon's first post I think).

It is *not* the case that DrawableGameComponents automatically add themselves to the Game component collection unless you do this explicitly. Some people choose to do this in derived classes immediately on creation, but it is not required.

This leads, therefore, an alternative approach to GameScreen containment whereby you can maintain the list of child DrawableGameComponents inside the GameScreen class and simply add and remove them from the main Game.Components collection as the screen is activated and deactivated.

This is the approach used to some extent in the AppHub Ninja game sample (which uses an updated version of the original gamestate classes I think).

Hope this info is useful.
> 2 votes

# Answer
So what I did was that I made my `SpriteManager` derive from `DrawableGameComponent` and in the `LoadContent` of my `GameScreen` I add it to my game's components list with the `Game.Components.Add()` call and set its `Enable` and `Visible` settings like I want them.

Then I handle the `Enable` & `Visible` properties of my SpriteManager manually inside the `GameScreen` class so that if I bring up another screen I can turn the update or draw calls off.

Like Leniency said, `DrawableGameComponents` are global and will continue to draw on top of everything, so it has to be taken care of manually. I don't know if this is a good way to go but it seems to work.

Though, I don't understand how to make use of the `IUpdateable` and `IDrawable` interfaces.
> 0 votes

---
Tags: xna, component-based, fsm
---


# Question
Title: What to think about when designing a simple GUI for a quiz game
I am coming close to finish my first iPhone game ever, as a matter of fact also my first programming experience ever, which is a quiz game. I have all the functionality i want and is currently polishing it both from a code point of view as well as looking at the GUI.

My initial idea was not to use any specific graphics but rather focus on the game experience and simplicity and by that only using background color, orange, and white text as well as buttons. The design is based on that all ages, from learning to read, should be able to host and play this game.

However, as i am now getting close to the finish line i am starting to think what is needed from a GUI point of view.

I would like to ask for some advice what to think about when designing a GUI. Is it considered OK without any 'fancy' graphics, what is the risk without it etc.?

Also, what colors goes well together if i choose to use a simple GUI. I am thinking about color blindness etc.

In other words how do i design a good and effective GUI for a simple game as mine?

Thanks

# Answer
I would also keep the design simple, if you are trying to make it too fancy you might end up making it feel messy.

For the colors I would suggest this site : http://kuler.adobe.com/

Make sure your menu is straight forward and simple too use. To avoid color blindness issues try not too use colors like green and red together, try looking at this for the exact schemes : http://en.wikipedia.org/wiki/Color\_blindness

Good luck !
> 4 votes

# Answer
I hate to say it, but a good (or bad) UI can make (or break) your application. If possible, get a group of beta-testers together (your friends who all have iPhones?), give them a free copy of your game, and drill them about the UI.

Assuming you have more than one person who's willing to do this, you can easily see trends in good (and bad).

Beyond that, I would **pick up a book or two about usability;** that's more important than GUI, imo. If you have a great, usable UI (albeit not sparklingly beautiful), people will like your game. But if you have amazing graphics and poor usability, people will put your game down quickly.

As for colour-blindness, just don't put red on a green background (or vice versa) and you're good to go. If people who are colour-blind are playing your game (and complaining), that's a great sign that you're getting lots of users.

**Edit:** some materials that might be useful: \- Dive into Accessibility (30 day accessibility "course"), i.e. usability for disabilities

There's a book I read, but I can't find it; try googling for good resources.
> 5 votes

---
Tags: iphone, gui, accessibility
---


# Question
Title: How do I allow a player to manager several games at once with different players using game center?
I wish to do a turn based multiplayer game like Words with friends on the iphone. I would like to know the approach for the implementation to allow the user to continue games that are currently still active even after a couple of days. Is this even possible using Game Center?

# Answer
All that you need to do is store the game state somewhere persistent where all the players can get at it. For example in a database accessed via a web server. That server could also process each players turns on the game if you want it to (this helps prevent cheating). You can then easily control how long it stores the game state for. For example it would appear words with friends simply allows a maximum of 20 in progress games per player, and the game state is probably no more than a few hundred bytes per game so the storage requirements on the server would be quite small.

I'm not certain about Game Center, but a quick look suggests that as long as your game can get at the User ID of the player that's all you'd need to track the game in your database.
> 2 votes

# Answer
I would implement that functionality on your server, and have your data stored temporarily (the stuff that you know won't change) on the iPhone itself.

(edit) whoah, do you even have a server when you use game center?
> 0 votes

---
Tags: iphone, turn-based, game-center
---


title: Generating geometry when using VBO

text:
# Question
Title: Generating geometry when using VBO
Currently I am working on a project in which I generate geometry based on the players movement. A glorified very long trail, composed of quads.

I am doing this by storing a STD::Vector, and removing the oldest verticies once enough exist, and then calling glDrawArrays.

I am interested in switching to a shader based model, usually examples I see the VBO is generated at start and then that's basically it. What is the best route to go about creating geometry in real time, using shader / VBO approach

# Answer
Even though this can be application bound and depends on how much you generate geometry and how dynamic your application is, there are general rules you can follow when using VBOs.

-Specify how your VBOs will be used.

* "**Static**" means the data in VBO will not be changed (specified once and used many times),
* "**Dynamic**" means the data will be changed frequently (specified and used repeatedly)
* "**Stream**" means the data will be changed every frame (specified once and used once). "Draw"

so in your case they should be dynamic.

* Update (reuse) your existing VBOs using `glBufferSubData`, `glMapBuffer()`, `glUnMapBuffer()`, instead of creating and allocating new VBOs.

About using std::vector I think this can hurt performance if you add and remove a lot of objects, try to specify a vector with predefined size to minimize memory copy.

As for shaders, I don't think this makes any difference as long as you track transformation matrices (player position, rotation).

for more on VBOs refer to http://www.songho.ca/opengl/gl\_vbo.html
> 5 votes

# Answer
I agree with Concept3d, you don't really want to be using a vector to store this data. If I was going to be setting this up with VBOs I would just allocate off a large static chunk of memory. This allows you to setup the VBO once, then just update the data as you add verts.

I would keep track of the how many verts were in the buffer using an outside variable. Then you could easily memcpy new verts on to the end of the buffer and use shift operators to removes old verts form the front of the buffer.

As Concept said you will want to use a Dynamic VBO which will need to be uploaded into RAM every time it changes. Just make sure you pass the correct number of verts to you Draw call and not the size of the VBO, as it could be partially full.
> 2 votes

---
Tags: opengl, geometry, vertex-arrays
---


# Question
Title: Sound emmiters with panning and volume in 2D
How can I create sound emmiters that pan and change volume based on distance from the player in a 2D game?

# Answer
> 6 votes
Use `SoundEffect.CreateInstance();` to get a `SoundEffectInstance` of your chosen sound effect.

You can then `Play()` that instance while modifying its `Volume` and `Pan` properties.

Or, if it's a short, one-shot sound effect, you can simply use `SoundEffect.Play(volume, pitch, pan);` to play it at your chosen volume and panning.

Here is some code that I have used in the past to set the volume and panning of a `SoundEffectInstance` based on the emitting object's position and the camera:

```
public bool SetSoundForCamera(SoundEffectInstance sound, Vector2 position, float baseVolume)
{
    Vector2 screenDistance = (position-cameraCenter) / cameraHalfSize;
    float fade = MathHelper.Clamp(2f - screenDistance.Length(), 0, 1);
    sound.Volume = fade * fade * baseVolume;
    sound.Pan = MathHelper.Clamp(screenDistance.X, -1, 1);
    return fade > 0;
}

```

For a `SoundEffectInstance`, simply call that each frame while the sound is playing. You could extract the maths and use it for one-shot sounds as well.

Of course, for a 2D game, how quickly you pan and how quickly you fade out sounds as they go off screen will depend on your game. You should modify the maths to suit your own game's mood.

# Answer
> 5 votes
There is a 3D audio example on XNA's app hub. I'm pretty sure you can take the same concept for 2D.

---
Tags: xna, audio
---


title: 2D Platformer Collision Handling

text:
# Question
Title: 2D Platformer Collision Handling
I am trying to create a 2D platformer (Mario-type) game and I am some having some issues with handling collisions properly. I am writing this game in C++, using SDL for input, image loading, font loading, etcetera. I am also using OpenGL via the FreeGLUT library in conjunction with SDL to display graphics.

My method of collision detection is AABB (Axis-Aligned Bounding Box), which is really all I need to start with. What I need is an easy way to both detect which side the collision occurred on and handle the collisions properly. So, basically, if the player collides with the top of the platform, reposition him to the top; if there is a collision to the sides, reposition the player back to the side of the object; if there is a collision to the bottom, reposition the player under the platform.

I have tried ***many*** different ways of doing this, such as trying to find the penetration depth and repositioning the player backwards by the penetration depth. Sadly, nothing I've tried seems to work correctly. Player movement ends up being very glitchy and repositions the player when I don't want it to. Part of the reason is probably because I feel like this is something so simple but I'm over-thinking it.

If anyone thinks they can help, please take a look at the code below and help me try to improve on this if you can. I would like to refrain from using a library to handle this (as I want to learn on my own) or the something like the SAT (Separating Axis Theorem) if at all possible. Thank you in advance for your help!

```
void world1Level1CollisionDetection()
{
for(int i; i < blocks; i++)
{
    if (de2dCheckCollision(ball,block[i],0.0f,0.0f)==true)
    {
        de2dObj ballPrev;
        ballPrev.coords[0] = ball.coords[0];
        ballPrev.coords[1] = ball.coords[1];
        ballPrev.coords[2] = ball.coords[2];
        ballPrev.coords[3] = ball.coords[3];
        ballPrev.coords[0] -= ball.xspeed;
        ballPrev.coords[1] -= ball.yspeed;
        ballPrev.coords[2] -= ball.xspeed;
        ballPrev.coords[3] -= ball.yspeed;

        int up = 0;
        int left = 0;
        int right = 0;
        int down = 0;

        if (ballPrev.coords[0] < block[i].coords[0] && ballPrev.coords[2] < block[i].coords[0] && (((ball.coords[1] < block[i].coords[1]) || (ball.coords[3] < ball.coords[1]))  || ((ball.coords[1] < block[i].coords[3]) || ball.coords[3] < block[i].coords[3])))
        {
            left = 1;
        }

       if (ballPrev.coords[0] > block[i].coords[2] && ballPrev.coords[2] > block[i].coords[2] && (((ball.coords[1] < block[i].coords[1]) || (ball.coords[3] < ball.coords[1]))  || ((ball.coords[1] < block[i].coords[3]) || (ball.coords[3] < block[i].coords[3]))))
        {
            right = 1;
        }
        if(ballPrev.coords[1] < block[i].coords[1] && block[i].coords[1] < ballPrev.coords[3] && ballPrev.coords[3] < block[i].coords[3])
        {
            up = 1;
        }
        if(block[i].coords[1] < ballPrev.coords[1] && ball
        {
            down = 1;
        }

        cout << left << ", " << right << ", " << up << ", " << down << ", " << endl;

        if (left == 1)
        {
            ball.coords[0] = block[i].coords[0] - 18.0f;
            ball.coords[2] = block[i].coords[0] - 2.0f;
        }
        else if (right == 1)
        {
            ball.coords[0] = block[i].coords[2] + 2.0f;
            ball.coords[2] = block[i].coords[2] + 18.0f;
        }
        else if (down == 1)
        {
            ball.coords[1] = block[i].coords[3] + 4.0f;
            ball.coords[3] = block[i].coords[3] + 20.0f;
        }
        else if (up == 1)
        {
            ball.yspeed = 0.0f;
            ball.gravity = 0.0f;
            ball.coords[1] = block[i].coords[1] - 17.0f;
            ball.coords[3] = block[i].coords[1] - 1.0f;
        }
    }
    if (de2dCheckCollision(ball,block[i],0.0f,0.0f)==false)
    {
        ball.gravity = -0.5f;
    }
}
}

```

To explain what some of this code means:

The blocks variable is basically an integer that is storing the amount of blocks, or platforms. I am checking all of the blocks using a for loop, and the number that the loop is currently on is represented by integer i. The coordinate system might seem a little weird, so that's worth explaining. coords\[0\] represents the x position (left) of the object (where it starts on the x axis). coords\[1\] represents the y position (top) of the object (where it starts on the y axis). coords\[2\] represents the width of the object plus coords\[0\] (right). coords\[3\] represents the height of the object plus coords\[1\] (bottom). de2dCheckCollision performs an AABB collision detection. Up is negative y and down is positive y, as it is in most games.

Hopefully I have provided enough information for someone to help me successfully. If there is something I left out that might be crucial, let me know and I'll provide the necessary information. Finally, for anyone who can help, providing code would be very helpful and much appreciated.

Thank you again for your help!

**Edit**: I have updated my code with a new algorithm that checks where the ball was previously before collision. Corner cases work on that single platform correctly now, but when I have a wall of objects, I keep can really slide against it, but if I move towards the wall while sliding, I pass through it and an essentially now standing on top of a block inside the wall. Also, there is a jittering effect that happens when I am on the ground, where the ball is constantly going up and down.

# Answer
> 1 votes
Thanks for all of the help, guys, and sorry for the late response.

I have taken all of these ideas into consideration, and they are helped me fix the issue. If anyone is curious to know how I solved the original and full problem, look here on Stack Overflow for the full answer (including explanations on handling collision more properly). The person who answered my question was really generous and provided a diagram, so that should help those who also have this problem.

Thanks to the following people for helping me with this problem:

* DanTup - Danny Tuppeny
* bummzack
* ghostonline
* ultifinitus

I appreciate it very much!

# Answer
> 6 votes
If I understand your code correctly, you compensate for the collision by offsetting the ball by a fixed amount without affecting its velocity. The reason your ball acts jittery is that although its position is corrected based on the collision, its velocity is still aimed at the colliding object. Because of this velocity, the ball is still moving towards the colliding block, and will collide after a few frames offsetting it again.

Perhaps the most simple solution to this is making sure the velocities are reset upon collision, making sure the ball will not move towards the block after being offset.

# Answer
> 5 votes
You don't show any code that's handling movement/velocity of the ball. If you don't stop/bounce the ball, then the very next frame your ball will move back into the block, and get "moved" back, so it'll probably get "stuck" on the side of the block.

If this isn't it, if you can more specific on the problems and/or post more code, someone might be able to help better :-)

# Answer
> 4 votes
Well You can always do what I did, however poorly implemented it was on my part, I have a simple method in my "being" class called update\_prev\_pos(), which does just that, it stores your current position in a struct to look at later. In my collision resolution function I look at the position of the side in question. If the side was previously outside of the object, then that side must be corrected.

I'm using a two pass method to check and resolve collisions. What I would recommend doing is checking all x-axis collisions, then all y-axis collisions, That way you won't get stuck on objects you shouldn't. happy colliding =)

---
Tags: c++, opengl, 2d, collision-detection, sdl
---


# Question
Title: Does one need normals for a strictly 2d Game?
I'm starting to learn OpenGL by creating a pure 2D game.

I have to decide on the format of the Vertices. Do I need a normal component? Or is this for a 2d component not needed?

My gut feeling says I won't need it since everything is flat. But perhaps I need it for some shader or other thing I don't see yet.

# Answer
> 9 votes
Does one *need* normals for a 2D game? No. You don't even need normals for a 3D game if you're not going to bother with lighting. However, normals and lighting very much can apply to 2D games. You just go about it in a different way. Rather than explicitly defining a 3D normal vector that aligns with your vertex, you can define a normal map that lines up with your 2D graphics. This lets you have incredibly epic lighting even in a 2D game.

# Answer
> 4 votes
Strictly speaking, the normal component will be ignored if you've turned off lighting. If you're able to write your own shaders in whatever language/toolkit you're using then you can make absolutely sure they're not used.

# Answer
> 1 votes
If you are drawing your triangles in a 3D space, and then viewing everything from the side to make it look 2D (which is what you should be doing), then you'll need normals in order to be able to draw lights over top of your quads.

If you don't light anything, then you won't need normals.

My recommendation since you're asking this question, is to omit normals for now, regardless of what your plans are later. It won't be hard to add them later if you need them.

# Answer
> 1 votes
You don't need normals unless you're doing lighting simulations. They're fairly trivial to add in once you need them, compared to the actual difficulty of writing lighting shaders.

# Answer
> 0 votes
Only you know whether you'll need normals in a 2d game. They may make sense - DOOM, for instance, had normals even though it was a 2d game (yes yes, it looked pretty 3d, but technically it was still a 2d game).

One good reason for having normals in a 2d game would be to be able to check whether you're inside or outside some shape. It may also accelerate wall collision response (knowing the direction to push objects out of the wall).

There's no reason to give the normals to OpenGL or whatever rendering package you use if it doesn't need it for anything (like the lighting pretty much everyone else has pointed out).

# Answer
> -1 votes
What sort of game is it? If you have a top-down perspective, normals might come in handy for strafing movement of your characters (you know, shifting position along the *normal* of the direction the character is facing)

Normals are also useful for quite a range of steering behaviours. But a link says more than thousand words: http://www.red3d.com/cwr/steer

---
Tags: opengl, 2d, normals
---


title: Beat detection and FFT

text:
# Question
Title: Beat detection and FFT
I am working on a platformer game which includes music with beat detection. I am currently detecting beats by checking for when the current amplitude exceeds a historical sample. This doesn't work well with genres of music, like rock, which have a pretty steady amplitude.

So I looked further and found algorithms splitting the sound into multiple bands using FFT... then I found the Cooley-Tukey FFt algorithm

The only problem I'm having is that I am quite new to audio and I have no idea how to use that to split the signal up into multiple signals.

So my question is :

How do you use a FFT to split a signal into multiple bands ?

Also for the guys interested, this is my algorithm in c# :

```
// C = threshold, N = size of history buffer / 1024
    public void PlaceBeatMarkers(float C, int N)
    {
        List<float> instantEnergyList = new List<float>();
        short[] samples = soundData.Samples;

        float timePerSample = 1 / (float)soundData.SampleRate;
        int sampleIndex = 0;
        int nextSamples = 1024;

        // Calculate instant energy for every 1024 samples.
        while (sampleIndex + nextSamples < samples.Length)
        {

            float instantEnergy = 0;

            for (int i = 0; i < nextSamples; i++)
            {
                instantEnergy += Math.Abs((float)samples[sampleIndex + i]);
            }

            instantEnergy /= nextSamples;
            instantEnergyList.Add(instantEnergy);

            if(sampleIndex + nextSamples >= samples.Length)
                nextSamples = samples.Length - sampleIndex - 1;

            sampleIndex += nextSamples;
        }

        int index = N;
        int numInBuffer = index;
        float historyBuffer = 0;

        //Fill the history buffer with n * instant energy
        for (int i = 0; i < index; i++)
        {
            historyBuffer += instantEnergyList[i];
        }

        // If instantEnergy / samples in buffer < instantEnergy for the next sample then add beatmarker.
        while (index + 1 < instantEnergyList.Count)
        {
            if(instantEnergyList[index + 1] > (historyBuffer / numInBuffer) * C)
                beatMarkers.Add((index + 1) * 1024 * timePerSample);
            historyBuffer -= instantEnergyList[index - numInBuffer];
            historyBuffer += instantEnergyList[index + 1];
            index++;
        }
    }

```

# Answer
Well, if your input signal is real (as in, each sample is a real number), the spectrum will be symmetric and complex. Exploiting the symmetry, usually FFT algorithms pack the result by giving you back only the positive half of the spectrum. The real part of each band is in the even samples and the imaginary part in the odd samples. Or sometimes the real parts are packed together in the first half of the response and the imaginary parts in the second half.

In formulas, if X\[k\] = FFT( x\[n\] ), you give it a vector i\[n\] = x\[n\] , and get an output o\[m\], then

```
X[k] = o[2k] + j·o[2k+1]

```

(although sometimes you get X\[k\] = o\[k\] + j·o\[k+K/2\], where K is the length of your window, 1024 in your example). By the way, j is the imaginary unit, sqrt(-1).

The magnitude of a band is computed as the root of the product of this band with its complex conjugate:

```
|X[k]| = sqrt( X[k] · X[k]* )

```

And the energy is defined as the square of the magnitude.

If we call a = o\[2k\] and b = o\[2k+1\], we get

```
X[k] = a + j·b

```

therefore

```
E[k] = |X[k]|^2 = (a+j·b)·(a-j·b) = a·a + b·b

```

Unrolling the whole thing, if you got o\[m\] as output from the FFT algorithm, the energy in the band k is:

```
E[k] = o[2k] · o[2k] + o[2k+1] · o[2k+1]

```

(Note: I used the symbol · to indicate multiplication instead of the usual * in order to avoid confusion with the conjugation operator)

The frequency of the band k, assuming a sampling frequency of 44.1Khz and a window of 1024 samples, is

```
freq(k) = k / 1024 * 44100 [Hz]

```

So, for example, your first band k=0 represents 0 Hz, k=1 is 43 Hz, and the last one k=511 is 22KHz (the Nyquist frequency).

I hope this answers your question about how do you get the energy of the signal per band using the FFT.

**Addendum**: Answering your question in the comment, and assuming you are using the code from the link you posted in the question (The Cooley-Tukey algorithm in C): Let's say you have your input data as a vector of short ints:

```
// len is 1024 in this example.  It MUST be a power of 2
// centerFreq is given in Hz, for example 43.0
double EnergyForBand( short *input, int len, double centerFreq)
{
  int i;
  int band;
  complex *xin;
  complex *xout;
  double magnitude;
  double samplingFreq = 44100.0;

  // 1. Get the input as a vector of complex samples
  xin = (complex *)malloc(sizeof(struct complex_t) * len);

  for (i=0;i<len;i++) {
    xin[i].re = (double)input[i];
    xin[i].im = 0;
  }

  // 2. Transform the signal
  xout = FFT_simple(xin, len);

  // 3. Find the band ( Note: floor(x+0.5) = round(x) )
  band = (int) floor(centerFreq * len / samplingFreq + 0.5);

  // 4. Get the magnitude
  magnitude = complex_magnitude( xout[band] );

  // 5. Don't leak memory
  free( xin );
  free( xout );

  // 6. Return energy
  return magnitude * magnitude;
}

```

My C is a bit rusty (I am mostly coding in C++ nowadays), but I hope I didn´t make any big mistake with this code. Of course if you were interested in the energy of other bands it makes no sense to transform the whole window for each of them, that would be a waste of CPU time. In that case do the transformation once and get all the values you need from xout.
> 14 votes

# Answer
Here is a great read about beat detection in games.

http://www.badlogicgames.com/wordpress/?p=99

It's a part of a 8 part blog series on the matter.

http://www.badlogicgames.com/wordpress/?category\_name=onset-detection-tutorial
> 3 votes

# Answer
I haven't done this or read much about it myself, but my first shot is something like this:

First of all, you'll need to apply a window function to get a time dependent spectrum with the FFT. The beat usually lies in the lower frequencies, so apply *another* FFT with a bigger time window on the intensities of some of these frequencies (for simplicity start with only 1 at e.g. 100 Hz and see if that is reliable enough). Find the peak in this spectrum and that frequency is a guess for the beat.
> 0 votes

---
Tags: game-design, c#, software-engineering, algorithm, audio
---


# Question
Title: How would you code an AI engine to allow communication in any programming language?
I developed a two-player iPhone board game. Computer players (AI) can either be local (in the game code) or remote running on a server. In the 2nd case, both client and server code are coded in Lua. On the server the actual AI code is separate from the TCP socket code and coroutine code (which spawns a separate instance of AI for each connecting client).

I want to be able to further isolate the AI code so that that part can be a module coded by anyone in their language of choice. How can I do this? What tecniques/technology would enable communication between the Lua TCP socket/coroutine code and the AI module?

# Answer
A socket based messaging scheme can be used to allow any arbitrary language to interact with the AI. You could use binary based messages, xml, text, etc. Just clearly define what the message format is and what messages you will send and receive.

This technique works relatively well for light to modest communication handling. There is a latency penalty associated with it of course, but since your game is a board game style it doesn't have to run in real-time.
> 8 votes

# Answer
For any language X, you can't know what interop feature it does or does not have- no language is expected to provide any interoperation features. The most reliable is C-style, as that is (almost certainly) what your OS uses, although this doesn't mean that the language actually exposes it.

Perhaps the most independent would be using a named pipe provided by the OS and sending through say, XML messages. However, this is a tad extreme- most encapsulation schemes stop short of encapsulating the authoring language.
> 0 votes

---
Tags: game-design, ai, lua
---


# Question
Title: Multiplayer / Networking options for a 2D game with physics
**Summary:**

My 50% finished 2D sidescroller with Box2D as physics engine should have multiplayer support in the final version. However, the current code is just a singleplayer game.

* What should I do now?
* And more important, how should I implement multiplayer and combine it with singleplayer?
* Is it a bad idea to code the singleplayer mode separated from multiplayer mode (like Notch did it with Minecraft)?

The performance in singleplayer should be as good as possible (Simulating physics with using a loopback server to implement singleplayer mode would be a problem there)

**Full background / questions:**

I'm working on a relatively large 2D game project in C++, with physics as a core element of it. (I use Box2D for that)

The finished game should have full multiplayer support, however I made the mistake that I didn't plan the networking part properly and basically worked on a singleplayer game until now.

I thought that multiplayer support could be added to the almost finished singleplayer game in a relatively easy and clear way, but apparently, from what I have read this is wrong.

I even read that a multiplayer game should be programmed as one from the beginning, with the singleplayer mode actually just consisting of hosting an invisible local server and connecting to it via loopback. (I found out that most FPS game engines do it that way, an example would be Source)

So here I am, with my half finished 2D sidescroller game, and I don't really know how to go on.

Simply continueing to work on the singleplayer / client seems useless to me now, as I'd have to recode and refactor even more later.

First, a general question to anybody who possibly found himself in a situation like this:

* How should I proceed?

Then, the more specific one - I have been trying to find out how I can approach the networking part for my game:

**(Possible solutions:)**

* Invisible / loopback server for singleplayer

This would have the advantage that there basically is no difference between singleplayer and multiplayer mode. Not much additional code would be needed.

A big disadvantage: Performance and other limitations in singleplayer. There would be two physics simulations running. One for the client and one for the loopback server.

Even if you work around by providing a direct path for the data from the loopback server, through direct communcation by the threads for example, the singleplayer would be limited.

This is a problem because people should be allowed to play around with masses of objects at once.

* Separated singleplayer / Multiplayer mode

There would be no server involved in singleplayer mode.

I'm not really sure how this would work. But at least I think that there would be a lot of additional work, because all of the singleplayer features would have to be re-implemented or glued to multiplayer mode.

* Multiplayer mode as a module for singleplayer

This is merely a quick thought I had. Multiplayer could consist of a singleplayer game, with an additional networking module loaded and connected to a server, which sends and receives data and updates the singleplayer world.

In the retrospective, I regret not having planned the multiplayer mode earlier. I'm really stuck at this point and I hope that somebody here is able to help me!

# Answer
> 4 votes
You will find an example (with source) of latency-proof networked physics here: http://gafferongames.com/2010/03/11/gdc-2010-networked-physics-slides-demo/

But first, focus on the gameplay of your multiplayer mode. If it is competitive and cheating (through reverse-engineering or packet tampering) is an issue, the proposed solution might not fit your needs.

Let's say your multiplayer mode is cooperative. For your singleplayer mode. I would just run the same game engine, but with the network features disabled, so that the world would not be populated with any other player characters. You would also probably want to load specific data for the multiplayer mode, to adjust the content to the number of players.

# Answer
> 1 votes
This book might be of some help to you. I believe that the company that I work for used the examples in this book even though we're not a game shop.

http://www.amazon.com/Multiplayer-Programming-Prima-Techs-Development/dp/0761532986/ref=pd\_sim\_b\_7

# Answer
> 1 votes
I think that the positives of a local loop back server, far out weigh the negatives. The amount of code reduction is extremely valuable, in my opinion.

With regard to running redundant physics simulations, you should look into server ticks, Valve has a great writeup on it here. In a local server environment, you maybe able to remove the "client simulation" and simply send full-world updates, in a local-only situation to avoid the redundant physics simulations since you'll have plenty of bandwidth.

---
Tags: game-design, networking, multiplayer, design-patterns
---


# Question
Title: Best memory allocation strategy for iOS?
I'm debating myself about memory allocation on iOS. I write most of my code in C++ and I really like using ObjectPools, FreeLists, etc. In order to pre-allocate a lot of the stuff that I'll be constantly "alloc/dealloc" during the course of my game, ( like particles, game entities, etc ).

Still on iOS, it's not like we are developing for a console like PSP, where I can know for fact that I'll get a fixed amount of memory. iOS , will issue "memory warnings" when the system needs memory.

Does anyone have some suggestions about this ? Is it too serious since the new iPod touch/iPhone 4 are carrying more RAM ? or it's still a big concern?

# Answer
> 10 votes
Use your common memory management sense. Use pools/freelists for things that are frequently allocated and deallocated (i.e. particles), free memory blocks that aren't in use. However, don't try to preallocate large chunks of memory upfront. iOS doesn't guarantee memory nor does it swap, so any memory you have allocated is taking resources away from the system and other apps. If the system cannot get enough memory because your application is hogging all of it, then it will resort to killing your app. You should handle the applicationDidReceiveMemoryWarning for what it was designed for by deallocating as much memory as possible. Although iPhone 4 has lots of memory, but with all the multitasking features and the way people tend to use them, you may actually have less memory than you think.

(Also, don't forget to profile your app to see whether memory allocation is a bottleneck!)

# Answer
> 1 votes
To tack on a note to 5ound's answer: pay attention to the level of the memory warning. Prior to iOS 3.2 there was no way to distinguish between warnings of different severity (i.e. is the OS just sitting on a bunch of UIImages it can clear or is there really no memory left?). in 3.2 onwards you can check the level of the memory warning to determine how to react. In my experience level 1 warnings are constant, unavoidable and largely meaningless, so I wouldn't take drastic action in response to them. Although level 2 warnings are not necessarily a sign of impending doom you should probably take them seriously and start clearing any caches you can, etc.

There's a good discussion of the different levels here: https://stackoverflow.com/questions/2915247/iphone-os-memory-warnings-what-do-the-different-levels-mean

P.S. - This is more of a comment to 5ound's answer but I don't have enough rep to comment so this was my only option...

---
Tags: ios, memory-efficiency
---