title: Simultaneous game states

text:
# Question
Title: Simultaneous game states
I think I understand the basic idea behind a Finite State Machine-based game loop. But I'm trying to write a little game in which the **same object** can simultaneously be in multiple, independent states. At least that's what I want to do.

To give you an idea: `Robot` may be in `FleeState` and `FireLaserState` at the same time, besides in each of them individually at any time.

Would something like this be possible using the FSM pattern? Or ought I to look elsewhere?

After all, does the whole idea make sense?

**Pasted from my comment below:** A little clarification of why I'd like states to be kept separate: I want the player to have the ability to program simple state changes before a game... say "if (health\_is\_way\_too\_low) flee". But then I want multiple such rules to be active simultaneously in order to keep the game interesting, and cannot know beforehand which other states may be active.

# Answer
The main idea behind a FSM is that, at any moment, it can be found in a single state from a finite number of possible states. If you find yourself needing more than this, try to see if those multiple states can't actually be merged in one single state. If you feel like taking the dirt road is not that much of a bad idea, you can build a FSM base and some extra behavior on top of it, to allow for a lot more flexibility. As I said in my comment, this whole object-in-multiple-states makes sense in quantum physics and is a really funky subject to think of, if you ask me.

Similar situation of mine: I've recently tried to design a simple lamp with a smooth turn on/off effect as a FSM. When turned on, its intensity would gradually increase. The opposite when turned off. Keeping just the states: On, Off, Turning On, Turning Off was insufficient. When saving the game, for example, I also had to store the current light intensity when turning on or off, so that the process may be resumed. While, obviously, the number of possible states here was not equal to infinity (intensity goes between \[min, max\]), there were just too many to enumerate and merge. I had to (partially) break the FSM idea by storing the intensity step alongside the state. Perhaps you could apply something like this?

Regarding your latest edit, take a look at the gambits system in Final Fantasy XII:

The player is able to program the AI-controlled companions in a very nice way. Conditions are checked on each turn, one after the other. If a particular condition is met, the character performs the action and stops checking the rest, since he only has the ability to perform one action per turn. But in your case, you can make it not stop the checking process, and achieve the feeling of simultaneous *actions*.

Noticed how I made the word "actions" stand out? If I were you, I'd use a list-like structure, or perhaps a stack-like structure, to keep track of multiple actions that the robot has to take at any given time. If the robot has to flee and shoot at the same time, the actions would be: `[Flee, Shoot]`. Every time you think it is necessary, you can go through the main table of `{condition, action}` pairs and build the list or stack of actions that the robot has to perform.

You can build this behavior on top of a FSM base, like I did with my lamp. If the robot is in state `COMBAT`, it does the table of `{condition, action}` pairs check. Perhaps its health is below 50%? Add action "Flee" to the stack! But don't stop there. If there are some enemies still in range, also add "Shoot" to the stack.
> 5 votes

# Answer
You have a couple choices here, you just haven't realized it yet from trying to shove round things into square holes =)

1) You haven't really defined all your states yet. Flee and Fire are independent states, adding a FleeAndFire state is the traditional way and well respected. By specializing states like this you get great control over what your actions will be and how they transition. The downside is that you need a good way to create your FSM and transitions and keep track, but there will be a finite number of states.

2) You've merged objects when they shouldn't be. Your robot is actually a RobotWheels that handles all the movement states, and probably all the other useful states for an entity in your world. On top of your RobotWheels is a RobotDefenseArray which is responsible for target acquisition decisions and firing when appropriate. The drawback is that your total entity may act "funny" unless they either use each other as inputs or react reasonably to the same trigger stimuli.

All the other options involve an AI and how it determines how your states transition; whether it is neural nets, pattern matching, procedural code, the list is endless.
> 4 votes

# Answer
I would break something like this up into slots and actions. For example, you would have a legs slot and an arms slot for your robot. Different actions take up different slots, so you can layer actions on top of each other. Here's a simple example:

```
Slot | Action
-----|-------
Head | Shoot
Arms | Shoot
Legs | Flee

```

As you can see, the `Shoot` action takes up both the `Head` and `Arms` slots. The `Flee` action takes up only the `Legs` slot, so both can be performed at the same time. If there are two pending actions that use some of the same slots, you can sort them by priority, so a `Flee` action would be more important than a `Patrol` action when a powerful enemy is around.
> 1 votes

# Answer
To me, it seems like you're running up against a common problem that the Mixin or Decorator pattern could solve. From the Wikipedia article on the Decorator Pattern:

> the decorator pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.

This sounds like what you're trying to do, no? You can also find more information about Mixins in relation to game development here.

Depending on the language you are using implementation may or may not be an easy solution. For instance, in the JavaMonkey engine every spatial entity in the scene has a linked list of objects which all implement a "control" interface. These "control" objects each have an update method that gets called from their "owner" object (the spatial scene entity) at every iteration of the game logic. This allows you to add bundles of functionality dynamically to an object.

You could, for instance, create a control that establishes a fire weapon behavior that acts independently of another behavior that flees. This functionality is easy to implement in Java with interfaces and even easier in Javascript as Mixins can be directly implemented, other languages I'm not too sure about.
> 0 votes

---
Tags: game-design, game-loop, state, fsm
---


# Question
Title: How can I convert screen coordinates to world coordinates on the floor (when the y component = 0)?
I am using the Irrlicht Engine and would like to convert the coordinates of the mouse on the screen to the floor of my world. I am currently trying to use

```
getRayFromScreenCoordinates()

```

which returns a "Ray starting from the position of the camera and ending at a length of the far value of the camera at a position which would be behind the 2d screen coodinates." Then I do this to get the position:

```
    core::line3df line = getRayFromScreenCoordinates(receiver.mousePos, device);
    irr::core::vector3df lineVector = line.getVector().normalize();
    irr::core::vector3df pos = line.start + lineVector*x;

```

`x` would be the magnitude from camera to the coordinate. However I do not know how to calculate `x` (as I don't know the coordinate yet).

The page I got the code from, written in 2003

# Answer
What you need to do is get a ray intersection against a plane which is your floor. I'm not certain how this is done in Irrlicht, but my guess is that there's some function such as:

`vector3df plane::getIntersectionWithRay(line3df)`

You can then discard the y part of the vector (or z, depending on your co-ordinate system ) as it will be equal to zero, and use the other two for a 2D vector.
> 1 votes

---
Tags: coordinates, irrlicht
---


title: What to do with old data?

text:
# Question
Title: What to do with old data?
I have a game - virtual soccer manager. It is browser based game. It is split into 'seasons' each of them takes around a half of a real year. The central game element is a soccer match, each team plays around 40-50 matches per season, there are roughly a thousand of teams.

Each match has a lot of match related data: game moments description, amount of experience earned by each team player during each match, etc...

Web site has around 200-600 users in different times and exists almost 8 years. For this time game get a ton of data. All data are saved in MySQL DB (5.1).

My problem is that tables size is growing constantly. It is not the problem on its own, but when I do some data maintenance (add new fields into existing tables, change field type, etc.) it takes a ton of time to execute those queries.

From one side, I don't really want to delete aged data (that is more than 5 years old) as potentially users could be interested in looking into them. from another side, 5 years old and older data are not really concerning and COULD be deleted.

Question: **what is good practices for keeping/archiving data in general and for online games in particular?**

P.S. Probably I should ask on another site?

# Answer
> 3 votes
If you want to limit table size, I'd suggest to split single large tables into a few distinct separate tables.

For example, say you have a `Matches` table that records all matches that ever took place. If only the *current season* is what is relevant, create 2 tables: `currentSeasonMatches` and `oldMatches`. When a season is over, move all the old matches to `oldMatches` and clear `currentSeasonMatches`. Or, you could break the data by year: `matches2011`, `matches2012`, `matches2013`. of course, it all matters **how accessible you need that older data to be**.

If database server size is an issue, **render all the data to an HTML tabular format that viewers can view**, and save that on a static HTML page on your website. `mysqldump` the old data and put it in a cloud somewhere.

# Answer
> 1 votes
First, do a full database backup. After you do the backup, I also recommend you load that backup back into mysql and verify it isn't corrupt. Assuming it's not, put it in a directory that is part of your regular file backups. After that, simply delete the data from the database you don't need. Or selectively copy only the data in tables that are required to start another 'season'.

As for past users wanting to view data, simply make a few 'top 100' static lists for previous years. Top 100 lists have worked for me in the past, although nowadays I just do Top 10 of specific categories.

I do this after every 'season' and purge the previous seasons data from the database. Keeps everything in tiptop shape, and also makes it really easy to edit the database structure between seasons, as there is no data in there to worry about conflicts. Only concern is the code changes that might be necessary.

This is from my personal experience with my browser rpg's. I am by no means a qualified database admin, and have simply found the above to work well for my needs based on experience.

---
Tags: game-design, multiplayer, browser-based-games, data
---


title: glDisableClientState in OpenGL

text:
# Question
Title: glDisableClientState in OpenGL
I'm just wondering why we need to call `glDisableClientState(GL_VERTEX_ARRAY)` after the drawing of a vertex array. Is it possible to just leave it there for the next drawing? Is there any side effect of doing this?

# Answer
First of all I want to mention that client-side vertex arrays are deprecated in OpenGL 3.0 and removed in OpenGL 3.1 and above.

To answer your question: you can call `glEnableClientState` once and leave the state enabled as far as your drawing code requires the same state. For example, if you don't want to render normals arrays you don't want it to be enabled, so you call `glDisableClientState`.

Performance wise it's better not to change states too often, but it's *usually* impractical to leave some states always enabled, hence affecting the whole application.

Also note that drivers that support OpenGL 3 and above will use temporary vertex buffer objects (VBOs) whenever you use non-VBO functions, because it needs to copy your data in case you modified it in your user space code.
> 1 votes

---
Tags: opengl
---


title: OpenGL global/local states

text:
# Question
Title: OpenGL global/local states
OpenGL has so many APIs which can modify different states. It's not so obvious whether an API has global effect or local effect.

For example, rumour says `glTexEnv` has global effect while `glTexParameter` has local effect (it only affects the current bound texture). Is this true? How to determine whether an API has global or local effect?

# Answer
Given the definitions you've outlined here, "global effect" means "context state" and "local effect" means "object state".

Broadly speaking, no. OpenGL does not have a *consistent* naming scheme for what functions change object state and what functions change global state. This is primarily due to the fact that many of the functions that change object state were *once* only changing global state.

Yes, even `glTexParameter`. Texture objects only came into existence in GL 1.1. The reason OpenGL requires you to bind objects to modify them is precisely for this: so that you *can't tell the difference*. This way, if they later decide to make some state "object state", you would use the same APIs to set that data, rather than having separate function calls for the "old way" and the "new way".

This is better nowadays in core profile OpenGL, as most functions that modify object state are named in accord with the objects that they modify. All of the `glTex` functions modify texture object state (`glTexEnv` was removed from OpenGL in 3.1). All of the `glBuffer` functions modify buffer object state. All of the `glFramebuffer` functions modify framebuffer object state.

But even here, there are exceptions. `glUniform` modifies program object state, but since it doesn't take the program as a parameter, it omits the word "Program" from the name (unlike `glProgramParameter` or the more recent `glProgramUniform`). Futhermore, older calls like `glReadBuffer` and `glDrawBuffer(s)` modify *framebuffer object state*, despite not using the word "framebuffer". Again, that's for backwards compatibility reasons; the `glFramebuffer` functions were all new functionality, but setting the read and draw buffers was old stuff, and thus had to use the old APIs.

So generally speaking, no, there is no way to be *certain* just from looking at a function's name to know whether it modifies context state or object state.
> 4 votes

# Answer
The OpenGL API is pretty clear, the official documentation and a good book will get you going with it easily!

You can check things like that directly by looking up the reference of the function. For example, in the sample you gave us, its made clear in the name of the function itself, one configures the texture environment, which means the "space" of all textures, the other a parameter of a texture, which applies to the currently bound texture for that target, at that texture unit.

Hope its clear enough.. :)
> 3 votes

---
Tags: opengl
---


title: Recommended collision response needed

text:
# Question
Title: Recommended collision response needed
In my game, I have

1. Player class
2. Enemy class
3. Wall class
4. GameComponents class ( Which is the base class for Player, Enemy and Wall)

The rules are

* Enemy chase Player, if collided with Walls, destroy Walls
* Player run away from Enemy, Player can generate Walls

Currently, I have the code for Enemy to destroy Wall setup. For it, after detected that it has intersected with Walls, it has a function to deduct the Wall's HP. Meanwhile, I set the speed for the Enemy to 0, so it stops moving. And after checking the Wall's HP is less than 1, Enemy's speed become 1 again ( Default speed )

Now, to Player, the Player cannot destroy Walls. So he has to move away from them. I use the function collision(Vector tempPos, bool shouldBeSolid) for collision detection & collision response. But due to the way it's setup, even though after the Wall has been "destroyed" by the Enemy. My Player still couldn't pass through them. I'm having difficulties of getting rid of the Walls ( Or their Rectangle ). I have thought of resetting the Rectangle ( Rectangle.Empty, basically reset all the values it has to 0 , which is x, y, width , height ), but that doesn't work.

So right now I'm asking for some better collision response method than the current function I use...

The codes are here...

**GameComponents class** class GameComponents { #region Variable protected Texture2D texture; public Rectangle area; protected string textureName; public bool isSolid = false;

```
    public Vector2 pos;
    public bool spawned = true;
    public float speed = 0.0f;
    public float rotation = 0.0f;
    public float scale = 1.0f;
    public Color color = Color.White;
    public SpriteEffects effect = SpriteEffects.None;

    protected bool enableDebugMessage = false;
    protected int currentFrameX = 0;
    protected int currentFrameY;
    protected int spritesCount = 1;
    protected int animationSpeed = 1;
    protected Point spritesFrame;
    protected Rectangle size;
    protected bool execMoveFunction = true;
    protected Rectangle newArea;
    #endregion

    public GameComponents(Vector2 pos)
    {
        this.pos = pos;
    }

    public virtual void LoadContent(ContentManager c)
    {
        texture = c.Load<Texture2D>(this.textureName);
        area = new Rectangle(0, 0, texture.Width / spritesCount + 2, texture.Height + 2);
    }

    public virtual void Update()
    {
        if (!spawned) return;

        UpdateArea();

        if (execMoveFunction)
        {
            pushTo(speed, rotation);
        }
    }

    public virtual void Draw(SpriteBatch sb)
    {
        if (!spawned) return;

        Vector2 center = new Vector2(texture.Width / 2, texture.Height / 2);

        Animate();
        sb.Draw(texture, pos, size, color, MathHelper.ToRadians(rotation),
            center, scale, effect, 0);
    }

    public bool collideWith(Vector2 pos, bool dontCheckForSolidity)
    {
        foreach (GameComponents component in Factory.componentList)
        {
            if (component.isSolid || !dontCheckForSolidity)
            {
                if (component.area.Intersects(area))
                {
                    return true;
                }
            }
        }
        return false;
    }

    // The problem function
    public virtual bool collision(Vector2 tempPos, bool shouldBeSolid)
    {
        newArea = new Rectangle(area.X, area.Y, area.Width, area.Height);
        newArea.X += (int)tempPos.X;
        newArea.Y += (int)tempPos.Y;

        foreach (GameComponents component in Factory.componentList)
        {
            if (component.isSolid && shouldBeSolid)
            {
                if (component.area.Intersects(newArea))
                {
                    return true;
                }
            }
        }
        return false;
    }

    public void UpdateArea()
    {
        area.X = (int)pos.X - texture.Width / 2;
        area.Y = (int)pos.Y - texture.Height / 2;
    }

    public virtual void pushTo(float speed, float dir)
    {
        float newX = (float)Math.Cos(MathHelper.ToRadians(dir));
        float newY = (float)Math.Sin(MathHelper.ToRadians(dir));
        pos.X += speed * (float)newX;
        pos.Y += speed * (float)newY;
    }

    public bool intersects(Rectangle R1, Rectangle R2)
    {
        if (R1.Left <= R2.Right && R2.Left <= R1.Right
                                &&
            R1.Top <= R2.Bottom && R2.Top <= R1.Bottom)
        {
            return true;
        }

        return false;
    }

    private void Animate()
    {
        size = new Rectangle(currentFrameX * spritesFrame.X, currentFrameY * spritesFrame.Y, spritesFrame.X, spritesFrame.Y);

        if (currentFrameX < spritesCount - 1)
        {
            currentFrameX += animationSpeed;
        }
        else
        {
            currentFrameX += -currentFrameX;
        }
    }

    public float point_direction(float x, float y, float x2, float y2)
    {
        float diffx = x - x2;
        float diffy = y - y2;
        float adj = diffx;
        float opp = diffy;
        float tan = opp / adj;
        float res = MathHelper.ToDegrees((float)Math.Atan2(opp, adj));
        res = (res - 180) % 360;
        if (res < 0) res += 360;
        return res;
    }
}

```

} **Player class** {

```
class Player : GameComponents
{
    private KeyboardState key;
    private int speed;
    private Vector2 prevPos;
    public static Vector2 position;
    public static int HP = 100;
    public static int maxHP = 100;

    public Player(Vector2 pos) : base(pos)
    {
        pos = this.pos;
        position = pos;
        speed = 4;
        textureName = "P";
        HP = maxHP;
    }

    public override void Update()
    {
        if (!spawned) return;
        key = Keyboard.GetState();

        Input(key);

        prevPos = pos;
        position = pos;
        base.Update();
    }

    private void Input(KeyboardState key)
    {
        if (key.IsKeyDown(Keys.W)
            && !collision(new Vector2(0, -speed), true))
        {
            pos.Y -= speed;
        }
        if (key.IsKeyDown(Keys.A)
            && !collision(new Vector2(-speed, 0), true))
        {
            pos.X -= speed;
        }
        if (key.IsKeyDown(Keys.S)
            && !collision(new Vector2(0, speed), true))
        {
            pos.Y += speed;
        }
        if (key.IsKeyDown(Keys.D)
            && !collision(new Vector2(speed, 0), true))
        {
            pos.X += speed;
        }
    }
}

```

} **Enemy class** {

```
class Enemy : GameComponents
{
    private int seeingRange = 400;
    private int HP;
    private int MaxHP = 50;
    private float spd;

    public Enemy(Vector2 pos) : base(pos)
    {
        pos = this.pos;
        textureName = "EDebug";
        damage = 25;
        HP = MaxHP;
        spd = 1;
        execMoveFunction = false;
    }

    public override void Update()
    {
        if (HP < 0 )
        {
            spawned = false;
            HP = MaxHP;
        }
        MoveToPlayerIfInRange();
        DestroyWall();

        base.Update();
    }

    private void MoveToPlayerIfInRange()
    {
        if (DistanceBetween(Player.position.X, Player.position.Y, pos.X, pos.Y) < seeingRange)
        {
            // Rotate to face Player
            rotation = point_direction(pos.X, pos.Y, Player.position.X, Player.position.Y);
            MoveToPlayer();
        }
    }

    private void DestroyWall()
    {
        foreach ( GameComponents c in Factory.componentList)
        {
            if (c.GetType() == typeof(Wall))
            {
                if (intersects(area, c.area))
                {
                    spd = 0;
                    Wall w = (Wall)c;
                    if (w.HP > 0) w.Damage(1);
                    if (w.HP < 1) spd = 1;
                }
            }
        }
    }

    private void MoveToPlayer()
    {
        if (Player.position.X < pos.X) pos.X -= spd;
        if (Player.position.X > pos.X) pos.X += spd;
        if (Player.position.Y < pos.Y) pos.Y -= spd;
        if (Player.position.Y > pos.Y) pos.Y += spd;
    }

    public static float DistanceBetween(float x1, float y1, float x2, float y2)
    {
        float xSquare = (x1 - x2) * (x1 - x2);
        float ySquare = (y1 - y2) * (y1 - y2);
        double sumOfXYSquare = xSquare + ySquare;
        float dist = (float)Math.Sqrt(sumOfXYSquare);

        return dist;
    }
}

```

} **Wall class** {

```
class Wall : GameComponents
{
    public int HP;
    public static Vector2 position;

    public Wall (Vector2 pos) : base (pos)
    {
        pos = this.pos;
        isSolid = true;
        textureName = "W";
        HP = MaxHP;
    }

    public override void Update()
    {
        if (!spawned) return;

        if ( hp < 1 )
        {
            spawned = false;
            HP = MaxHP;
        }

        position = pos;
        base.Update();
    }

    public void Damage(int damage)
    {
        HP -= damage;
    }
}

```

} **Factory class** {

```
class Factory
{
    public static List<GameComponents> componentList = new List<GameComponents>();

    public static void Initialize()
    {
        componentList.Add(new Player(new Vector2(100 + (39 * 3) , 140)));
        componentList.Add(new Cursor(new Vector2(50, 50)));

        componentList.Add(new Wall(new Vector2(100 + (39 * 5), 100 + (36 * 2))));
        componentList.Add(new Wall(new Vector2(100 + (39 * 5), 100 + (36 * 3))));

        componentList.Add(new Spawner(new Vector2(350, 50)));

        for (int i = 0; i < 1; i++)
        {
            Enemy e = new Enemy(Vector2.Zero);
            e.spawned = false;
            componentList.Add(e);
        }
        for (int i = 0; i < 32; i ++ )
        {
            GameComponents components = new Bullet(Vector2.Zero);
            components.spawned = false;
            componentList.Add(components);
        }
    }
}

```

# Answer
> 1 votes
Ok so i'll post this in an answer to try and help you.

I'll write this in java. However, you could easily convert it to C#

Your entity classes will look something like this

```
public class Entity {

    private Vector2D position;
    private Vector2D velocity;

    private int width;
    private int height;

    public Entity(double x, double y) {
        position = new Vector2D(x, y);
        velocity = new Vector2D(0, 0);
        width = 32;
        height = 32;
    }

    //Getters and setters for position and velocity

    public Rectangle getBounds() {
            return new Rectangle((int)position.x, (int)position.y, width, height);
    }

}

```

Lets presume you would like to add 10 enemies, you would have something similar to this

```
List<Enemy> enemies = new ArrayList<Enemy>();

```

We will then add enemies to that array.

```
for (int i = 0; i < numberOfEnemy; i++) {
    Enemy enemy = new Enemy(randomX, randomY);
    enemies.add(enemy);
}

```

You would also have an array of walls too which can be added and taken away exactly the same as the enemy.

You could then loop through each enemy checking intersection with the wall and player

```
for (int i = 0; i < enemies.size(); i++) {
    Enemy tempEnemy = enemies.get(i);
    for (int j = 0; j < walls.size(); j++) {
        Wall tempWall = walls.get(i);

        if (tempEnemy.getBounds().intersects(tempWall.getBounds() {
            // Remove wall or whatever it is you want to do
        }

    }

    if (player.getBounds().intersects(tempEnemy.getBounds() {
        // --hp; etc...
    }
}

```

Are you picking up what i'm putting down? lol

Let me know if you need more clarification :)

---
Tags: xna, c#, collision-detection
---


# Question
Title: XNA- Add a content reference to a library?
Making a Game library with XNA, and I'd like to bundle it with some stock effects, if possible. But I'm having no luck attaching a Content project to the Library, so is it possible to use the Content Processor to load effects this way?

If not, how should the bundling be done? I would like the "user" (that is, someone building something with the library) not to have to deal with loading the effect, other than calling some library function with no arguments.

# Answer
> 2 votes
I just developed a similiar thing for my project and it works, but it's bad for debugging so I skipped it. What I did was implement this:

http://blogs.msdn.com/b/shawnhar/archive/2010/05/07/effect-compilation-and-content-pipeline-automation-in-xna-game-studio-4-0.aspx

I have an Engine DLL Library and in it I just created a resource file, called "Effects.resx" and added some simple effect files that aren't compiled then later with the code above implemented I just created a method for generating an effect.

```
public class DynamicContent
{
    public static Effect CreateEffect(GraphicsDevice graphicsDevice, string effectCode)
    {
        EffectContent input = new EffectContent() {  EffectCode = effectCode };
        EffectProcessor processor = new EffectProcessor();
        CompiledEffectContent content = processor.Process(input, new MyProcessorContext());

        return new Effect(graphicsDevice, content.GetEffectCode());
    }
}

```

then with my Resource file I just accessed it like this:

```
// "multitexture.fx" for example in the Resources.resx / Effects.resx
Effect effect = DynamicContent.CreateEffect(GraphicsDevice, Effects.multitexture);

```

Some things that aren't ideal about using the Pipeline is that it needs the full .NET Framework, so to be able to use the tutorial above you need to change the Target Framework by going into your Game Library Properties / Application.

This way, no files are loaded from the content directory but compiled during runtime and bundled with the Game Library as a Resource.

---
Tags: xna, xna-content-pipeline, effect
---


# Question
Title: Java 2D game programming: Different approaches to make a game loop
I am new to Java game programming, but the more I read the more I'm confused, because I've seen several different approaches to make a game loop: 1. The standard approach, that uses the Timer class (seems to be less precise). 2. The more precise approach that uses System.nanoTime. 3. A simple approach that uses scheduleAtFixedRate.

Which one should generally be preferred and where are the advantages/disadvantages of each approach? Thanks in advance for any info.

# Answer
> 7 votes
For a basic game loop, you'd run a while loop, within which you'd get the time using nanoTime(), determine how much time has passed since the last frame, then update your gamestate and render.

Using http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#nanoTime%28%29 , you can poll for the elapsed time. Basically...

```
public static void main(String [ ] args)
{
    long current_frame_time = system.nanoTime();
    long last_frame_time = current_frame_time;

    while(gameIsRunning)
    {
        last_frame_time = current_frame_time;
        current_frame_time = system.nanoTime();

        long timeTaken = current_frame_time - last_frame_time;

        //update and render game here
    }
}

```

This basic method can be improved upon, e.g. http://www.koonsolo.com/news/dewitters-gameloop/ and http://gafferongames.com/game-physics/fix-your-timestep/.

Alternatively, you could create a timer and set this timer to run your update and rendering every X milliseconds. But, there are some downsides to constructing a gameloop like that.

According to http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Timer.html: "*Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially. Timer tasks should complete quickly. If a timer task takes excessive time to complete, it "hogs" the timer's task execution thread. This can, in turn, delay the execution of subsequent tasks, which may "bunch up" and execute in rapid succession when (and if) the offending task finally completes.*"

According to http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Timer.html#scheduleAtFixedRate%28java.util.TimerTask,%20java.util.Date,%20long%29: "*In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).*"

Since you usually don't know ahead of time how long a game loop takes, setting a timer to execute your gameloop every X milliseconds (depending on target frame rate) could lead to a few bunched up frames, which would execute whenever a frame is finished instead of when a frame is scheduled. When that happens... why use a timer in the first place?

Now, don't get me wrong, timer is not a bad class, but it is usually better suited to small tasks which need to be done periodically or at a certain time, e.g. a mail client might want to check for new mail every 5 minutes, or a counter might get decremented every second to display a countdown before the start of a race.

# Answer
> 7 votes
I would not put the main loop in a timer. Rather I would make a 'while' loop that processes every frame and then use some sort of timekeeping functionality (it sounds like in Java that would be System.nanoTime) to calculate how much time has passed since the last frame/last iteration of the loop.

Certain languages are exceptions here (eg. JavaScript, ActionScript) because those languages operate within an environment that has an implicit main loop to hook into (eg. the browser, the Flash Player) but that exception doesn't apply to Java.

---
Tags: 2d, java, game-design, game-loop, timer
---


# Question
Title: Low FPS on Java drawing in BufferStrategy
I ran into a very strange problem while using **BufferStrategy**, I've tried searching for an answer but all I have found are non-relevant threads and discussions. So here is my query.

```
for (int i = 0; i < 10; i++){
    for (int x = 0; x < 10; x++){
        g.drawImage(enlImg(getImg(terrain, x), 4), i*40, x*40, null);
    }
}

```

(The parameter 'terrain' is a BufferedImage pre-loaded, which will be used to get a sub image from it.)

I'm trying to draw images to a Canvas, where 'g' is the buffer strategies, 'getDrawGraphics()' because that's how I am drawing to the BufferStrategy. Anyway, straight to the point. I'm only getting ~3fps.

I know this is only drawing 100 images, but other games draw hundreds of thousands with no lag... Any ideas?

Is it maybe because of trying to enlarge, draw and get a sub image all at once, or is it because of my computer?

**Extra**

*enlImg() code*

```
public BufferedImage enlImg(BufferedImage image, int x){
    BufferedImage enlargedImage = new BufferedImage(image.getWidth() * x, image.getHeight() * x, image.getType());
    for (int a = 0; a < enlargedImage.getHeight(); a++) {
        for (int b = 0; b < enlargedImage.getWidth(); b++) {
            enlargedImage.setRGB(a, b, image.getRGB(a / x, b / x));
        }
    }
    return enlargedImage;
}

```

*getImg() code*

```
public BufferedImage getImg(BufferedImage img, int x){
    int y = 0;
    if (x >= 10){
        x=x-10;
        y++;
    }
    return img.getSubimage(x*10, y*10, 10, 10);
}

```

Computer Specifications (Windows):

*AMD Athlon II X2 250 - 3.00GHz
OS: 32bit
4GB RAM,
256GB HHD*

# Answer
> 4 votes
In enlImg, you're creating a new image every frame and copy 100\*(width\*x * height\*x) pixels. Instead, you should generate the scaled images only once and reuse them every frame.

Basically, you'd make a list or array (or whatever data structure fits your needs) of BufferedImages:

```
LinkedList<BufferedImage> enlargedImages;

```

This should be a member function of the class you're using for drawing.

Then, you generate the enlarged images once in a function which is not the rendering function:

```
for (int i = 0; i < 10; i++){
    for (int x = 0; x < 10; x++){
        enlargedImages.add(enlImg(getImg(terrain, x), 4));
    }
}

```

Then, terrain can be rendered in your paint function without regenerating the images:

```
for (int i = 0; i < 10; i++){
    for (int x = 0; x < 10; x++){
        g.drawImage(enlargedImages.get(x), i*40, x*40, null);
    }
}

```

---
Tags: java, graphics, html-canvas
---


# Question
Title: How can i use A star pathfinding algorithm
How would i implement an A star algorithm for a game that i'm making on the android in java? i'm looking for a pre-made A star API in java with classes and methods to call. i don't want to have to code from scratch.

# Answer
> 2 votes
Like others have commented, it might be easier (not to mention fun) to write your own implementation of A\* (use the link jhocking provided, I learned it from there, and highly recommend it - Link).

However if you definitely want a pre-existing library, here are some alternatives:

But the one I like best is Critter AI, which is a port of Recast for .NET and Java. The one for Java is more intended for study, but is still awesome. http://www.critterai.org/

Good luck! :)

# Answer
> 0 votes
*Ignore, if you are done.*

I have implemented "8-puzzle" using pure **A\* implementation**. You can follow the same **searching pattern** for your game.

---
Tags: java, android, algorithm, path-finding
---


# Question
Title: variable number of lights in a glsl shader?
I want to render an arbitrary number of lights in my fragment shader. I do not understand how you can properly pass them into the shader though. For example, I want something like this:

```
uniform int numberOfLights;

struct PerLight
{
    vec4 position;
    vec4 intensity;
}

uniform Lights
{
    vec4 ambientIntensity;
    float lightAttenuation;
    PerLight lights[numberOfLights];
} Lgt;

```

I've only seen documentation and examples use 'numberOfLights' as a constant and I cant get above to work so I am guessing you cant have a dynamicly sized struct in glsl.

So, how are you supposed to pass any given number of lights to the shader?

# Answer
You're not supposed to pass an arbitrary number of lights to a shader because it won't work, as you've discovered. This isn't just a software or API limitation; this is a hardware limitation - each light must fit in GPU register space, of which there is a limited amount (increasing all the time, but still a hard limit). Adding together the contributation for each light would also cause you to hit limits on GPU instruction counts (not so relevant any more, but it used to be a big deal in the earlier days of shaders).

So, the main limit is register space, this limit will vary across different hardware generations, and therefore you can't just specify an arbitrary number of lights. You need to find an alternative solution.

One method may be to sum individual light contributions across multiple passes - Doom 3 did this, with one pass per light, and it worked well enough there. On more modern hardware you could sum lights in groups of 2, 4, 8 or whatever, which would get the number of passes down.

Another method might be to use a deferred renderer instead (Google for info).

Finally, and if you know that you're never going to exceed a certain number of lights, you can just specify your own hard limit.
> 6 votes

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


# Question
Title: How to determine what hexes are in an area bounded by 3 hexes
I've been searching for hex grid algorithms for a while now, but I'm not having much luck.

I'm working on a game that will be using hex grids for the board. There seems to be sufficient resources to manage the A\* path finding routines, but trying to find something as simple as determining a set of hexes within a triangle seems to be a real challenge.

An example of what I'm looking for is that I want to have a starting coordinate. I want to get a hex that is 3 hexes to the north/east away from the source hex. I want to get a hex that is 3 hexes to the south/east away from the source hex. I then want to produce a list of all hexes bounded by these 3 hexes.

It should be simple enough, but the fact that rows are staggered is completely confounding me.

Thanks

# Answer
Use a Canonical (Or oblique) coordinate system (with axes at 120 degrees) to identify the hexes that are in the triangle. Then convert the coordinates of those hexes (with a homogenous transformation) to Rectangular coordinates for display. The utility toolkit I linked to above could be of help in writing this code.
> 9 votes

---
Tags: algorithm, hexagonal-grid
---


# Question
Title: GameLoop architecture for local multiplayer
I'm writing a game for Android to which I want to add a mulitplayer mode (local multiplayer via WiFi/Bluetooth, not online multiplayer via server). I stored the exchange-code between the client devices and the host device in th methods getInput() and pushInput(). I'm currently using a single-threaded gameLoop like this in my singleplayer mode:

```
public void mainLoopIteration(Canvas c, float deltaTime){
    compute(deltaTime);
    render(c);
    ...
}

```

My question is which of the following ways is the better implementation of the multiplayer "add-ons":

1. Adding exchange-calls to mainLoopIteration():

```
public void mainLoopIteration(Canvas c, float deltaTime){
    pushInput();
    getInput();
    compute(deltaTime);
    render(c);
    ...
}

```
2. creating a second thread that handles all the exchange stuff:

```
public void run(){
    while(mainLoopIsRunning){
        pushInput();
        getInput();
        //???Thread.sleep(...);
    }

```

}

Which solution you'd suggest or maybe do you suggest a completely other way?

Thx and regards Lisa

# Answer
It depends on your architecture, but I think you're thinking about this too hard.

In general, if you're going to thread something it should be worthwhile to spawn that thread and keep it running (the operations on it should probably be at least somewhat expensive and timely to make.) In my experience, networking does not necessarily need to run on its own thread like this. Polling in the gameplay loop is simple, reduces locking and will probably simplify your architecture. It's unlikely your game will bottleneck from pushing a few states and receiving them - so I reccomend just pushing them out on the main loop.

**Implement it and then profile it. If it really is a resource hog, then deal with the threading headache. If you don't need it though, why make yourself into more of a mess?**
> 1 votes

---
Tags: android, multiplayer
---


title: animation runs only onces

text:
# Question
Title: animation runs only onces
I found this tutorial on sprite sheets that works great. How can I make a sprite-sheet-based animation system?

I am not sure how I could modify it, so that it loops through just once. My thought was to add an if statement in the update method. This way I could stop the animation, but I am unable to figure out what to put in the if statement.

```
public void update() {
    if (!stopped) {
        frameCount++;

        if (frameCount > frameDelay) {
            frameCount = 0;
            currentFrame += animationDirection;

            if (currentFrame > totalFrames - 1) {
                currentFrame = 0;
               if(){
                   stopped = true;
                }
            }
            else if (currentFrame < 0) {
                currentFrame = totalFrames - 1;
            }
        }
    }

}

```

# Answer
> 1 votes
I answered that post you are referring to... You need to create a Boolean like so:

```
private boolean loop;

```

And replace

```
If (currentFrame > totalFrames - 1)

```

With

```
   If (currentFrame > totalFrames - 1 && loop)

```

I'm on my phone at the moment. However I don't see why it wouldn't work.

You will need to set the Boolean to either true or false... You can easily do this in the constructor.

Basically it is saying if the current frame number is greater than total frames - 1 (total frame count) and loop = true, then make current frame = to 0 so the animation will restart...

Understand?

Good luck

# Answer
> 0 votes
Add a boolean `loop` somewhere in the Animation class, then check if it's `false`.

---
Tags: java, spritesheet
---


title: Storing data for a pokemon like game

text:
# Question
Title: Storing data for a pokemon like game
The game I'm developing is close to Pokemon. How should I store the data? I am currently thinking of text files where I save the map and have a corresponding textfile for the trainers and their teams on the "current" screen. However this leaves me with a **LOT** of textfiles.

At the moment I'm thinking of something like this, however I haven't coded this yet so I can still easily change this.

```
@Trainer;5;
@Pokemon;12;1;3;4;6;
@Pokemon;13;1;2;5;
@Pokemon;13;1;4;5;
@Pokemon;11;1;3;5;
@Pokemon;16;1;2;7;
@Trainer;3
@Pokemon;13;1;4;5;
@Pokemon;11;1;3;5;
@Pokemon;16;1;2;7;

```

Where the first column is the "type" of the entry. If the first is Trainer the second is his number of Pokemon. If the first is Pokemon the second is the level, the third the type, the fourth/fifth/sixth the IDs of his attacks. (How should I store the attacks? A seperate textfile where I just store the attacks?)

I am currently finding myself with having such a huge amount of data that I'm starting to wonder wether I should be using a Database instead?

**Edit:** Using Java(LWJGL).

# Answer
> 3 votes
I'd just use some simple binary Format, especially if you don't want users to easily edit the file (and also to remove some redundancy).

For example, for a new Trainer you just add the number of Creatures he got.

Then, for every creature, you just add the creature data/stats (assuming they're fixed length or you can determine their length).

From your example above, the first trainer's dataset would just be something like this:

```
5,              12, 1, 3, 4, 6, 13, 1, 2, 5, 13, 1, 4, 5,  11, 1, 3, 5,  16, 1, 2, 7
↑Number of sets ↑ Start of #1    ↑Start of #2 ↑ Start of #3 ↑ Start of #4 ↑ Start of #5

```

Note that these would be bytes rather than actual textual numbers written to the file (might depend on the min/max values as well).

# Answer
> 1 votes
It depends on how you're storing things internally.

Here's an example, though it's not terribly efficient, that uses your format:

```
public Vector<Trainer> loadData(BufferedReader in) throws IOException {
  Vector<Trainer> trainers = new Vector<Trainer>();

  String line = in.readLine();
  String[] split;
  while (line != null) {
    split = line.split(";");
    if (split[0].equals("@Trainer")) {
      int count = Integer.parseInt(split[1]);
      Trainer t = new Trainer();
      for (int i=0; i < count; i++) {
        t.add(Pokemon.createMonster(in.readLine().split(";")));
      }
      trainers.add(t);
    }
    line = in.readLine();
  }
  return trainers;
} // end loadData()

```

I'm also sidestepping the issue of the varying parameter counts for each type of pokemon by passing the split array on to the creation method.

Strictly speaking, you don't *really* need the "@Trainer" and "@Pokemon" bits, because the system will automatically differentiate between trainers and monsters. That's how helpful the monster-count information is.

If you'd rather, you could also store things in a database, like SQLite, and pack things into tables instead.

Here are some example tables:

```
CREATE TABLE Trainers (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE Monsters (
  id INTEGER PRIMARY KEY,
  type INTEGER NOT NULL,
  owner INTEGER FOREIGN KEY (Trainers.id),
  parameters TEXT NOT NULL
);

```

By using a `parameters` column, you're avoiding the need for individual columns for each parameter for each monster type. Formatting would be whatever you want, including the semicolon-separated method you mention.

# Answer
> 0 votes
I'll offer an alternative strategy here which might be effective and lets you tack on data fairly easily.

Consider the following object:

```
public class SaveGame
{

   private ArrayList<EventFlags> _eventFlags;
   private TrainerInfo _trainerInfo;
   private SomeBlob _someBlob;
}

```

You'll have to forgive me for it not being explicit Java; but this is a basic "SaveGame" class that just contains a bunch of pointers to various game data. You store things like your story flags, variables and other persistent world information things here.

Then, just use Java serialization to save this file to the disk when you need to save. You'll be modifying these things in-game as you play anyway, so in a game like Pokemon it makes sense to just flush the state to the disk when you're done.

Nice and simple.

# Answer
> 0 votes
If you want a format that's easy to edit, read and write, XML or JSON are great choices.

**They are not very efficient** \- they use a LOT more space than the format you suggested - but they are supported by many tools, and having labels on the fields makes it easy to change the format later without any confusion about what each value means.

example file:

```
{
trainers: [
    { "level":5
      pokemons: [
        {"level":12,"attack1":1,"attack2":3,"attack3":4},
        {"level":13,"attack1":1,"attack2":2}
         ]
    }
    { "level":2
      pokemons: [
        {"level":2,"attack1":1,"attack2":2,"attack3":3},
        {"level":2,"attack1":1,"attack2":2,"attack3":3}
         ]
    }
    ]
}

```

Java

```
import java.util.List;

import com.google.gson.Gson;

public class JsonTest {

    public static void main(String[] args) {
        new JsonTest().start();
    }

    private void start() {
        Gson gson = new Gson();

        // Pretend this was read from a file
        String examplePokemonsString = "{ trainers: [{ level:3, pokemons: [{level:3,attack1:1,attack2:2,attack3:3},{level:3,attack1:1,attack2:2,attack3:3}]}]}";

        DataFile data = gson.fromJson(examplePokemonsString, DataFile.class);

        List<Trainer> trainers = data.trainers;
        Trainer firstTrainer = trainers.get(0);
        Pokemon firstPokemon = firstTrainer.pokemons.get(0);
        System.out.println(firstTrainer.pokemons.size()); //This trainer has 2 pokemon
        System.out.println(firstPokemon.level); // First pokemon is at level 3
    }

    class DataFile {

        List<Trainer> trainers;
    }

    class Pokemon {
        int level;
        int attack1;
        int attack2;
        int attack3;
    }

    class Trainer {
        int level;
        List<Pokemon> pokemons;
    }
}

```

---
Tags: java, game-design, lwjgl, data-structure
---


# Question
Title: Tutorials for shadow mapping with multiple point lights in XNA
I've been trying to crack this problem for a while now and I'd like to know if there's a tutorial or two out there that can help me with this. I know how to do shadow mapping with a single light, and I know how to implement multiple lights. What I can't seem to do is put them together, despite my many attempts.

So yeah, does anyone know of any XNA tutorials that can baby-step me through this?

EDIT: This is for a 3D environment

# Answer
> 1 votes
I don't think there is, but here is one for DirectX.

But since your problem is that yours is not working, I would suggest writing as much information as you can to console, and building some tools to show what is going on, like a draw line function. Personally, I like to copy my entire project folder every couple hours when doing this sort of thing. Best of luck.

edit: I've added some links in the comments. Hopefully there is something you can use there.

# Answer
> 0 votes
This tutorial should explain to you how to accomplish this:

http://www.catalinzima.com/2010/07/my-technique-for-the-shader-based-dynamic-2d-shadows/

I've used this technique and it works quite well.

---
Tags: c#, xna, lighting, shadow-mapping
---


title: 'perfect' platformer base Xna

text:
# Question
Title: 'perfect' platformer base Xna
When a player touches a ground peice in a game, he seems to sink through the ground then slowly rise back up, and when he has risen back up, he is very jittery.

```
 if (touchingTheGround())
 {
     player.velocity.Y -= 2;
     touchground = false;
 }

```

the collision method sets the variable touchground to true if the player touches a ground peice, and if i dont set it to false, the collision detection wont work at all. i set the players velocity to move 2 up because when he's not touching a platform, his velocity.Y += 1. How do i achieve a way so that the player

1. Does not sink in the ground before moving up
2. Stops jittering when its position is higher than the ground its touching

# Answer
Think about these cases:

1. The player is in the air
    * we want them to fall (increase velocity.Y)
2. The player is "inside" the ground
    * we want them to instantly stop falling (set velocity.Y to zero)
    * we want them to instantly move up onto the surface of the ground (set position.Y to the correct value)

Here is one idea for fixing the code you showed to make it work for case 2

```
if (touchingTheGround())
 {
     player.velocity.Y = 0; //stop falling
     while (isPlayerStillTouchingTheGround()) { //Need to re-do the collision check
        player.position.Y -= 1; //move until they are no longer inside the ground
     }
     touchground = false;
 }

```

First we stop the player from falling. Second, we move the player up until they are not in the ground any more. This all happens in the single frame, so from the player's point of view, it is instant.

Note that you have to be able to repeat the collision check over and over in one frame, so we can tell when we have moved the player far enough to be back above the ground.

Repeating the collision check is inefficient - it would be better if you could get the position of the top of the ground, and move the player there in one step.
> 1 votes

---
Tags: xna, xna-4.0, platformer
---


# Question
Title: Show view over existing view in same activity
I am newbie Android developer, and I am starting out with a simple Sudoku game. The problem I am facing right now is that I have my game showing on a dedicated Activity, which is displaying a custom View class. I have the code within the onDraw function. Now I want to show a custom keypad view, which is a separate class extending View, whenever a user clicks on a block in the Sudoku grid.

I am extremely confused as to how I should go about doing this. I am reluctant to create a dedicated activity for just this keypad, and want to show this keypad over the Sudoku grid view that the activity is currently displaying.

The activity is using setContentView(myCustomGridViewClass) to show the grid. Now I want something to the equivalent of

onTouch -\> setContentView(myCustomKeypadView), though this should appear over the previous view.

I have tried reading about the LayoutInflater, but did not understand how to use it to show the keypad within this same activity. This is probably a very noob question, but any help, including any other questions, or sources I could refer to for an answer would be highly appreciated.

Regards,

# Answer
You could place both views in a `FrameLayout` or a `RelativeLayout` and control the keypad's visibility (http://developer.android.com/reference/android/view/View.html#setVisibility(int)) when needed.

Change setContentView(myCustomGridViewClass) to setContentView(R.layout.id\_of\_my\_layout), then write id\_of\_my\_layout.xml that contains the layout (more help here http://developer.android.com/guide/topics/ui/declaring-layout.html).

Make sure to add your keypad view *after* the game view in your layout xml, otherwise the game view will be placed on top of it and you'll never see the keypad :)
> 3 votes

---
Tags: android, view
---


# Question
Title: Should my assets match my reference resolution?
I'm confused over supporting multiple resolutions in my 2D game.

I'm currently working with a reference resolution of 1280x720. That means that all elements are positioned in a 1280x720 coordinate system which I scale up/down to the actual resolution using `glScale`. My graphic assets are all pixel graphics, so it also means I need to save them relative to this reference resolution.

Now the artist sent me some files in a pretty high resolution and I scaled them all down to match the reference resolution, but I noticed that the positions of the graphics relative to each other are slightly off. Probably because there was some rounding involved in the down scaling.

Should I increase my reference resolution to match the artwork? Or should I ask the artist to scale everything down and make sure the positions aren't off as a result? Should my reference resolution be larger anyway? (2880x2304 is what I came up with to support all modern screen resolutions and aspect ratios down to 5:4, but that seems awfully large.)

How is this commonly being tackled?

**Edit:** Sorry, forgot to provide some relevant background: My game is a simulation game, that is essentially a UI. So there is no such thing as a world space, I'm just positioning widgets on the screen.

# Answer
Since you have the choice, I'd recommend you do the proper thing: make it resolution independent.

There are two factors to consider here, not just one. There's both the physical size and resolution (often conflated when calling a screen size in pixels a "resolution"). For high or low resolution screens, the same number of pixels can vary wildly in actual physical size (compare an ancient monitor running at 800x600 and Apple's "Retina"-branded displays).

In order to accomodate these, you should really be thinking in terms of physical size, and use a device independent coordinate space based on millimeters or inches instead. Make your UI flexible enough to accomodate all screen sizes and aspect ratios.

Use your source artwork at the resolution provided by your artists to get the most out of the detail, and make it gorgeous on high resolution displays now and in the future. As a performance improvement, you could rescale it to the target resolution at load time.

The main problem with having a very flexible device independent coordinate space is snapping graphics on a tile to make them seamlessly line up. Depending on the artwork I'd suggest either to (a) use floating point everywhere and have ultra-smooth motion, or (b) snap image sizes and positions to be pixel aligned to line up without seams but possibly suffer from jitter in motion.
> 2 votes

---
Tags: 2d, graphics, assets, screen, resolution
---


title: Pong horizontal movement algorithm

text:
# Question
Title: Pong horizontal movement algorithm
I was just wondering about the horizontal movement of a pong ball? What is the general algorithm used with this? The ball in my pong game just moves vertically and I don't know about the algorithms used for horizontal movement.

# Answer
> 3 votes
You have two speeds here: \- ball speed (x,y) \- paddle speed (x)

Ball speed is constant (positive or negative) by Y axis while speed on X axis is set depending how fast is the paddle while you hit the ball.

Simple calculation could be:

```
// this is called when ball hits the paddle
function OnCollision()
{
    BallSpeed.x = PaddleSpeed.x * 0.5f; // 0.5f = custom factor
}

// you calculate new ball position here every frame
function OnUpdate(float dt)
{
    BallPosition.x += BallSpeed.x * dt;
    BallPosition.y += BallSpeed.y * dt;
}

```

Of course, you could also calculate X speed depending which part of the paddle it hit (if it was far edge, X speed is bigger). Usually both parameters are applied in pong games. Let me know how it went.

---
Tags: 2d, algorithm, game-mechanics, movement
---


# Question
Title: Child Object Placement based on Parent Object Angle
I want to perform object placement based on parent object position.

For example, I have chest and head object. I want when I rotate chest object then as per chest rotation head object also rotate and transform.

For this thing to achieve I did following stuff but I don't achieve desire effect and can't able to understand what was I doing?

```
private void addRectangle(float angle) {

    Rectangle baseRectangle = new Rectangle(300f, 300f, 100f, 200f);
    baseRectangle.setRotationCenter(0f, 0f);
    baseRectangle.setRotation(angle);
    // red base rectangle
    baseRectangle.setColor(1f, 0f, 0f);
    mMainScene.attachChild(baseRectangle);

    float tAngle = MathUtils.atan2(-200, 100f);
    float dist = FloatMath.sqrt(50 * 50 + 50 * 50);

    float pX = baseRectangle.getX()
            + FloatMath.cos(MathUtils.degToRad(baseRectangle.getRotation())
                    + tAngle) * dist;
    float pY = baseRectangle.getY()
            + FloatMath.sin(MathUtils.degToRad(baseRectangle.getRotation())
                    + tAngle) * dist;

    Rectangle childRectangle = new Rectangle(pX, pY, 50f, 50f);
    childRectangle.setRotationCenter(0f, 0f);
    childRectangle.setRotation(angle);
    // green child rectangle
    childRectangle.setColor(0f, 1f, 0f);
    mMainScene.attachChild(childRectangle);

}

```

As function argument I provide desire angle on which both the object needs to be rotated. Someone please help me to get out from this problem.

# Answer
> 0 votes
your angle and distance formula wrong. in your child position you get angle and dist that i define below code.

```
private void addRectangle(float angle) {
    float centerX, centerY;
    Rectangle baseRectangle = new Rectangle(300f, 300f, 200, 100f);
    centerX = baseRectangle.getX() + baseRectangle.getWidth() / 2;
    centerY = baseRectangle.getY() + baseRectangle.getHeight() / 2;
    baseRectangle.setRotation(angle);
    baseRectangle.setColor(1f, 0f, 0f);
    mScene.attachChild(baseRectangle);
    float tAngle = -0.2f;
    float dist = 128f;
    float pX = centerX + FloatMath.cos(MathUtils.degToRad(angle) + tAngle)
            * dist;
    float pY = centerY + FloatMath.sin(MathUtils.degToRad(angle) + tAngle)
            * dist;
    Rectangle childRectangle = new Rectangle(pX, pY, 50f, 50f);
    childRectangle.setRotationCenter(0, 0);
    childRectangle.setRotation(angle);
    childRectangle.setColor(0f, 1f, 0f);
    mScene.attachChild(childRectangle);
}

```

---
Tags: andengine
---


# Question
Title: Why is XNA not considered a game engine?
I'm just wondering what XNA is missing, to be considered as a game engine. It does all the things a game engine should do (except the physics part); it also has support for every aspect defined in the Wikipedia article on game engines.

Why is XNA not considered a game engine?

# Answer
> Microsoft XNA is **a set of tools** with a managed runtime environment provided by Microsoft that facilitates computer game development and management. **XNA attempts to free game developers from writing "repetitive boilerplate code"** and to bring different aspects of game production into a single system.

It is designed as a framework - in fact, XNA is the Microsoft XNA Framework - so technically it's not an engine by name.

There is no 'engine' - if you notice, you derive your main class from XNA.Framework.Game and have to override the draw and update functions yourself. There is no central rendering system, or input system, or audio system ready out of the box. There is SpriteBatch and the vertex classes, there is KeyboardState, and there are some audio classes..but they are only abstractions over the low level drawing code.

EDIT: For the sake of usefulness, why does something matter if it's labelled as an engine, framework, library, or toolset?

To clear things up somewhat: I am developing an engine in XNA. Obviously I can't do that in something like Unreal, like Jonathan has mentioned. However, there are a few things I feel are important that XNA just doesn't have:

Plug-n-play: I want to be able to make some kind of template - have this HP, this mesh, this animation and BOOM! I have an NPC in my game.

Hidden low level - XNA does this already, but I don't want to fiddle around with GameServiceProviders. I just want to shove stuff together.

Game separated from engine - There may be a 'game' class, but I want to separate my logic and my code from the base system. I don't want `if(player.hasitem(Item.SECRET_SWORD_OF_SECRETNESS)` mixed with updating the buffers on my graphics renderer.
> 28 votes

# Answer
A framework provides a minimal architecture built for a specific type of application. It minimises assumptions about implementation details beyond the stated goals of the architecture. While a cross-platform game development framework might have the goal of providing "what is common to (nearly) all computer games, irrespective of platform", and might implement only such abstract factors as timing and entity management, the XNA Framework (implicitly) has a goal of providing "what is common to (nearly) all computer games written for execution on the XNA CLR". Given that this focus is so narrow, they have been able to included engine features with impunity. They bundle it all under the heading of "Framework", since this indicates a certain freedom of implementation which you as the game developer will enjoy.

Roughly speaking, a framework should be as unrestrictive as possible while still providing useful foundations. An engine, on the other hand, is typically more focused toward specific features, and in using it, you accept that there are certain limitations which you will be tied to.
> 5 votes

# Answer
I’ve never used a ‘game engine’ but my understanding of this is more as a pre-defined set of tools bundled with a pre-defined skeletal game-structure for the development of a specific type of game. And surely that structure for the development of a specific type of game is the main defining factor in a games engine, it certainly seem to be what the aforementioned Wikipedia article is alluring to. To me the XNA framework is more akin to a third-party library set, like AJAX, in that it adds pre-built routines to the existing bare-boned programing language. It does not put any restrictions or guidelines on what you, as the programmer, can and cannot do with these library routines. In my mind that is not akin to an engine in any way. Then I come from a business software/web centric background, so maybe the view if this is slightly askew for a dyed-in-the-wool games dev.

I’ve built the framework for a game idea using XNA and it definitely feels like I’m using just another library over C#. I’m going to use the processes I’ve hacked out in the test program to produce two or three games for windows and possibly Xbox.

So, as I said, In my mind this is far away from what I understood to be a ‘Games Engine’ so when I came across this post I had no idea why someone would make that comparison. Am I wrong?
> 2 votes

---
Tags: xna
---


# Question
Title: Entity moving Up and Down but not Left and Right
I am trying to create an entity class for my game but I'm having difficulty with the movement, I can get the sprite moving along the Y-Axis but not along the X-Axis.

Here's my code:-

```
package Game;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.geom.Vector2f;

public class Entity {

    protected Vector2f pos; // Vector contains a value with components x & y
    protected Rectangle box;
    protected Image sprite;

    public Entity(float x, float y, int width, int height, Image sprite) {
        pos = new Vector2f(x,y);
        box = new Rectangle(x, y, width, height);
        this.sprite = sprite;
    }

    public void update(GameContainer gc, int mapWidth, int mapHeight, int delta) {

    Vector2f trans = new Vector2f(0, 0);

    Input input = gc.getInput();

    if (input.isKeyDown(Input.KEY_W)) // Delta is used to move things on a frame rate independent way
        trans.y = -0.5f * delta;

    if (input.isKeyDown(Input.KEY_S))
        trans.y = 0.5f * delta;

    if (input.isKeyDown(Input.KEY_D))
        trans.x = 0.5f * delta;

    if (input.isKeyDown(Input.KEY_A))
        trans.x = -0.5f * delta;

    if (trans.x != 0 && trans.y != 0) { // If both components aren't null, we reduce them to have constant speed on all directions
        trans.set(trans.x / 1.5f, trans.y / 1.5f);
    }

    if(pos.x+trans.x > 32 && pos.x+trans.x < (mapWidth-64)) // Is the player inside the map? (We add (subtract) because of the stone wall)          pos.x += trans.x;               if(pos.y+trans.y > 32 && pos.y+trans.y < (mapHeight-64))
        pos.y += trans.y;

}

public void render() {
    sprite.draw(pos.x, pos.y);
}

// Getters and Setters
public Vector2f getPos() {
    return pos;
}

public float getX() {
    return pos.x;
}

public float getY() {
    return pos.y;
}

public void setPos(Vector2f pos) {
    this.pos = pos;
}

public Rectangle getBox() {
    return box;
}

public void setBox(Rectangle box) {
    this.box = box;
}

public Image getSprite() {
    return sprite;
}

public void setSprite(Image sprite) {
    this.sprite = sprite;
}
}

```

I was just wondering if there's anything glaringly obvious as to why the sprite won't move left and right when the A & D keys are pressed.

Thanks in advance.

# Answer
```
if(pos.x+trans.x > 32 && pos.x+trans.x < (mapWidth-64)) // Is the player inside the map? (We add (subtract) because of the stone wall)          pos.x += trans.x;               if(pos.y+trans.y > 32 && pos.y+trans.y < (mapHeight-64))
        pos.y += trans.y;

```

That code will move the y component, but you seem to be missing moving x component

you have the correct code commented out right next to it. user error??
> 3 votes

---
Tags: java, lwjgl, slick
---


# Question
Title: How to flip coordinate system in Pyglet?
Is there any way I can flip the coordinate system in Pyglet vertically so that y = 0 is at the top of the screen and a higher y value is closer to the bottom? It is really confusing trying to use Pyglet's flipped coordinate system with Ogmo Editor.

# Answer
> 4 votes
Just use the maximum height of the window for your calculations:

When setting:

```
py_Y_Value = max_Screen_Height - my_Y_Value

```

or when getting:

```
my_Y_Value = max_Screen_Height - py_Y_Value

```

The best way to utilize these would be to abstract away their use in wrapper functions.

---
Tags: coordinates, pyglet
---


# Question
Title: Automatically generate low detail collision meshes
I lately integrated Bullet Physics into my little game engine, but for now I only use basic shapes as spheres or boxes for collision checks. For more realistic physics I need collision meshes for all models in the scene. They should be much simpler and in lower detail than the actual model for drawing to speed up computations.

Since I want adding new asserts to the engine as easy as possible, I am looking for a way to automatically generate collision meshes. I could just use the actual mesh loaded from file and that would result in very realistic physics calculations but that won't be fast enough. Therefore, how can I generate low detail collision meshes from a given set of vertices?

This task doesn't seem trivial since there many different cases to handle. For example a model of a house with furniture must retain details of floor and door frames while ornaments should be removed. I believe there already was research on this topic, but I couldn't find anything useful yet.

# Answer
> 7 votes
You can first decimate the mesh. Then use the decimated mesh to create a triangle mesh shape to create a collision mesh for that model.

You will probably run into issues with automatically generating meshes in this way. Since your physics object will not exactly match your world object. The decimating can have unexpected results for changing the shapes of meshes, particularly cutting off corners.

In my game, I define simple shapes in my modeling software (Blender), I name them something special like "PHYSICS\_SHAPE\_1", then my model importer looks for meshes with the name "PHYSICS\_SHAPE\*" and reads those to create physics objects. This is a little more work, but it ensures that my collision meshes are accurate and fits well with a data driven approach.

---
Tags: collision-detection, physics, models, performance
---


# Question
Title: Pathfinding on a uneven planetary surface
My question is what would be the best approach to pathfinding on an uneven planetary surface?

---

***Background Information***

*I have created a planet from displacement mapping 6 sphere projected planes. The planes initially formed a cube before being projected into a sphere shape.*

I'm wondering if it is possible to use each "sphere projected cube face" as grids and use a simple A\* algorithm to find the best possible route, I would also like the displacement height to be taken into account so the path avoids climbing mountains etc (I guess this would just be a heuristic within the A\* algorithm) Another consideration is that I have achieved planetary movement by leveraging Unity3d's physics engine, apply gravity towards the centre of the planet. Would my proposed solution require the agents movement to be controlled independently to gravitational physics.

*To help better articulate my question this is my current planetary body:*

# Answer
> 12 votes
It seems you've already answered your own question. A\* is likely the best approach. Yes of course it can be used in the way you describe, including using the height information to avoid mountains. As long as you're able to access information about any grid on the surface of your world, there's no reason you can't use it in the A\* heuristic.

Finally, you're confusing path finding with path following at the end of your question. Path finding doesn't care about gravity, unless you add it as a heuristic and since you're on the surface of a planet, gravity will be essentially the same over the entire surface. Many games have gravity together with movement, I see no reason you can't.

Basically we want to map going from red to blue, to be the same on a sphere as it is on a cube.

Since A\* is frequently getting neighbors to its current node, you can easily create a set of functions for getting adjacent nodes. For example, `getXPlus()`, `getXMinus()`, `getZPlus()` and so on. These functions will take the current node and return the node in the direction specified by the function name.

Most of the time these functions can just increment a value and be done, however, on the edges, that will change.

You'll want to map the surface of your cube to a 2D coordinate system. However you do this is up to you, they don't have to line up, just give each grid space a unique X, Y coordinate.

Now when on an edge, and getting the adjacent grid space it's not necessarily going to be just incrementing the coordinates. We have to find out which face we're moving to and switch to the coordinates of that face.

For example, getting the XPlus coordinate here will change both the X and the Y coordinates because we're moving to a new grid space on a new face. The green line represents an edge between two faces.

Now these are just global coordinates, it may be easier to use an internal local coordinate system, with a 3rd dimension that represents the cube face you're currently on.

Either way, you need to have a unique coordinate for each grid space on the face of the cube. Traversing between them will depend on how you implement the coordinate system. You need to know where that coordinate maps to the surface of the sphere too.

All this should eventually be abstracted away so that you don't even know about it.

---
Tags: unity, physics, movement, path-finding, planet
---


# Question
Title: Developing a 2D Android game on Unity - Pros and Cons
Depending on your experiences, if you have created a 2D game on Android using Unity, was it painful? Have you ever said "I wish I have used X instead of Unity!"?

Tell me the Pros, Cons and the name of "X" please.

Edit: Consider it for a commercial shoot em up game. The programming language can be anything.

# Answer
I have developed games using both the android sdk/andengine , as well as unity, and my personal preference is to go with the android sdk route. Unity is great, but seeing as this was my first trip into the mobile development world, I took this as a good excuse to learn the environment, and understand the constraints and pitfalls associated with it. Unity simplifies everything so much, making everything from debugging to deployment ten times easier, but I must say that from a personal perspective I don't feel like I got a darn thing out of it.

If your goal is rapid prototyping, or you simply aren't interested in the challenges or opportunities to learn associated with the android platform, then you should go with unity hands down. Otherwise, I would recommend the SDK.
> 4 votes

# Answer
I have built 3D games that are played in two dimensions just fine in Unity3D. If you seek a true two dimensional game, I can tell you there are more suitable engines, Unity3D really focuses on the 3D realm.

The best answer I can give you based on the information you have provided. Hope it helps.
> 3 votes

---
Tags: 2d, android, unity
---


# Question
Title: JavaScript - 2D Top-down Tile Collision Detection
I am developing a small Top-down Game (Much like the old Zelda Games) and I'm having an issue in terms of Collision detection (The actual theory itself rather than assigning Tiles as solid, etc.)

I have a function called "checkTileCollision" which takes two parameters, X and Y, and is called through the Player's Move function. X and Y are the location of the player AFTER they have moved, as it's suppose to check the position the player is moving to for a solid Tile(s), and if it finds any, returns true to stop movement.

My Player is larger than a Tile (For examples sake, let's say each Tile is 32x32 and the Player is 26x60) and I need to know an efficient way to detect whether or not the player is attempting to step on to a Solid tile. The Player doesn't move on the Grid and is free-moving, so X and Y are true positions and not Tile co-ordinates.

Please note; I am aware of things such as Box2D but I'm wanting to do this without the use of third party libraries.

Any help is appreciated!

# Answer
> 2 votes
You need to check each corner of the character sprite to detect if any of them enter a solid tile. Also since your character is larger than your tiles, you'll need to check midpoints as well to prevent the player from straddling a single block.

To turn your true positions into coordinates, divide the true position by the tile width (the ground not the player) and that will give you the tile coordinates.

Also I've found it much easier to check for collisions prior to moving than it is to check after moving. Just a thought. :)

---
Tags: javascript, html5, html-canvas
---


title: Reading text files XNA 4.0 on Xbox 360

text:
# Question
Title: Reading text files XNA 4.0 on Xbox 360
I'm working on porting a game from PC to Xbox 360.

When I want to create a level I read a .txt file that I store in my content I read the whole file as a string using this method

`File.ReadAllText(fi.FullName)`;

Where I'm passing in the full path to that file.

Later on in my code I parse that string to create whatever level I need.

When I try to deploy my game onto the Xbox I usually get an error stating

```
'System.IO.File' does not contain a definition for 'ReadAllText'

```

I was wondering if there was a simple way to read the text in a .txt file when I deploy onto the Xbox 360

# Answer
You can't access the file system on the Xbox 360 in the same you can on Windows; you need you use one of the storage APIs to access files.

There's an article here which outlines the different ways to handle IO in XNA 4.0 which will work on both the Xbox 360 and Windows. From a quick read it looks like you want to use Title Container, for which I've included some example code below (taken from the MSDN)

```
/// <summary>
/// This method opens a file using System.IO classes and the
/// TitleLocation property.  It presumes that a file named
/// ship.dds has been deployed alongside the game.
/// </summary>
private static void DoOpenFile()
{
    try
    {
        System.IO.Stream stream = TitleContainer.OpenStream("ship.dds");
        System.IO.StreamReader sreader = new System.IO.StreamReader(stream);
        // use StreamReader.ReadLine or other methods to read the file data

        Console.WriteLine("File Size: " + stream.Length);
        stream.Close();
    }
    catch (System.IO.FileNotFoundException)
    {
        // this will be thrown by OpenStream if gamedata.txt
        // doesn't exist in the title storage location
    }
}

```
> 3 votes

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


title: XNA moving towards 3D point, RTS style

text:
# Question
Title: XNA moving towards 3D point, RTS style
I looked around to see if this question had already been asked- maybe it has, maybe it hasn't, I don't know.

I'm trying to make a 3D RTS game. Right now we're trying to get the basics on the table. When you select a unit (I have that working) and right click on a point, the unit should move towards that point at a set speed. We can't figure out what's going wrong, but the unit never seems to move towards the clicked point, and sometimes, not at all. We used MSDN's
`-CSng(Math.Sin(unitRotation))`

but that didn't seem to work. (We converted to degrees) How do you get an appropriate, consistent velocity to set to the unit so that it moves towards the ordered position?

Thanks much.

EDIT: Clarification: If I can get it to move towards a point, I can take it from there. We've got a pathing system in the works. I just want it to go where you click right now.

# Answer
> 0 votes
Assuming you don't have any pathfinding constraints, what you need to do is calculate the offset from your unit's position (let's say `x`) to your target's position (let's say `y`). Then, the velocity of your unit will be `y-x`, normalized times the speed of your unit. You can then move your unit's position towards the target location. In pseudocode:

```
void update(Unit u, float dt) {

    Vector velocity = u.target - u.pos;
    float distance = velocity.magnitude();
    float dx = u.speed * dt;

    if(distance < dx) {
        u.pos = u.target;
    }
    else {
        velocity /= distance;
        u.pos += velocity * dx;
    }
}

```

# Answer
> 0 votes
If you are using vectors you can do something like that

```
Vector UnitPosition;   // position of your unit
Vector ClickPosition;  // position of your click

Vector Direction = ClickPosition - UnitPosition;
Direction.Normalize();

Vector UnitSpeed = Direction * speed; // speed is your unit's speed

// Now you update position
Unit.Position.x += UnitSpeed.x * dt;
Unit.Position.y += UnitSpeed.y * dt;

```

This should be it. Let me know if it works / if you don't understand anything.

---
Tags: xna, 3d, rts
---


title: Lockstep Game Loop

text:
# Question
Title: Lockstep Game Loop
I have an XNA game using a basic lockstep update loop. The client sends all commands to the server, and updates only if it has received the next turn's commands from the server.

When does a turn end? When the Server says so (using the timer class, it sends out every 200ms a "Turn Done" to all clients. If a client hasn't received the turn done message from the Server then it does not update, it just waits until it gets that message from the Server.

So, this works fine, for about 20 seconds. After that, the game starts stuttering. I'm not hosting for other players, it's just my client and my server, all on the same machine.

The issue seems to be the XNA game loop itself. While the Server uses a System.Timers.Timer to keep track of... time, the game itself is using gameTime.ElapsedGameTime.TotalSeconds. And guess what, XNA.GameTime races ahead. The game reaches the end of the Turn before the Server does, so it ends up waiting for the Server to respond. And XNA.GameTime is consistently faster than the timer, so the delay just keeps getting bigger.

So, my question is: Which is the most accurate way to measure time and synchronize the game and Server in this context? Also, even if I do synchronize two processes on the same machine (seems feasible), Is it realistic to expect two different PCs to be synced? (And no, I don't mean that both have the same time at the very same instant, but that 200ms on one machine is exactly 200ms on another machine in real time, as otherwise one of them will sooner or later fall behind. If it.s the client that falls behind he will lag, and if it is the Server that falls behind then the Client will stutter while waiting for the Server to end the turn)

ps Thanks for any ideas/insight.

pps Thanks but I am well aware of the 1500 archers article. Either it doesn't contain info helpful to this question or I am too dim to see how it does, so some extra explanation is what I need.

# Answer
What I would do is re-synchronise the server with the client every turn. Given how 200ms is 1/100th of 20s, the stutter won't be noticeable after just one turn. Then, on the 'turn end' signal from the server, ***both*** reset their timers to 0. At this point, the stutter shouldn't ever be detected by a player - the time difference over 1 turn is minimal.
> 1 votes

# Answer
First of all for 2P lockstep using a server only introduces more delay. You should be using P2P for that.

Don't use *real time*. Use frames. It's much easier to track integral frame numbers than this XNA's concept of "gameTime". Forward-Mark each message with a certain number of frames (say 10) that represents the average latency + some buffer time that each command will be executed in the future

Say it is frame 80 and you want to move UP.

Send the command to the remote player and plan to execute yourself in 10 frames. If you don't get a response before 10 frames, **wait on frame 89** until the remote player responds with "Yes I will execute at frame 90". Then you can execute it the command too. OR he might respond with "I've already passed frame 90, no can do". You can discard the player input then.

When the game is running smoothly, all messages will be received and responded to early enough that the game won't stutter.
> 1 votes

---
Tags: game-loop, client-server, timer, synchronization
---


# Question
Title: AI system recommendations for a Hive mind system
Im currently starting to work on a game project where a player will be faced against an enemy which has a hive mind. I was wondering if anyone could recommend an A.I system which I could use as at the moment I am thinking about using Finite State Machines(FSM) and I think that if I use FSM's that it will get messy.

Just to clear up what will be part of the "Hive Mind" if anyone was wondering will be:

1. Hive Leader
2. Soldiers
3. Workers

Under each of these categories there will be roughly 2-3 different sub-categories which will have to have slightly modified FSM's dependent on their abilities.

Thanks for any response

# Answer
Nearly all AI systems out there are "hive mind" already. Consider, the AI knows where every unit is, what every unit can see, what each unit is doing and has control over their actions. Most any RTS AI is already functioning like a hive mind.

You may be over thinking your implementation, since it's already very common. Search around for AIs that are suitable for RTS games and you'll find your hive mind AI.
> 10 votes

# Answer
byte56 is right. Most games are like that anyway. It's too computationally expensive to use an AI that truly has limited information. Better to give it all information by default, then simulate one with limited information by selectively ignoring stuff or causing an occasional lapse in judgement. Regardless of the How, here's something that you might like for experiments.

Open RTS Engine for AI's https://skatgame.net/mburo/orts/#Overview
> 0 votes

---
Tags: ai, fsm
---


# Question
Title: Collision Detection - Slide Around Sprite
I'm creating an RPG using XNA/C# and am trying to add some complicated collision detection code. I have the playable character 'Wizard' and when it collides with something, a method gets called in his class with the sprite which he collided with as a parameter.

Now what I want the wizard to do is be able to 'slide' around the sprite when he collides with (In this case it's a tree), both sprites are 8px x 8px (they are scaled up by x 8 when drawn to the screen). So far what I've done is find the co ordinates of each corner of both sprites and the co ordinates of the mid points of each side of both sprites and storing them as Vector2's.

```
Vector2 spriteTopLeft = new Vector2(sprite.X, sprite.Y);
Vector2 spriteTopRight = new Vector2(sprite.X + sprite.Width, sprite.Y);
Vector2 spriteBottomLeft = new Vector2(sprite.X + sprite.Height, sprite.Y + sprite.Height);
Vector2 spriteBottomRight = new Vector2(sprite.X + sprite.Width, sprite.Y + sprite.Height);

Vector2 wizardTopLeft = new Vector2(X, Y);
Vector2 wizardTopRight = new Vector2(X + Width, Y);
Vector2 wizardBottomLeft = new Vector2(X, Y + Height);
Vector2 wizardBottomRight = new Vector2(X + Width, Y + Height);

Vector2 spriteTopMid = new Vector2(spriteTopLeft.X + (sprite.Width / 2), spriteTopLeft.Y);
Vector2 spriteRightMid = new Vector2(spriteTopRight.X, spriteTopRight.Y + (sprite.Height / 2));
Vector2 spriteBottomMid = new Vector2(spriteBottomLeft.X + (sprite.Width / 2), spriteBottomLeft.Y);
Vector2 spriteLeftMid = new Vector2(spriteTopLeft.X, spriteTopLeft.Y + (sprite.Height / 2));

Vector2 wizardTopMid = new Vector2(wizardTopLeft.X + (Width / 2), wizardTopLeft.Y);
Vector2 wizardRightMid = new Vector2(wizardTopRight.X, wizardTopRight.Y + (Height / 2));
Vector2 wizardBottomMid = new Vector2(wizardBottomLeft.X + (Width / 2), wizardBottomLeft.Y);
Vector2 wizardLeftMid = new Vector2(wizardTopLeft.X, wizardTopLeft.Y + (Height / 2));

```

Then I'm comparing different corners of both sprites to decide which sides are being collided together, so wherever the wizard is on the top of the tree, to the left, right or underneath it. Next by using the midpoints of the sides of the 2 sprites, I'm calculating which way the wizard should slide.

For example, if the wizard in on the top of the tree, but on the right hand side of the top half, then it should slide around the right side of the tree. I've tried to show what I mean with the following image:

To try to achieve this, I've implemented this code:

```
    float leverage = 1.5f;
Vector2 temp = new Vector2(0, 0);

if (wizardBottomRight.Y <= spriteTopRight.Y + leverage && wizardBottomLeft.Y <= spriteTopLeft.Y + leverage)
{
    //Top
    if (wizardBottomMid.X <= spriteTopMid.X)
    {
        //Left
        temp = new Vector2(-speed, 0);
    }
    else if (wizardBottomMid.X >= spriteTopMid.X)
    {
        //Top
        temp = new Vector2(speed, 0);
    }
}
else if (wizardTopRight.X <= spriteTopLeft.X + leverage && wizardBottomRight.X <= spriteTopLeft.X + leverage)
{
    //Left
    if (wizardRightMid.Y <= spriteLeftMid.Y)
    {
        //Top
        temp = new Vector2(0, -speed);
    }
    else if (wizardRightMid.Y >= spriteLeftMid.Y)
    {
        //Bottom
        temp = new Vector2(0, speed);
    }
}
else if (wizardTopRight.Y >= spriteBottomRight.Y - leverage && wizardTopLeft.Y >= spriteBottomLeft.Y - leverage)
{
    //Bottom
    if (wizardTopMid.X <= spriteBottomMid.X)
    {
        //Left
        temp = new Vector2(-speed, 0);
    }
    else if (wizardTopMid.X >= spriteBottomMid.X)
    {
        //Right
        temp = new Vector2(speed, 0);
    }
}
else if (wizardBottomRight.X >= spriteBottomLeft.X - leverage && wizardTopRight.X >= spriteTopLeft.X - leverage)
{
    //Right
    if (wizardLeftMid.Y <= spriteRightMid.Y)
    {
        //Top
        temp = new Vector2(0, -speed);
    }
    else if (wizardLeftMid.Y >= spriteRightMid.Y)
    {
        //Bottom
        temp = new Vector2(0, speed);
    }
}

position += temp;

```

(The variable 'speed' is a float with the value 0.6, 'sprite' is the tree that gets passed into the method which the Wizard collides with)

So far this detection works 75% of the time, need to work on tweaking the leverage amount. At the moment the wizard sort of moves to the right/left and kinda jumps almost around the tree when walking in from the top or bottom and doesn't work correctly at all when walking in from the left/right.

Is this a good way of doing this? Or is there a better method? Also how would I get this code working correctly so that the wizard smoothly walks around the tree?

Thanks in advance!

# Answer
Do your objects need to be represented by boxes in your collision system? If you used circles or spheres instead of a bounding box, you can quickly detect when objects are colliding and then apply your movement speed along the tangent vector at the intersection point of your colliding objects. Each tick, the wizard would collide, adjust, and slide along the new tangent until it's around the tree and able to continue in the original direction. This gives a very smooth effect like you'd see in your favorite JRPG and your code would also be much smaller (no if-checks for each side of the bounding boxes).

The downside is if your sprites don't fit well in circles, you would either get some overlap or separation depending on the radii you choose.

Here's one explanation, but Google will quickly point you to more http://strawberrycowbear.blogspot.com/2011/06/simple-sphere-based-collision-detection.html
> 2 votes

# Answer
I have not tried this, but it is along the lines of how this usually works in 3D physics Using 2D Vector math will yield more elegant and flexible solution. Essentially all you want to do is get rid of the velocity component which is in direct opposition to the obstacle.

E.g. Let w = wizard.Position, t = tree.Position, and assume bounding squares.

```
if (overlapping(w,t)) // we have a collision
{
    Vector2 d = t - w; // direction to obstacle
    float mx = d.X; float my = d.Y;
    Vector v;
    if (Math.Abs(mx) > Math.Abs(my)) // find direction of collision
        v = new Vector2(mx,0);
    else
        v = new Vector2(0,my);
    v = d - v;
    wizard.Velocity = v;
}

```

This is pseudocode. Even if this does not work, the goal behind it should give you the general idea.
> 0 votes

---
Tags: xna, c#, collision-detection
---


# Question
Title: Is there a "box2d without physics" lib (only for collision detection)?
Box2d Collision detection algorithms are probably the best ones out there. Unfortunately, they are bundled together with a realistic physics engine that I don't need.

Is there an open source project out there that strips out the physics part of Box2D, or provides a similar functionality?

# Answer
> 1 votes
You can can decide how to respond to collisions. See this question. You'll use collision filtering for detecting collisions, and simply set the objects not to respond to collisions.

To further remove the physics, you'll want to set the positions of your bodies directly, don't use their velocity values at all. Also remove gravity from the world.

---
Tags: collision-detection, physics, box2d
---