# Question
Title: 360+ degree rotation skips back to 0 degrees when using Math.Atan2(y, x)
I'm new to XNA and this is my first actual project, so forgive my noobness.

I'm using

```
 jointAngle = System.Math.Atan2(RightStick.Y, RightStick.X);

```

in order to set an angle of a joint (farseer) so that the attached body points in the direction pushed with the right joystick. This all works great and i get values from negative pi to pi which correlate with the pushed direction. The problem arises when i go from 360 degrees to 361. Instead of the continued rotation beyond 360 degrees that one might expect, it jumps back to 0 degrees (or -3.14 radians), which causes a jerking motion as the joint suddenly shifts 359 degrees back instead of 1 forward.

Is there a simple way to account for this? I came up with a few solutions, but they're all pretty messy at best and completely unreliable at worst.

Please help!

# Answer
> 10 votes
`atan2` is a mathematical function; it is stateless. There is nothing in it to “know” that you want an angle which is close to the angle from the previous frame, as opposed to an angle which is simply sufficient to identify the direction.

You must write your own logic to handle this case. There are several possible behaviors you could implement; here's the ones I've thought of. Note that I am not familiar with C#, XNA, or Farseer, so I have only pseudocode here, but all of these should work as long as you can retrieve the joint's current actual angle as well as the target angle.

1. The joint should spin the smallest amount to match the direction of the joystick. This means that if the user spins the stick faster than the joint can keep up, it will start turning the other direction to make a shorter motion. This can be implemented as:

```
let currentStickDirection = atan2(RightStick.Y, RightStick.X)
let currentJointDirection = currentJointAngle mod 2π
let difference = ((currentStickDirection - currentJointDirection + π) mod 2π) - π
jointTargetAngle = currentJointAngle + difference

```

The addition and subtraction of π (a half-turn) combined with modulus puts the difference-between-angles in the range −π…+π, which is the “smallest amount to match” property.

Note that if you are implementing, for example, a turret, then this might be undesirable as it makes it harder to strafe a particular arc as the player needs to make sure not to lead too much.
2. The joint should follow the motions of the stick. That is, if the user quickly makes multiple revolutions of the stick, the joint will follow and make multiple revolutions even if the user's movement is long over.

To implement this, the logic is the same as above except that instead of using the joint's current actual angle, we use the joint's target angle (which can be simply a variable/field in your program, unrelated to the physics engine) as the state input.

```
let currentStickDirection = atan2(RightStick.Y, RightStick.X)
let currentJointDirection = jointTargetAngle mod 2π
let difference = ((currentStickDirection - currentJointDirection + π) mod 2π) - π
jointTargetAngle += difference

```
3. Same as option 2, but the joint will never make an unnecessary full revolution. This differs from option 1 in that the joint will always turn in the same direction as the input does.

To implement this, use the code from option 2, but after all of the above we also remove extra `±2π`s from the target angle:

```
 let revolutions = (jointTargetAngle - currentJointAngle) / 2π
 if (revolutions >= 1)
     jointTargetAngle -= floor(revolutions) * 2π
 else if (revolutions <= -1)
     jointTargetAngle -= ceil(revolutions) * 2π

```

---

Note that if the stick is near its center, then small motions, possibly including noise/vibration rather than user motion, will cause large changes in the computed angle. If you haven't already, you will probably want to add a “dead zone” around the center which disables the angle computation. This can be a simple distance condition, like `pow(RightStick.Y, 2) + pow(RightStick.X, 2) < pow(deadZoneRadius, 2)`.

Another interesting option would be to reduce the “motor power” of the joint (I don't know what exact options Farseer provides in this area) depending on the computed distance, so that small pushes on the stick can be used to slowly swing the joint (note that then the imprecision of direction matters less) and moving it to the limit does a fast swing. This would naturally reduce the effect of noise about the center, but unless you are using option 1 above (which does not depend on the *previous target angle*) and your joystick has perfect mechanical return-to-center, you will still want to have a deadzone.

---

Commentary: The two key principles here are:

1. Work with *differences between angles*, not absolute angles.
2. Make sure that (where appropriate for the application) you are treating any particular angle *θ* as equivalent to *θ + 2π*. This is the reason for all of the uses of modulo; the π offsets are used to control where we flip from positive to negative numbers, which affects the overall behavior of the algorithm, but not in a way which is dependent on the input *range*.

---
Tags: xna, mathematics, game-mechanics, rotation, farseer-physics-engine
---


# Question
Title: How to disable and re-enable video card and keyboard drivers on Windows as part of program testing?
For my game I want to give the user full control. I am writing a hangman game where the user has the option of pressing the 'X' key on the keyboard to disable the keyboard driver completely, and 'G' to disable the graphics card.

You can re-enable by left-clicking the screen, but thus far I have found no ways of doing this, or tutorials, not even questions!

Can someone point me in the direction here? Thanks.

# Answer
> 2 votes
As this is for testing, I'd suggest getting the tester to do it manually through device manager in the windows control panel. The tester would have to disable and enable them an awful lot before it would become worthwhile programming some shortcuts.

Alternatively instead of disabling them at that level just program the game to have a couple of booleans that you adjust in the appropriate places which control rendering and input.

P.S. Why do you want to test this? I can't think of any sensible situation where this would happen when playing a game.

---
Tags: windows
---


# Question
Title: Orbiting multiple objects evenly around a changing radius
I have multiple objects (circles) and I want to place them in a circle, with even distance between each one, and have them orbit the center of the screen.

If I remove one object, I want the orbit radius to reduce and the other circles, as a result, end up getting closer and closing the circle again.

Below are some images to help explain what I'm trying to achieve.

A. is the objects evenly distributed around the center.

B. is after destroying one of the objects, the "circle of objects" need to close in and evenly distribute the objects once again.

C. is just after another object has been destroyed.

I know that the solution is some "basic" math, but it's been a while, and I'm super rusty.

Thanks for the help, if anything further is needed please let me know!!

Cheers!

o7

# Answer
> 9 votes
There are 360 degrees (2π radians) in a circle. Divide that by the number of objects, and that tells you the correct angle between the objects, for even spacing.

If you want to keep the objects the same distance apart no matter how many objects are in the circle, we need to calculate the distance out from the center at which points are that distance apart. That's just trigonometry; we make a triangle from the center to two adjacent objects. Split that into two right triangles, and use the cosin of the half angle to determine the distance from the center to one of the objects.

We can then use the angle and distanceFromCenter to place each object.

So if that calculated angle is `a`, then: (pseudocode)

```
float distanceBetweenObjects = 50.0; // or however far apart you want them to be
float distanceFromCenter = (distanceBetweenObjects*0.5)/sin(a*0.5);
float accumulatedAngle = 0.0;
foreach( object )
{
    object.position.x = cos(accumulatedAngle) * distanceFromCenter;
    object.position.y = sin(accumulatedAngle) * distanceFromCenter;
    accumulatedAngle += a;
}

```

Note that this assumes that the center of the screen is 0,0. If the center of your screen is some other coordinate, then add that to the calculations above. Also note that this doesn't take into account the size of the objects; it's merely trying to place their midpoints a certain distance apart. So your "sistanceBetweenObjects" value needs to include the size of the objects.

---
Tags: mathematics, actionscript-3, rotation, flash-develop
---


title: XNA 4.0 / C# Collision Response

text:
# Question
Title: XNA 4.0 / C# Collision Response
Okay, this is really starting to annoy me.

First of all, detecting collisions is nice and easy. I have a list of tiles, and a player. The player and each tile have their own rectangles. (The tiles are 16x16, the player is 10x14). To detect a collision, I simply iterate through the list of tiles to see if the player is colliding with any of them, and if so, set a value to true.

^The above works all fine and dandy, but I've tried just about every way I can think of to respond to that collision. I've ended up with some almost there but buggy results, and I can't find a single tutorial on 2D collision **RESPONSE**. Sure, there are thousands of tutorials out there about detection, but I'm having more trouble then I would think I would when I look for stuff about response.

The two methods I use for collision are;

```
        public bool CanMove(Rectangle playerRect, List<Tile> tiles, Direction d, Vector2 speed)
    {
        bool b = true;
        Rectangle r = new Rectangle();

        if (d == Direction.Up)
        {
            foreach (Tile ti in tiles)
            {
                r = new Rectangle(playerRect.X, (int)(playerRect.Y - speed.Y), playerRect.Width, playerRect.Height);
                if (r.Intersects(ti.rect))
                {
                    b = false;
                    return b;
                }
            }
        }
        if (d == Direction.Down)
        {
            int adjust = 1;

            if (playerPos.Y < 0)
                adjust -= 1;

            foreach (Tile ti in tiles)
            {
                r = new Rectangle(playerRect.X, (int)(playerRect.Y + speed.Y + adjust), playerRect.Width, playerRect.Height);
                if (r.Intersects(ti.rect))
                {
                    if (Math.Abs(r.Y - ti.rect.Y) > 12.5f && Math.Abs(r.Y - ti.rect.Y) < 13.5f && Math.Abs(r.X - ti.rect.X) > 14.5f && Math.Abs(r.X - ti.rect.X) < 15.5f)
                    {
                        playerPos.Y -= 1;
                    }
                    b = false;
                    return b;
                }

            }
        }

        if (d == Direction.Gravity)
        {
            int adjust = 1;

            if (playerPos.Y < 0)
                adjust -= 1;

            foreach (Tile ti in tiles)
            {
                r = new Rectangle(playerRect.X, (int)(playerRect.Y + speed.Y + adjust), playerRect.Width, playerRect.Height);
                if (r.Intersects(ti.rect))
                {
                    if (Math.Abs(r.Y - ti.rect.Y) > 12.5f && Math.Abs(r.Y - ti.rect.Y) < 13.5f && Math.Abs(r.X - ti.rect.X) > 14.5f && Math.Abs(r.X - ti.rect.X) < 15.5f)
                    {
                        playerPos.Y -= 1;
                    }
                    //adjustTile = ti;
                    b = false;
                    return b;
                }

            }
        }

        if (d == Direction.Left)
        {
            foreach (Tile ti in tiles)
            {
                r = new Rectangle((int)(playerRect.X - speed.X), playerRect.Y, playerRect.Width, playerRect.Height);
                if (r.Intersects(ti.rect))
                {
                    adjustTile = ti;
                    b = false;
                    return b;
                }
            }
        }
        if (d == Direction.Right)
        {
            foreach (Tile ti in tiles)
            {
                r = new Rectangle((int)(playerRect.X + speed.X), playerRect.Y, playerRect.Width, playerRect.Height);
                if (r.Intersects(ti.rect))
                {
                    b = false;
                    return b;
                }
            }
        }

        return b;
    }

```

And the portion of my update method that's necessary;

```
                if (kbs.IsKeyDown(Keys.Right) && kbs.IsKeyUp(Keys.Left))
            {
                direction = Direction.Right;
            }
            if (kbs.IsKeyDown(Keys.Left) && kbs.IsKeyUp(Keys.Right))
            {
                direction = Direction.Left;
            }

            //if (IsColliding(playerRectangle, tileList))

            if (playerSpeed.Y < 0)
            {
                playerSpeed.Y += 0.15f;
            }
            else
            {
                playerSpeed.Y += 0.2f;
            }
            //playerPos.X += playerSpeed.X;

            if (kbs.IsKeyDown(Keys.Space) && pkbs.IsKeyUp(Keys.Space))
            {
                playerPos = Vector2.Zero;
                playerSpeed.Y = 0;
            }

            playerRectangle = new Rectangle((int)playerPos.X + 3, (int)playerPos.Y + 2, 10, 14);

            if (playerRectangle.Contains(ms.X - viewport.Width / 2, ms.Y - viewport.Height / 2))
            {
                player.rectY = 16;
            }
            else
            {
                player.rectY = 0;
            }

            if (CanMove(playerRectangle, tileList, Direction.Gravity, new Vector2(0, playerSpeed.Y)))
            {
                if (playerSpeed.Y == 0)
                   playerSpeed.Y = 1f;
                playerPos.Y += playerSpeed.Y;
            }
            else
            {
                canJump = true;
                    playerSpeed.Y = 0f;
                    //if (adjustTile != null && playerPos.Y != adjustTile.rect.Y - 15)
                    //{
                    //    playerPos.Y = adjustTile.rect.Y - 15;
                    //    adjustTile = null;
                    //}
                    playerPos.Y = playerRectangle.Y - 2;

            }
            if (CanMove(playerRectangle, tileList, Direction.Left, new Vector2(playerSpeed.X, 0)))
            {
                //playerPos.X -= playerSpeed.X;
                player.rectY = 0;

            }
            else
            {
                player.rectY = 16;
            }
            if (CanMove(playerRectangle, tileList, Direction.Right, new Vector2(playerSpeed.X, 0)))
            {
                //playerPos.X -= playerSpeed.X;
                player.rectY = 0;

            }
            else
            {
                player.rectY = 16;
            }

            #region Check input

            if (kbs.IsKeyDown(Keys.Left) && pkbs.IsKeyUp(Keys.Right))
            {
                player.flipped = true;
            }
            if (kbs.IsKeyDown(Keys.Right) && pkbs.IsKeyUp(Keys.Left))
            {
                player.flipped = false;
            }

            if (kbs.IsKeyDown(Keys.Up) && pkbs.IsKeyUp(Keys.Up))
            {
                if (CanMove(playerRectangle, tileList, Direction.Up, new Vector2(0, 2)))
                {
                    if (canJump)
                    {
                        playerSpeed.Y -= 4.2f;
                    }

                    player.rectY = 0;

                }
                else
                {
                    player.rectY = 16;
                }
            }
            if (kbs.IsKeyDown(Keys.Down))
            {
                if (CanMove(playerRectangle, tileList, Direction.Down, new Vector2(0, 2)))
                {
                    //playerRectangle.Y += 2;
                    player.rectY = 0;

                }
                else
                {
                    player.rectY = 16;
                }
            }
            if (kbs.IsKeyDown(Keys.Left))
            {

                playerSpeed.X = 2f;
                if (CanMove(playerRectangle, tileList, Direction.Left, new Vector2(playerSpeed.X, 0)))
                {
                    playerPos.X -= playerSpeed.X;
                    player.rectY = 0;

                }
                else
                {
                    player.rectY = 16;
                }

                if (player.rectY == 16)
                {
                    playerPos.Y -= 1;
                }

            }
            if (kbs.IsKeyDown(Keys.Right))
            {
                playerSpeed.X = 2f;
                if (CanMove(playerRectangle, tileList, Direction.Right, new Vector2(playerSpeed.X, 0)))
                {
                    playerPos.X += playerSpeed.X;
                    player.rectY = 0;

                }
                else
                {
                    player.rectY = 16;
                }
                if (player.rectY == 16)
                {
                    if (playerPos.Y / 16 != (int)playerPos.Y / 16)
                    {
                        playerPos.Y -= 1;
                    }
                }
            }

            if (kbs.IsKeyUp(Keys.Right) && kbs.IsKeyUp(Keys.Left))
            {
                playerSpeed.X = 0;
            }

            #endregion

```

This is almost there, but there are one or two kinks in it.

If I'm up against a wall of tiles, and jump, I'll end up in the roof(If not going completely through it) if it's low enough.

The reason I add the 'playerpos.y -= 1' in certain spots is because the player would get stuck when coming down on a corner at the right angle.

Also, when the player goes to jump, and come back down, he will hit an invisible wall (usually about 8 pixels or so above the tile he would be landing on) before continuing to fall and land on the said tile.

Any tips or advice?

And yes, this is 2D, there is gravity and such, I'm trying to get it to work kinda like the way mario collisions work.

EDIT: The new code is actually what I came up with to start with, the `HandleCollisions()` thing was an attempt to try and implement the Platformer Starter kit code, which didn't work very well. The `GetRectangleIntersectionDepth()` might come in handy though.

# Answer
For very simple response:

1. Store the position of the player in a temp variable
2. Move the player
3. Check for collision
4. If there is collision, reset the player position to the temp position.

Depending on the speed of the player you might have a gap between the tile and the player.
> 3 votes

# Answer
You were right, but I finally figured out a more advanced way (And amazingly rock solid) way of detecting and responding to a tile based level. (This code assumes the players and all tiles are 16x16, and their corresponding origins are all (x0, y0))

First, I declare these variables at the start of the player's update method;

```
            // The middle points of the 4 edges of the players bounding rectangle
        topMiddle = new Vector2(pos.X + rect.Width / 2, pos.Y);
        bottomMiddle = new Vector2(pos.X + rect.Width / 2, pos.Y + rect.Height);
        leftMiddle = new Vector2(pos.X, pos.Y + rect.Height / 2);
        rightMiddle = new Vector2(pos.X + rect.Width, pos.Y + rect.Height / 2);

        // The distance on one axis, reset and re-used after each direction check
        int distanceToPlayer = 0;

        // The index in the list of tiles of the closest tile to the player
        // The one above,
        int nearestObjectU = 0;

        // the one below,
        int nearestObjectD = 0;

        // the one to the left,
        int nearestObjectL = 0;

        // and the one to the right.
        int nearestObjectR = 0;

```

I then check for each tile, one direction at a time;

```
            #region Check Top

        foreach (Tile t in tileList)
        {
            if (t.rect.Y + 1 < pos.Y && topMiddle.X + 7 >= t.rect.X && topMiddle.X - 7 < (t.rect.X + t.rect.Width))
            {
                if (distanceToPlayer == 0)
                {
                    nearestObjectU = tileList.IndexOf(t);
                    distanceToPlayer = (int)Math.Abs(pos.Y - t.rect.Y);
                }
                else if (Math.Abs(pos.Y - t.rect.Y) < distanceToPlayer)
                {
                    nearestObjectU = tileList.IndexOf(t);
                    distanceToPlayer = (int)Math.Abs(pos.Y - t.rect.Y);
                }

            }
        }

        tileList[nearestObjectU].color = Color.Red;
        closestUp = tileList[nearestObjectU];
        distanceToPlayer = 0;

        #endregion
        #region Check Bottom

        foreach (Tile t in tileList)
        {
            if (t.rect.Y - 1 > pos.Y && topMiddle.X + 7 >= t.rect.X && topMiddle.X - 7 < (t.rect.X + t.rect.Width))
            {
                if (distanceToPlayer == 0)
                {
                    nearestObjectD = tileList.IndexOf(t);
                    distanceToPlayer = (int)Math.Abs(pos.Y - t.rect.Y);
                }
                else if (Math.Abs(pos.Y - t.rect.Y) < distanceToPlayer)
                {
                    nearestObjectD = tileList.IndexOf(t);
                    distanceToPlayer = (int)Math.Abs(pos.Y - t.rect.Y);
                }

            }
        }

        tileList[nearestObjectD].color = Color.Red;
        closestDown = tileList[nearestObjectD];
        distanceToPlayer = 0;

        #endregion
        #region Check Left

        foreach (Tile t in tileList)
        {
            if (t.rect.X + 1 < pos.X && leftMiddle.Y + 7 >= t.rect.Y && leftMiddle.Y - 7 < (t.rect.Y + t.rect.Height))
            {
                if (distanceToPlayer == 0)
                {
                    nearestObjectL = tileList.IndexOf(t);
                    distanceToPlayer = (int)Math.Abs(pos.X - t.rect.X);
                }
                else if (Math.Abs(pos.X - t.rect.X) < distanceToPlayer)
                {
                    nearestObjectL = tileList.IndexOf(t);
                    distanceToPlayer = (int)Math.Abs(pos.X - t.rect.X);
                }

            }
        }

        tileList[nearestObjectL].color = Color.Red;
        closestLeft = tileList[nearestObjectL];
        distanceToPlayer = 0;

        #endregion
        #region Check Right

        foreach (Tile t in tileList)
        {
            if (t.rect.X > pos.X - 1 && rightMiddle.Y + 7 >= t.rect.Y && rightMiddle.Y - 7 < (t.rect.Y + t.rect.Height))
            {
                if (distanceToPlayer == 0)
                {
                    nearestObjectR = tileList.IndexOf(t);
                    distanceToPlayer = (int)Math.Abs(pos.X - t.rect.X);
                }
                else if (Math.Abs(pos.X - t.rect.X) < distanceToPlayer)
                {
                    nearestObjectR = tileList.IndexOf(t);
                    distanceToPlayer = (int)Math.Abs(pos.X - t.rect.X);
                }

            }
        }

        tileList[nearestObjectR].color = Color.Red;
        closestRight = tileList[nearestObjectR];
        distanceToPlayer = 0;
        #endregion

```

Thus, the player now holds the tile in each of the 4 directions on the X and Y axes closest to him, and can be used in the Main update accordingly. You may have noticed that for each direction, when it had found the closest tile, it painted it `Color.Red`. This was so I could visually see which tiles it was selecting. (The tile classes update method automatically changes its color back to white before this is called, so only the four adjacent ones are red.) And then, in the main update method, you simply keep the player from moving past these points, like so;

```
                    #region Apply Gravity

                if (playerPos.Y < player.closestDown.rect.Y - 16)
                {
                    if (playerSpeed.Y < 0 && playerSpeed.Y > -0.5f)
                        playerSpeed.Y = 0.2f;

                    if (playerSpeed.Y < 0)
                    {
                        playerSpeed.Y += 0.2f;
                    }
                    else
                    {
                        playerSpeed.Y += 0.3f;
                    }
                }
                else
                {
                    playerSpeed.Y = 0;
                    playerPos.Y = player.closestDown.rect.Y - 16;
                }

                if (!(playerPos.Y > player.closestUp.rect.Y + 16))
                {
                    playerPos.Y = player.closestUp.rect.Y + 16;
                    playerSpeed.Y = 1f;
                }

                #endregion

                #region Keep in bounds

                if (!(playerPos.X > player.closestLeft.rect.X + 16))
                {
                    playerSpeed.X = 0;
                    playerPos.X = player.closestLeft.rect.X + 16;
                }

                if (!(playerPos.X < player.closestRight.rect.X - 16))
                {
                    playerSpeed.X = 0;
                    playerPos.X = player.closestRight.rect.X - 16;
                }

                #endregion

                #region Proccess Input

                if (kbs.IsKeyDown(Keys.Up) && pkbs.IsKeyUp(Keys.Up))
                {

                        playerSpeed.Y -= 6f;

                }
                if (kbs.IsKeyDown(Keys.Down))
                {

                }
                if (kbs.IsKeyDown(Keys.Left))
                {
                    if (playerPos.X > player.closestLeft.rect.X + 16)
                    {
                        if (playerSpeed.X == 0)
                        {
                            playerSpeed.X -= 1;
                        }
                        if (playerSpeed.X > -5.7f)
                        {
                            playerSpeed.X += -0.3f;
                        }
                    }
                    else
                    {
                        playerSpeed.X = 0;
                        playerPos.X = player.closestLeft.rect.X + 16;
                    }
                }
                if (kbs.IsKeyDown(Keys.Right))
                {
                    if (playerPos.X < player.closestRight.rect.X - 16)
                    {
                        if (playerSpeed.X == 0)
                        {
                            playerSpeed.X += 1;
                        }
                        if (playerSpeed.X < 5.7f)
                        {
                            playerSpeed.X += 0.3f;
                        }
                    }
                    else
                    {
                        playerSpeed.X = 0;
                        playerPos.X = player.closestRight.rect.X - 16;
                    }
                }

                if (kbs.IsKeyUp(Keys.Right) && kbs.IsKeyUp(Keys.Left))
                {
                    if (playerSpeed.X > 0.1f)
                    {
                        playerSpeed.X -= 0.35f;
                    }
                    if (playerSpeed.X < -0.1f)
                    {
                        playerSpeed.X += 0.35f;
                    }

                    if (Math.Abs(playerSpeed.X) < 0.2f)
                    {
                        playerSpeed.X = 0;
                    }
                }
            }

                #endregion

```

It makes sure that the player can't go past those points, and double checks when trying to move. I was surprised at how solid it was once I managed to finish it.

And yes, I know the code is poorly commented. It should be fairly straight forward anyways.

That article on 2D platformers gave me the idea on how to code this. It's so freaking solid, I'm going to make a tutorial on how to implement this type of collision response.
> 0 votes

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


# Question
Title: Use an external sprite or image file in flixel game in flashbuilder
Is there any way to use an external image/sprite file for the graphic of a FlxSprite instance?

Say I declare my player FlxSprite as follows:

```
player = new FlxSprite(FlxG.width/2 - 5);
player.makeGraphic(10,12,0xffaa1111);

```

How could I instead instantiate the FlxSprite using my own spritesheet or image? I have seen others do it in the Flixel demos , and in the featured games.

# Answer
You want to use the loadGraphic method of FlxSprite, here's an example :

```
// in your class declarations
[Embed(source="your.png")] private var yourGraphic:Class;

// in your class code wherever, after you have created an instance
// use true for second parameter if image is a row of sprite frames
player.loadGraphic(yourGraphic, false);

```
> 0 votes

---
Tags: sprites, actionscript-3, spritesheet, flixel
---


# Question
Title: How to get enemy to follow character using angles? (atan2)
I have an enemy and a character to control. I want to get the enemy to follow the character in a straight line. I already found the angle in which the enemy needs to travel.

```
double angle = Math.atan2(y, x) * 180 / Math.PI;

```

Now, let's say it return 73.0. What do I do with that number? And what if it's a negative angle.

BTW, I'm using dx(dynamic x) and dy(dynamic y) to control movement.

# Answer
> 6 votes
You do not need to know the angle, because the difference in X and Y already gives you the desired orientation of the enemy. The only thing that remains to be done is normalise that direction vector (if possible -- otherwise it means the player and the enemy are exactly at the same position), and multiply it by the enemy’s speed:

```
dx = player_x - enemy_x;
dy = player_y - enemy_y;
float norm = Math.sqrt(dx * dx + dy * dy);
if (norm)
{
    dx *= (enemy.speed / norm);
    dy *= (enemy.speed / norm);
}

```

# Answer
> 4 votes
```
double angle = Math.atan2(y,x);  // Note: keeping angle in radians for cos & sin.
dx = enemy.speed * Math.cos( angle );
dy = enemy.speed * Math.sin( angle );

```

This will work fine with negative angles.

See also: What are atan and atan2 used for in games?

---
Tags: java, angles
---


# Question
Title: Gamification: designing cooperation in an RPG like game based on Scrum methodology
I have implemented with 3 friends a gamified system at my work (development company) which builds an fantasy rpg game over scrum project methodology. Generally, the tasks are the missions, each player is represented by a character. They earn XPs for completing tasks and they advance to the next levels which gives them badges, titles and (this is in planning phase) new privileges (e.g. priority in choosing tasks).

Since the very beginning we try to do everything to avoid rivalisation between players because it would ruin the project if the players started to compete. There are no explicit leaderboards, we also plan to give bonuses for helping other players.

I have a feeling that this is still not enough to really encourage cooperation. I would like to ask You for any ideas that come to Your mind that would help.

# Answer
Perhaps make it so that:

1. Players can trade tasks with others to get assignments better suited to their interests or skills. As pointed out in the comments, this could lead to players gaming the system by taking good tasks and sitting on them for trading later. To prevent this, perhaps a task could have something like a "timeout" and if it sits in a player's queue for longer than that timeout it becomes "up for grabs" again and they are docked points. Similar to what might happen if you promise to finish X tasks for a sprint but fail to do so. This will stop people from pulling good tasks and sitting on them. Players can avoid the point loss by trading their task to another player and in this case the timer resets for both tasks. This should encourage interaction with other players,e.g. p1 and p2 are both about to lose points on a task so they trade tasks in order to start fresh.
2. A player can decide to share a task with another player such that both of them working to complete it. When it is completed they both earn a percentage of the reward.

You might award specific badges or privileges for "number of assists" to benefit players who invest time working with others.
> 2 votes

# Answer
You can use a "party system" that allow the player invite another player to help him in your quest. Who invite gets a bonus and who is invited too. This kind of approach (mutual bonuses) help the players to work together. Its good ask for help and is good be "asked for help".
> 3 votes

# Answer
Only a small idea, but maybe you could make the complete **sprint backlog** a (team) quest and when all tickets are finished in time they all get experience?

Or like when the **bug backlog** is empty at the end of the day, they get some additional experience or badges or whatever your RPG includes. This would make them fix bugs rapidly.

I guess generally team quests are a feature to make them work **together**.
> 1 votes

# Answer
Here is one idea which have worked since the begining of my experimentation: since we work with Agile, one of our Skills on the character profile is the Agility, and you can gain points on this by finishing the task in a pre-set time; for example, the estimation of the whole task (not brokendown) is 15h, and the character finish it in 10h, so he/she gains some agility.
> -1 votes

---
Tags: game-design
---


title: 16-bit PNGs in Slick2D

text:
# Question
Title: 16-bit PNGs in Slick2D
I'm working on a project and I'm using some 3rd party sprites just to get it off the ground; recently I've come into a hitch. Slick2D doesn't seem to want to load my images. That is, it will warn me that images are the wrong bit-depth. All the images are in 16-bit PNG form (PNG is required for transparency). Is there any way I can disable the warning (being the bad guy programmer (the console print for each individual load REALLY SLOWS DOWN the image)) or is there another solution?

I was thinking about converting all images (using imagemagick) to .gif (with an alpha channel). Would there be any loss in quality between formats?

EDIT: I tried using imagemagick but some of the sprites use pure black so I can't do that without wrecking the image.

EDIT2: using "identify" on any of the images show them as being 8-bit.. but Slick2D won't load them. What the hell? D:

EDIT3: Issue solved (ish). If you are googling this then just disable the java png loader from slick by sticking this somewhere in your code (like the main method):

```
System.setProperty("org.newdawn.slick.pngloader", "false");

```

# Answer
See main post - Disabled the Slick PNG loader by sticking this in the Main method:

```
System.setProperty("org.newdawn.slick.pngloader", "false");

```
> 2 votes

# Answer
You really should just convert all your images to **8 bit PNG**.

PNG16 bit PNG uses 16 bits for Red, 16 Green, 16 blue, and 16 alpha. So 64 bits/pixel.

PNG8 uses R8G8B8A8, 8 bits for each of red, green blue, alpha. Or 32 bits/pixel.

With PNG8, you get much less color depth. But for a mobile game, you don't need it, and the display format will very likely be R8G8B8A8 anyway. PNG16 bloats file size anyway, so at the end of the day you really do want to use PNG8 these days.

In Photoshop, to save as an 8-bit PNG, you have to convert to 8 bits/channel useing Image/Mode/8 Bits/Channel:

GIF uses 1 bit for alpha (transparent or **not**) and is largely outdated and superceeded by PNG. I would advise never use GIF.
> 2 votes

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


# Question
Title: How should multiplayer games handle authentication?
I've been lurking around to understand how an authentication system would work in games, but after many searches, it seems that working with ssl/certificates could be a little complicated for just a multiplayer game with a lot less capacity than an MMO.

I know that successful multiplayer games need this, but I'd like to check if other multiplayer games commonly take this precautions.

**EDIT**: I'll describe what I have in mind. The server not only handles game logic, but also authentication. So, in order to play on a specific server (that everyone could start), you first need to register an account on the server, and each time you want to play there, login as usual (password/name user).

My question is, would not providing a secure channel for logging in/registering an account be forgivable/understandable in this context? Also I'm interested to know how games with a similar architecture would handle this matter.

# Answer
Specifically regarding the last bit of your question: No, it is never forgivable to have an insecure authentication system. Users are rarely enlightened when it comes to computer security. Users use the same password for your little game as they do for their Google account, Facebook account, bank account, and so on. Even if you can claim that it's their fault for using poor Internet security habits, you're the one who will be held responsible if your game is used as an attack vector to steal users' login credentials. As a developer who knows better, the only ethical options are to properly secure your authentication process or to not have one at all.

As some unsolicited but related advice, users don't want to be required to sign up for your game anyway. They might do so if they want to play your game badly enough, but having Yet Another Freaking Login to sign up for is going to just drive away many potential players. Users are sick to death of making a new account for every single site, service, and game out there, *especially* if they require any kind of email validation or the like. If you can, either avoid having a login at all, or use an existing third-party authentication service that users likely already have an account with. You will have more players that way. This goes triple if you plan on having any kind of in-app purchases.

**Web Games**

A popular option -- particularly for Web games, though it also works for traditional games -- is to use a Web-based third-party authentication service. Facebook and Google both have well-documented APIs (both based on standardized APIs, iirc) for authentication. They do require the ability to open a browser window and direct the user towards their services, but this is pretty easy to do on most non-console platforms, and of course trivial for Web games.

Those services take care of all the messy details of encrypting login traffic over the wire, securely storing login credentials, and validating user logins. Your game server then needs only implement the portion of the protocol that receives a cookie from the user and asks the authentication service if the cookie is valid or not, which can be done with a simple HTTP in most cases.

I won't claim most traditional multiplayer games do this, because they don't, but I will claim that most online casual Web games do this.

For traditional (non-Web) games, facilitating this login procedure is possible by either embedding a browser (Awesomium, Chromium Embedded Framework, or straight up Webkit being popular choices) or by calling out to an external browser (this takes some more fanagling to get the auth cookie out of though, and isn't really any easier than embedding one of the aforementioned libraries).

A typical example of this approach is any Facebook game.

**Traditional Games using HTTPS**

Having a simple HTTPS service for login is increasingly normal. Many games use custom protocols, but most of these are incomplete (they have secure login, but no secure way to create/update an account, so they need the HTTPS service anyway) or are simply horrifically insecure.

You don't even need to go about getting a custom SSL cert. There are online app hosting providers that give you a subdomain and use a wildcard SSL cert. You can put your authentication service at mygame.someservice.com, which is covered by the \*.someservice.com wildcard cert that Some Service maintains, and you're good to go.

The idea here is that the user logs in to your service, which generates a unique session cookie, which the user can then pass into your main game server. The server then asks the login system if the cookie is valid for the requested user. There's usually a *very* short timeout on the cookie, on the order of seconds (15-30, for example), and it's generally invalidated once used, making replay attacks impossible.

Note that HTTPS is my most recommended option if you plan on sending payment information over the wire from inside the client itself. However, it's significantly better to use a third-party for this. If you think securing something as simple as a password is too much work, you don't even want to even think about trying to meet the minimum (and honestly quite inadequate) PCI compliance rules for storing and processing credit card numbers. You'll have better sales uptake anyway if you have users use trusted third-party payment services that they're already on file with.

One strong advantage of separating your login service from the main game server is that it allows external functionality to be tied to user accounts independent of the game. You might have some account features (viewing avatars or such) on your website, or perhaps you allow linking Facebook accounts into your accounts, or perhaps you have multiple games sharing a single underlying account platform (e.g., the Galaxy at War features of Mass Effect 3).

A popular example game using HTTPS for authentication is Minecraft.

**Third-Party Web Authentication with Native Client Games**

It is possible to use third-party services like Facebook Connect or Google with a native client. Facebook for example has a native SDK for iOS and Android, as does Google. Some services likewise have native SDKs for traditional PC clients.

If the target service does not having a native SDK and requires the use of a Web browser, you could just embed a browser in your game. However, some users may be distrustful of using an embedded browser to enter login information.

You can also use an external browser. There are a few ways to pull this off. Some require a little bit more OS-integration than others. Some require you to have an external Web service running alongside (or at least reachable by) your main game server. Note that since Facebook and Google generally require a URL that is authenticated, you will need a public website landing page to use these protocols in (almost) all cases.

The most fool-proof and reliable, if not quite the easiest, is to bounce your login request from your client through your main website. Your client connects to the main game server as an authenticated guest user and receives a unique session token. The game server does not allow the client to actually do much while in this state; the game doesn't know who the player is, so the player cannot yet chat, start a match, or so on.

The client then launches the external browser pointing at the login URL of your game's domain, passing this session token as a parameter in the URL. The site then goes through the usual login handshake for Facebook/Google.

At this point, your webserver knows that the user has logged in, and can associate that with the session token it received from the client. This verification can then communicated to the game server, elevating the client's unauthenticated guest connection into an authenticated user session. This can be done by having the webserver directly communicate with the game server, if possible. Or the game server can periodically poll the webserver for authentication status of pending guest connections. Or the client can periodically poll the webserver to see if login is complete and, when it is, signal the game server to request verification from the webserver.

All of these require that your game server and webserver be able to communicate, but *any* third party authentication service will require your game server to be able to communicate with the outside world, so this shouldn't be a surprise.

This authentication method is found in some small-to-mid-sized MMOs.

Note that this all also works for making payment requests through an external service, like PayPal, Amazon Payments, Google Wallet, etc.

**Direct TLS Connection**

It is not too difficult to start a TLS session over a custom stream protocol. Libraries like OpenSSL, GnuTLS, NSS, and various OS-specific libraries provide a stream wrapper API that layers over a low-level transport/protocol. You generally just need to feed bytes through the wrapper API and it deals with the handshake and encryption.

The tricky parts here are ensuring your use of TLS is safe. Some of the common libraries for example will by default require a valid signed certificate from a trusted authority. Some of the common libraries require that, but by default don't trust any authorities. Some of them do not require that the cert be valid at all.

It is recommended that you always require a valid cert. Allowing invalid certs will not allow an attacker who is merely eavesdropping to steal a password, but it will still allow man-in-the-middle attacks.

This approach requires the absolute least in terms of external dependencies while still allowing maximum security.

Examples of games using this now include most big traditional MMOs.

**Secure(ish) Traditional Games**

Games that don't use a separate service and don't use TLS typically have to implement some kind of nonce-based login protocol in their main game protocol. With this method, the server generates a random number (a nonce) and sends that to the client. The client then hashes that nonce with the user's password (and username, possibly some other data) and sends that response to the server. The server then compares this hashed value with the credentials it has on file. This keeps the user's password secrete over the wire and ensures that you can't use a simple replay attack on the hashed password, like many other weak hash-based login schemes.

A problem is that the user has no way to submit a new password to the service over this protocol securely. Typical implementations also store the user's password in plaintext on the server, which is a horrible practice (if your server gets hacked, your user probably just had his email/facebook/bank password stolen, because he was using the same password for your game as everywhere else, because users tend to do that).

There are enhanced versions of that basic login scheme. The most basic -- though still not ideally secure -- is for the server to send the password hash salt with the nonce value during login. This allows the server to stored a hashed (and salted) password securely while allowing the client to generate the same hash during login. This does allow an attacker to get the salt for a particular user's password, but this is not particularly useful without also getting the original hashed password (which is not sent over the wire during login). During creation/updating of the password, the client sends the whole hashed password (with salt), which the attacker can sniff. If the hash function used is strong enough (say, sha-2/512) then pure brute forcing is not feasible, though the attacker can still easily brute-force weak passwords (which is why enforcing some minimum password length, minimum distribution of letters/numbers/symbols, and comparing to a dictionary of known/obvious/weak passwords is important). The fact that the attacker can still get the hashed password is why it still more secure to do the entire password exchange over a secured, encrypted channel.

A number of popular game networking libraries implement some optional form of this protocol. I believe SmartFox is one such example, though I haven't looked at it in depth (I generally ignore any such library auth system and use the HTTPS method, since it's dead simple to implement and significantly stronger). A number of early non-Web Internet games also used this approach, particularly before Steam, XBL, and so on came around.

**Unsecure Traditional Games**

A lot of games unfortunately just send a username/password in plaintext. Maybe they hash the password, which vaguely kind-of protects the users actual password (not nearly well enough) but a replay attack makes logging into the game service trivial.

Don't do this. It's irresponsible and lazy. The Internet naiveté of the 1990's that popularized these login methods is no longer a viable excuse.

Many early pre-Facebook Flash and web games took this approach. I don't know of any specific examples off the top of my head; I'd like to believe they're all long dead, but the world just isn't that lucky.

**No Authentication**

Most games just don't do authentication. The player connects, sends over some handle to uniquely identify himself, and a match starts. There is no global server that tries to validate that only one real human is ever allowed to claim to be "CaptainMisterDude". The local server just ensures that only one currently connected player has any particular handle, and that's the end of it. Local servers use name-based and IP-based blacklisting for trouble makers. This is common for FPS deathmatch style games even today.

If you don't need any permanent state for accounts, this is by far the easiest solution, and quite "secure" since there's nothing there to actually hack or steal. Obviously this doesn't work too well if you do need to store account information between game sessions.

Quake is an example of a game using this method of "authenticating" users.
> 46 votes

# Answer
SSL would help the clients to identify legitimate servers, vs "fake" servers, by using a server-certificate signed by a known CA. I strongly suspect that most games do not bother to do this.

There are, however, good reasons why they might want to. Some licensing avoidance / cheating mechanisms might work by using a rogue server, or a "man in the middle" server.

I expect the major multiplayer networks such as Steam and Microsoft, have such protection built-in though.

Web-based game can simply use HTTPS, but I don't know if that works for Websockets (a trivial Google should answer it).
> 3 votes

---
Tags: multiplayer, security
---


# Question
Title: OpenGL: Is it possible to use VAO's without specifying a VBO
On all the tutorials I can find about VAO's (Vertex Array Objects), they show on how to use them by configuring vertex attributes and binding a VBO (Vertex Buffer Object). But I want to create a VAO that will be configured for a set of VBO's in combination with a fixed shader, where each buffer uses the same data pattern (vertex, uv, color, etc). So, I want to create one VAO for multiple VBO's that will be drawn using one shader.

I couldn't find any demo on this, so I decided to just give it a try. But it doesn't work and crashes on the `glDrawArray` call. It looks like the VBO isn't bound. Here is the code I'm using:

**Rendering:**

```
/* Prepare vertex attributes */
glBindVertexArrayOES(vao);

/* Upload the buffer to the GPU */
glBindBuffer(GL_ARRAY_BUFFER, pool->next());
glBufferSubData(GL_ARRAY_BUFFER, 0, parts * buffer.stride() * 6, buffer.getBuffer());

/* Draw the triangles */
glDrawArrays(GL_TRIANGLES, 0, parts * 6);

glBindVertexArrayOES(0);

```

**VAO Creation:**

```
glBindVertexArrayOES(vao);

glEnableVertexAttribArray(ls.position);
glVertexAttribPointer(ls.position, 2, GL_FLOAT, GL_FALSE, buffer.stride(), 0);

glEnableVertexAttribArray(ls.color);
glVertexAttribPointer(ls.color, 3, GL_FLOAT, GL_FALSE, buffer.stride(), GL_BUFFER_OFFSET(buffer.dataTypeSize * 2));

glBindVertexArrayOES(0);

```

Where `ls` is a simple `struct` that holds the attribute locations.

In the Rendering part, swapping the `glBindBuffer` and the `glBindVertexArrayOES` around didn't work either.

So, the question is: Is it even possible to do so, or will I have to create for each buffer a VAO? And if I have to create a VAO for each VBO, is it possible to update the VBO's data using `glBufferSubData` in combination with a VAO?

# Answer
VAOs do not contain "glBindBuffer" state, with the exception of `GL_ELEMENT_ARRAY_BUFFER`'s binding state. What you're not understanding is that `glBindBuffer(GL_ARRAY_BUFFER)` ***doesn't do anything***. Well, it doesn't do anything as far as rendering is concerned. Try it; right before calling glDraw\*, call `glBindBuffer(GL_ARRAY_BUFFER, 0)`; your rendering will work just fine.

The way `glVertexAttribPointer` works is that it looks at what is bound to GL\_ARRAY\_BUFFER **at the time `glVertexAttribPointer` is called**. Not at render time. Not later. Right at that exact moment. It takes whatever buffer object was there and stores it in another piece of OpenGL state, which is encapsulated within the VAO.

In general, you have two options, one of them that's new and probably shouldn't be used at this point in time.

Your first option is to put all objects that use the same vertex format (ie: everything except the buffer object and offset) in the same buffer object. Basically, build a giant array that contains all the vertices for all object that use the same format.

When it comes time to render, you can render a portion of the vertices. `glDrawArrays` takes a range of elements to render, and you can adjust your indices in `glDrawElements` to do the same. Alternatively, you can use `glDrawElementsBaseVertex` to bias the vertices, so that an offset is added to each index. This offset is the number of vertices before that vertex in the big array.

The other alternative is to use the relatively new format attribute separation system added in GL 4.3. It would allow you to change buffers without resetting the format. Thus you would bind a single VAO, then just substitute in different buffers as needed with `glBindVertexBuffer`. This is also available in ES 3.1.
> 19 votes

# Answer
The VAO stores the glVertexAttribPointer state. Changing the VAO does not affect the current glBindBuffer, nor does changing the glBindBuffer affect the VAO. Only the glVertexAttribPointer call affects the VAO, by recording the buffer in use at the call.

So the answer to your question is no.

One option if you want to reduce the number of objects is to put all your mesh data into one large VBO and specify where the mesh data lives in the VBO in the glDrawArrays call using the 'first' and 'count' arguments.
> 5 votes

---
Tags: opengl, vbo, vao
---


# Question
Title: Running advanced floating point calculations on the GPU?
I want to learn how to use AMD Stream and NVIDIA CUDA (PhysX) to calculate things such as locations. I have not yet found where to get the SDK for these (I can't test the CUDA things because I have a AMD graphics card but it's plenty of power for advanced game dev). So do any of you people know where to get these? Or even better a single library to control both platforms in the same way so I don't have to learn two different platform libs. I would also like to say that I will be using DX11.

# Answer
Take a look at OpenCL, it's an open API that's implemented on a bunch of platforms, including NVIDIA and AMD GPUs.

Also, you can interop with DirectX pretty easily, here is an article on the subject.
> 4 votes

---
Tags: c++, directx11, nvidia, amd
---


# Question
Title: Implementation of planets in top-down space shooter
I am working on a top-down space shooter, and I have come to the point where I need some input on a mechanic. I have implemented enough that I can make this choice; either way will not change the code in any major fashion.

Which would be a more interesting feature: Having planets being among the 2d objects that the ships interact with (crashing into, being able to have batteries that fire from them); or should they be background objects, maybe still having effects on the battle, but less of a direct influence.

Practical differences: Would the planets have gravity (first yes, second maybe not)? Would they take up space (first yes, second no)? Any other differences that might affect the differences, please let me know.

# Answer
Try both. I expect the difference in your code should be trivial. Play for a while with each and decide which feels better. Then recruit some others to play and see what they think.
> 4 votes

---
Tags: 2d, game-design, game-mechanics, physics
---


# Question
Title: Unity (Javascript Syntax) Isn't Allowing Me to Override My Inherited Method
First, I would like to say I apologize if this has already been asked and there is already an available thread covering this. I did my very best to try and find a resolution to this using preexisting resources, but nothing is really helping me.

Next the information I've been working from is here:

http://wiki.unity3d.com/index.php?title=Head\_First\_into\_Unity\_with\_UnityScript#Virtual\_functions\_can\_be\_used\_to\_override\_functions

It states that the virtual keyword is used to override functions/methods down the line if inherited from another object. More so it is my understanding that Unity automatically uses virtual key word unless otherwise specified.

So hypothetically with this train of thought in mind I would simply just pre-pend override in my function declaration and it should override it. However. That is not the case.

What occurs next is an error:

> Assets/Scripts/Classes/Actors/TestPlayer.js(500,18): BCE0089: Type 'TestActor' already has a definition for 'getMovementVector()'.

Below are the class definitions shortened to just the initial skeleton and the functions I'm discussing.

```
class Actor extends DefaultGameObject {
    function getMovementVector() : Vector3 {
        var moveDirection = Vector3(0, 0, 0);

        if(isJumping && !jumpUsed) {

            //TODO: If double jump is added modify this line
            //so that the speed can be changed if you want that
            moveDirection.y += jumpSpeed;

            if(jumpTimer < jumpTimerMax) {
                jumpTimer++;
            }
            else {
                isJumping = false;
                jumpUsed = true;
                //animatedImage.animateOnceAndStopAtEnd(39, 39, 41);
            }
        }

        if((movingLeft || movingRight) && !(movingLeft && movingRight)) {
            if(movingLeft) {
                moveDirection.x -= moveSpeed;
            }
            if(movingRight) {
                moveDirection.x += moveSpeed;
            }
        }

        //applies gravity
        if(!isJumping) {
            moveDirection.y -= fallSpeed;
        }

        return moveDirection;
    }
}

```

Below is the code for the class that inherits from the above class with its function/method.

```
class TestActor extends Actor {
    override function getMovementVector() : Vector3 {
        var moveDirection = Vector3(0, 0, 0);

        if(isJumping && !jumpUsed) {
            if(doubleJumpUsed) {
                moveDirection.y += jumpSpeed;
            }
            else {
                //Debug.Log("omg jumping");
                moveDirection.y += jumpSpeed;
            }
            if(jumpTimer < jumpTimerMax) {
                jumpTimer++;
            }
            else {
                isJumping = false;
                jumpUsed = true;
                animatedImage.animateOnceAndStopAtEnd(39, 39, 41);
            }
        }

        if((movingLeft || movingRight) && !(movingLeft && movingRight)) {
            if(movingLeft) {
                moveDirection.x -= moveSpeed;
            }
            if(movingRight) {
                moveDirection.x += moveSpeed;
            }
        }

        //applies gravity
        if(!isJumping) {
            moveDirection.y -= fallSpeed;
        }
        return moveDirection;
    }
}

```

To me it seems relatively straightforward, but no matter what I do I cannot for the life of me get it to stop complaining about a method that has already been declared for it. I've tried explicitly using the virtual keyword as well. I tried adding access modifiers and that didn't change anything.

I would really appreciate any help or directions on where I can go for this. Thank you.

# Answer
> 1 votes
Oh wow... This is embarrassing...

I'm just a big dope and didn't realize hidden in my file there was an empty method by the same name declared.

Thank you to all those who tried to answer this question. I appreciate the time and patience you all demonstrated.

# Answer
> 0 votes
UnityScript doesn't use the override keyword. Use virtual instead.

http://wiki.unity3d.com/index.php/Head\_First\_into\_Unity\_with\_UnityScript#Virtual\_functions\_can\_be\_used\_to\_override\_functions

Edit: Looking your question over again, it seems you've already tried that. Are you sure you did it the way it shows at the link? I'm not sure why your code isn't complaining about the use of "override"; it's not even a keyword in UnityScript.

---
Tags: unity
---


# Question
Title: Creating Animations Without Hardcore Art for 2D Action RPG
I'm working on a 2D action RPG. One of the issues I run into is art; in the vein of Flash games like FF7, Secret of Mana, or Epic Battle Fantasy, I would like to actually display the weapon with the player while they're walking around, and swap it out with a different image when they change weapons.

As a simple example, if I have a bronze and gold sword, when walking around, attacking, etc. you would see the bronze or gold sword image accordingly. This is an oversimplifcation, because I'm not sticking to only recolouring based on the weapon; I may actually change the design (not 100% sure about this yet).

As such, my core question is: **how can I design this to minimize the amount of artwork I need to make for each weapon?**

It seems like I need to create standardized weapon sizes (eg. 18x36px sword), positions relative to the character to show them for each frame, and I need to create a sprite-sheet for each frame. (I have four directional images for walking, each with four frames of animation.)

This means, per weapon, I need another 4x4 frames of animation; that's a lot (for a non-artist like me). The other approach would be programmatic animation; but how will that work? I have to worry about:

* Positioning must be always similar for each weapon (different sizes?)
* Occlusion; the whole weapon appears when looking down, but most of it is hidden when looking up; how can I standardize this?

For reference, see (really) FF7; they did a fairly decent job of this, albeit in 3D.

Sample:

# Answer
> 3 votes
I'd follow the strategy used in some of the older JRPGs, in this example Secret of Mana (Seiken Densetsu 2; SNES):

Use one set of frames having an unarmed character (you might want that one for villages/peaceful scenes anyway).

Each weapon is a separate set of frames containing ONLY the weapon (and always full, not occluded or anything).

When drawn, there are essentially three layers involved:

* Behind the character
* The character itself
* In front of the character

To further reduce the number of frames, you can just mirror facing west and east. People looking close might notice the difference, but it's really just minor (if done right).

Depending on the animation frame and the character's facing, the order in which the layers are drawn can then adjust dynamically, e.g. to fake the weapon being swung past the character (or its head).

For example, Secret of Mana draws weapons behind characters when facing down (which is not always the case, see below).

Bonus feature: Having the weapon separated makes it rather easy to tint or adjust the weapons as well. In Secret of Mana this is used to show different weapon buffs, for example ice magic making the weapons freeze enemies on successful hits:

To further improve characters, adding easy animations and possibly even more customization (e.g. different hair styles), I'd even separate the head as well:

* Behind the character
* Character's body
* Character's head
* In front of the character.

Again coming back to Secret of Mana, this was used rather well to let characters perform simple emotes, e.g. while talking: Nodding, refusing, etc.

---

Doing the animation in code would essentially be the same, just with the added step of rotating/adjusting the weapon frame based on the animation step (rather than using a different frame). This will safe you drawing time and texture memory, but it might look rather odd depending on your overall art style (it works fine with HD graphics, but it will most likely fail with classic pixelated graphics unless using special shaders to ensure "proper" rendering (e.g. to avoid lines getting removed while rotating or edges being too thick, etc.)).

---

So choose either approach? You could most likely combine both: Done right, you can probably reduce the number of weapon frames to 2 or 3 per direction/animation (which might save you 25-50% for some animations) and just move the weapon's origin when drawing. Secret of Mana does this for some weapons in some animations. Although I can't give any specific examples right now (as screenshots), I'm rather sure that both the axe and javelin (and possibly other weapons) have been a perfect example for this, both consisting of only 1 or 2 frames in some animations.

# Answer
> 0 votes
### South Park style:

Rather than dedicated frames, make sprites of all desired limbs and animate the character simply by positioning these sprites. This way you can mix weapons and armour any way you like. But you will be bound to a cartoon style.

There are many variations for this technique, you may blend it with some traditional animated sprites for doing part of the animation, you can vary the number of joints in arms and legs, you can choose to stretch some of the sprites to make some more complicated animations, or to some degree simulate a rotation that is not in the viewplane.

It is by the way worth noting that a lot of 2D games have used sprites generated from 3D models, or have used partial 3D rendering where the majority of the scene is traditional 2D graphics.

---
Tags: animation, art, pipeline
---


title: Working with chunks of terrain

text:
# Question
Title: Working with chunks of terrain
Let's take for example that in our game, we divide our world (1000x1000 tiles) into chunks of 100x100 tiles. Each chunk contains its own npcs, traps, players, items, whatever. Now, there comes to my mind many problems:

* Pathfinding: what if an npc at one chunk needs to find a player/npc that is near him but not in the same chunk?
* Sight: Npc wants to check if someone is near him, what if the nearest npc/player is like the previous example at other chunk.

I'd like to find a solution where the player doesnt have to see how chunks are loaded and interaction between chunks is possible, but seems hard.

**EDIT**: what i have in mind is a multiplayer rpg (not as big as a mmo), where the map is divided into chunks. Each chunk would represent maybe a settlement, a portion of a forest, a portion of a hill, etc ... I thought about loading not just the chunk being visited by a player, but its surroundings, so transitions are easier.

I need this organization because i'll have many entities to manage. Maybe in the world map exists 100 cities, and each one contains 10 citizens. If a chunk is visited by a player, i want him to see how each citizen talk, and walk, and live. But a chunk not being visited should be handle differently. Maybe i'll do some checks when the night comes to see what happened there.

# Answer
> 5 votes
Create class to encapsulate your chunks that will behave like virtual 2D array. Each time you need X:Y tile, that class would find correct chunk and correct local position inside it. For example, if your pathfinding wants 101:206 tile, that class would find 1:2 chunk and return 1:6 tile from it.

For entities, you may need spatial partitioning structure. Update it each time chunk is loaded or unloaded.

# Answer
> 1 votes
If your first question is strictly about pathfinding, I believe you can simplify the problem by defining some preconditions.

For example: each chunk is connected to every adjacent chunk by a single door. This door is never blocked and is always walkable.

In this case to find your way anywhere you need to find two paths: one global, the sequence of doors to travel, and a lot of local ones (these can be generated when your agent enters a chunk and thrown away when it leaves it) for each chunk to travel to the next door.

If you need anything more complicated, this is a starting point. You can easily modify this idea to have multiple doors, shortcuts between chunks, blocked doors, chunk penalties, etc.

Of course there are other solutions to this problem too - small local graphs that include multiple chunks and are generated dynamically, or even pre-generating the graph for your entire world, and loading parts of it on demand. Each solution has its drawbacks, and you also need to consider which algorithm you're using. A\* using Eucledian distance for its heuristic function is always a good idea, as it will keep look-ups very close to the origin in most situations, especially if you accept sub-optimal solutions.

---
Tags: path-finding, terrain, space-partitioning
---


# Question
Title: How to remove an object from a std::vector
So I have a vector of bullets that show up on the screen and I do not want these bullets to live forever. I want them to "die as soon as they go off screen or collide with an enemy. How can I make sure they are removed from the array and no longer take up memory.

code:

```
std::vector<Bullet> bulletArray;

for(int i=0; i<bulletArray.size(); i++)
{
    bulletArray[i].MoveBullet();
    bulletArray[i].Draw();
    if(bulletArray[i].PosY<0)
    {
        //Delete object forever
    }
}

```

# Answer
There are two ways to do it:

1. You can simply remove object i from the vector using `bulletArray.erase(bulletArray.begin() + i)` and then `i--` to process everything for the new bullet in i'th position. But this way vector will move all the object after the that specific bullet, meaning this kind of removal is O(bulletArray.size()).
2. But usually order of the bullets is not important, so you can simply put the last bullet in the i'th cell, and only remove it's spot. This way it's much more faster since these operations are O(1). And it's implemented as `bulletArray[i] = bulletArray.back(); bulletArray.pop_back(); i--;` again you need to decrement i by one to check this new object in this i'th position in the next loop.
> 12 votes

# Answer
In general, I find that it's a good idea to add a flag (normally I call this "dead") to the objects.

Then you can do this (in pseudo-pythonic code):

```
// Processing
for obj in my_list:
  if obj has hit enemy:
    obj.dead = true
  if obj outside play area:
    obj.dead = true
// Rendering (at some different point)
for obj in my_list:
  render somehow

```

Then you can use the std::remove\_if higher-order function (in algorithms) to remove the ones with the "dead" flag set. Remember to use std::erase to truncate the vector to the right point.

The main advantage of using this remove\_if/erase is that it avoids problems when trying to remove elements while iterating the list.

Additionally, sometimes you may want to remove object X while processing object Y (in collision detection, such situations are normal) - we can do this easily without breaking any iterator objects.

(Note that iterator objects are normally only valid as long as no new elements are added or removed. Especially for std::vector)
> 2 votes

---
Tags: c++
---


title: Allegro 5 compiling with GCC on mac

text:
# Question
Title: Allegro 5 compiling with GCC on mac
I have the following code from a tutorial and i am trying to compile it on a mac using g++/gcc however every time it complains about the native dialog but i am referencing the library correctly i think

```
#include<allegro5/allegro.h>
#include<allegro5/allegro_native_dialog.h>

int main()
{
ALLEGRO_DISPLAY *display;

if(al_init())
    al_show_native_message_box(NULL, NULL, "Error", "Could not initialize Allegro 5", NULL, ALLEGRO_MESSAGEBOX_ERROR);

display = al_create_display(800, 600);

if(!display)
    al_show_native_messagebox(NULL, NULL, "Error", "Could not create Allegro 5 display", NULL, ALLEGRO_MESSAGEBOX_ERROR);

al_destroy_display(display);

return 0;
}

```

**The error i get is**

```
main.cpp: In function ‘int _al_mangled_main()’:
main.cpp:17: error: ‘al_show_native_messagebox’ was not declared in this scope

```

**And the command i use is**

```
g++ -o main main.cpp -lallegro -lallegro_main -lallegro_native_dialog

```

**I have also tried with**

```
g++ -o main main.cpp -lallegro -lallegro_main -lallegro_dialog

```

Any help would be great.

Thanks

# Answer
> 2 votes
Without knowing anything about your framwork:

You used `al_show_native_messagebox` and `al_show_native_message_box`. `al_show_native_message_box` was used first and does not result in an error so I guess the second one should be `al_show_native_message_box` too?

---
Tags: c++, allegro
---


# Question
Title: How make collision for terrain Modeled in 3D's max
I read couple articels about collisions and terrain but there is nothing about terrain making in 3D program I can't see boundingBox being used for terrain collision there must be something like Every Single trinangle collision tell me if i wrong and give me some tips

# Answer
> 2 votes
It depends on what kind of terrain you have. Normally, terrain is stored as a grid of height values, which eliminates the possibility of having caves, overhangs, or vertical cliffs. This terrain is usually stored as a height map, which is an image that contains the height data, instead of as a model. Collision detection on a heightmap is usually done by calculating the height (Y) at a certain position (XZ) using interpolation and comparing that to the height of an object or point.

If your terrain is just another model, you'll have to decompose it into a series of convex hulls and use a 3D collision algorithm like Minkowski subtraction or the separating-axis theorem, exactly the same way you would handle any other 3D collisions. For simpler games with only basic collision detection needs, I'm sure you can get away with raycasting, which is a relatively simple operation, to check for collisions in a given direction.

---
Tags: xna
---


# Question
Title: What is the issue with my model rendering from .obj files?
Well I can clearly tell that what rendered is close to what I wanted, but there seems to be a few problems.

The .obj files contained values like "f", "v", "vt".

Image Of Problem:

As you can see it renders very close to what it's suppose to be, but there's a few problems. I can provide more examples/code if needed. The top two are what I'm rendering, the bottom two are while it's loaded in Blender.

Example below of each:

```
v 0.025487 1.194620 0.121091
v -0.025487 1.194620 0.121091
v 0.025487 1.143731 0.118145
v -0.025487 1.143731 0.118145

vt 0.032776 0.559649
vt 0.041251 0.559656
vt 0.041210 0.563958
vt 0.035813 0.563927

f 47/1 46/2 35/3 36/4
f 51/5 50/6 39/7 40/8
f 51/5 40/8 44/9 55/10
f 45/11 33/12 41/13 53/14

```

Going by simple things in Math Vertex,Edge,Face The "v" must be corners and "f" must be the quads or the jointed triangular faces. So then each of the "f"'s must build 6 indices?

So what I did was

Firstly I wrote the size of the vertices and quads.

```
content.writeInt(vertexs.size());
content.writeInt(quads.size());

```

I wrote to a separate file all the "v" values.

```
for (Vector3f vector : vertexs)
    content.writeVector(vector);

```

So they are in order that they were loaded out of the .obj file.

Then I figured every line for the faces would be 6 indexes. So from what I found in some tutorials you're suppose to do it clockwise so for a 1 side of a quad 1,2,3 then 2,4,3. So What I did was load the first part of each "f" so let's say we had "f 11/5 12/6 13/7 14/8" I'd store the values 11,12,13, and 14. Then I'll write them out like the following:

11,12,13, 12,14,13

So basically what I have below.

```
for (Quad qv : quads)
{
    content.writeShort(qv.indices[0] - 1);
    content.writeShort(qv.indices[1] - 1);
    content.writeShort(qv.indices[2] - 1);
    content.writeShort(qv.indices[1] - 1);
    content.writeShort(qv.indices[3] - 1);
    content.writeShort(qv.indices[2] - 1);
}

```

So now I can load these into DirectX like this:

LOAD MODEL METHOD

```
CacheReader::open("model.dat"); //For now it just files no indexing yet.
CacheReader *reader = CacheReader::readFully();

vert_size = reader->readUnsignedInt();

int faces = reader->readUnsignedInt();

int index_capacity = faces * 6;
index_size = faces * 2;

CUSTOMVERTEX *verts = new CUSTOMVERTEX[vert_size];
short *indices = new short[index_capacity];

for (int i = 0; i < vert_size; ++i)
{
    verts[i].X = reader->readFloat();
    verts[i].Y = reader->readFloat();
    verts[i].Z = reader->readFloat();
    verts[i].COLOR = D3DCOLOR_XRGB(255, 255, 255);
}

int n = 0;

for (int i = 0; i < faces; ++i)
{
    indices[n++] = reader->readUnsignedShort();
    indices[n++] = reader->readUnsignedShort();
    indices[n++] = reader->readUnsignedShort();
    indices[n++] = reader->readUnsignedShort();
    indices[n++] = reader->readUnsignedShort();
    indices[n++] = reader->readUnsignedShort();
}

VOID* pVoid;

d3ddev->CreateVertexBuffer(vert_size * sizeof(CUSTOMVERTEX),
    0, CUSTOMFVF, D3DPOOL_MANAGED, &v_buffer, NULL);
v_buffer->Lock(0, 0, (void**)&pVoid, 0);
memcpy(pVoid, verts, vert_size * sizeof(CUSTOMVERTEX));
v_buffer->Unlock();

d3ddev->CreateIndexBuffer(index_capacity * sizeof(short), 0,
    D3DFMT_INDEX16, D3DPOOL_MANAGED, &i_buffer, NULL);
i_buffer->Lock(0, 0, (void**)&pVoid, 0);
memcpy(pVoid, indices, index_capacity * sizeof(short));
i_buffer->Unlock();

D3DXMATRIX matView;
D3DXMatrixLookAtLH(&matView, &D3DXVECTOR3 (0.0f, 0.0f, -5.0f),
    &D3DXVECTOR3 (0.0f, 0.0f, 0.0f), &D3DXVECTOR3 (0.0f, 1.0f, 0.0f));
d3ddev->SetTransform(D3DTS_VIEW, &matView);

D3DXMATRIX matProjection;
D3DXMatrixPerspectiveFovLH(&matProjection, D3DXToRadian(45),
    (FLOAT)SCREEN_WIDTH / (FLOAT)SCREEN_HEIGHT, 1.0f, 100.0f);
d3ddev->SetTransform(D3DTS_PROJECTION, &matProjection);

```

RENDER METHOD:

```
d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);
d3ddev->Clear(0, NULL, D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0, 0, 0), 1.0f, 0);

d3ddev->BeginScene();
d3ddev->SetFVF(CUSTOMFVF);

D3DXMATRIX matRotateY;
static float index = 0.0f; index+=0.05f;
D3DXMatrixRotationY(&matRotateY, index);
d3ddev->SetTransform(D3DTS_WORLD, &matRotateY);

d3ddev->SetStreamSource(0, v_buffer, 0, sizeof(CUSTOMVERTEX));
d3ddev->SetIndices(i_buffer);
d3ddev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, vert_size, 0, index_size);

d3ddev->EndScene();
d3ddev->Present(NULL, NULL, NULL, NULL);

```

INITALIZE METHOD

```
d3d = Direct3DCreate9(D3D_SDK_VERSION);

D3DPRESENT_PARAMETERS d3dpp;

ZeroMemory(&d3dpp, sizeof(d3dpp));
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.hDeviceWindow = hWnd;
d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
d3dpp.BackBufferWidth = SCREEN_WIDTH;
d3dpp.BackBufferHeight = SCREEN_HEIGHT;

d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
    D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &d3ddev);

d3ddev->SetRenderState(D3DRS_ZENABLE, TRUE);
d3ddev->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
d3ddev->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
d3ddev->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
d3ddev->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
d3ddev->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW);
d3ddev->SetRenderState(D3DRS_LIGHTING, FALSE);

load_model();

```

Here's what the first quad shows in the .obj file.

These are the vertex's

```
47:  v 0.104867 0.547076 -0.142017
46:  v 0.113943 0.548103 -0.144205
35:  v 0.113968 0.543585 -0.146221
36:  v 0.108210 0.542732 -0.144383

```

This is the first face.

```
f 47/1 46/2 35/3 36/4

```

# Answer
> 0 votes
Yeah, the problem this whole time was that my method of storing floats in order to speed up load time had a few minor errors with some values. Thus only a couple floats or coordinates were screwed up. I've converted it to read as ASCII code, but this is horribly slow and I'll be trying to figure out a better alternative that's still fully portable.

Thank's for all the help guys. Sorry that the issue was something so simplistic when it felt like something much more. Seem's I've spent 3 days trying to figure out an error that was merely my own fault for trying to optimize the floats, but my tests showed it worked, which led me to think it was a good system.

I'll have to start verifying every class is working from the easiest to the hardest. So I don't run into a really easy glitch again.

# Answer
> 2 votes
The issue is that indices in a `.obj` file start at 1, while when rendering, they start at 0. Pretty much everyone who writes a `.obj` parser will run into this issue at some point.

The solution is to subtract each index by 1 when loading it:

```
for (Quad qv : quads)
{
    content.writeShort(qv.indices[0] - 1);
    content.writeShort(qv.indices[1] - 1);
    content.writeShort(qv.indices[2] - 1);
    content.writeShort(qv.indices[1] - 1);
    content.writeShort(qv.indices[3] - 1);
    content.writeShort(qv.indices[2] - 1);
}

```

Additionally, the other answer is correct about index ordering, and you're going to run into another issue when you want to apply a texture. The order of the vertices (`v`) and vertex texture coordinates (`vt`) don't match up, which is why `f` defines two indices for every vertex. What you want to do is create a new vertex buffer and copy the vertices into it as the indices specify.

This is necessary because the `.obj` format does not guarantee unique sets of vertex data, so you'll run into issues if you try and sort the texture coordinates alone, because they are sometimes used with more than one vertex.

Link to obj specification

# Answer
> 0 votes
I don't know if you are triangulating your quads correctly.

```
for (Quad qv : quads)
{
    content.writeShort(qv.indices[0]);
    content.writeShort(qv.indices[1]);
    content.writeShort(qv.indices[2]);
    content.writeShort(qv.indices[1]);
    content.writeShort(qv.indices[3]);
    content.writeShort(qv.indices[2]);
}

```

Would make the triangles

```
-----|
\    |
 \   |
  \  |
   \ |
    \|

```

and

```
     /|
    / |
   /  |
  /___|

```

which dont represent the quad. You can change the second triangle to match the first one, like so:

```
for (Quad qv : quads)
{
    content.writeShort(qv.indices[0]);
    content.writeShort(qv.indices[1]);
    content.writeShort(qv.indices[2]);
    content.writeShort(qv.indices[2]);
    content.writeShort(qv.indices[3]);
    content.writeShort(qv.indices[0]);
}

```

---
Tags: c++, models, 3d-meshes, directx9, vertex
---


# Question
Title: What would be a good filter to create 'magnetic deformers' from a depth map?
In my project, I am creating a system for deforming a highly detailed mesh (clothing) so that it 'fits' a convex mesh. To do this I use depth maps of the item and the 'hull' to determine at what point in world space the deviation occurs and the extent.

Simply transforming all occluded vertices to the depths as defined by the 'hull' is fairly effective, and has good performance, but it suffers the problem of not preserving the features of the mesh and requires extensive culling to avoid false-positives.

I would like instead to generate from the depth deviation map a set of simple 'deformers' which will 'push'\* all vertices of the deformed mesh outwards (in world space). This way, all features of the mesh are preserved and there is no need to have complex heuristics to cull inappropriate vertices.

I am not sure how to go about generating this deformer set however. I am imagining something like an algorithm that attempts to match a spherical surface to each patch of contiguous deviations within a certain range, but do not know where to start doing this.

**Can anyone suggest a suitable filter or algorithm for generating deformers? Or to put it another way 'compressing' a depth map?**

(\*Push because its fitting to a convex 'bulgy' humanoid so transforms are likely to be 'spherical' from the POV of the surface.)

**Edit:** Here is an image/diagram rightly suggested that illustrates what I am trying to achieve.

Also, I should say since this question was posted I worked a lot more on this problem, and though I never solved how to the get the deformers I did eventually decide that depth maps for this were unsuitable as:

1. If the deformed mesh is not complete, it is possible to get texels in the map that are *meant* to be on the other side of the convex mesh (because they are not obscured by those closer to the camera on the correct side).
2. The efficiency was not as high as I had hoped due to the fact 6 maps were needed per deformation.

Not that these were unsolvable, but the other solution, which involved collision testing in kernels running on the GPU, resulted in higher quality results and was much simpler, even though it may not be as fast.

I still think this questions problem is interesting though and would be interested in any answers as I am sure there are situations where it would be preferred.

# Answer
You have a depth map, which I assume is simply the distance between the convex mesh A and the neutral deformed mesh B, and you have surface normals of mesh A.

What you're missing is weights (or groupings) of how each vert on mesh B affects its neighbors. For example, when the central vert gets moved it should also drag along its neighbor verts by some amount (percentage) if they are in the same group.

If you have a group of verts affect each other 100% they will all end up pushed out by the farthest amount from your depth map as if they were all part of an unbendable steel structure that moves as a unit, set at 50% this structure may act more like thick rubber sheets and 10% like form fitting plastic wrap because each vert barely affects its neighbor (which is what you have now.

Obviously there's some blending and merging of values going on. Like @Gajoo said, "what is wrong with moving the whole shape?"
> 2 votes

---
Tags: physics, depth-buffer, filtering
---


# Question
Title: How can I implement a global high score ladder?
Are there any existing frameworks I can build on? Should I build my own? How can I prevent fake scores from being posted to it?

# Answer
> 6 votes
ScoreLoop is available for Android platform.

You can use ScoreNinja too. ScoreNinja offers an easy way to implement global scores but requires to view your score in the ScoreNinja application.

Otherwise Cocos iphone provides a global score with CocosLive. You can use CocosLive.net or use your own GoogleApp Engine VM. CocosLive is not available on Android platform but the protocol is REST with JSON and can easily be ported.

My current solution is CocosLive for Android and iPhone with my own VM but i will use ScoreLoop in my next game for social network integration.

# Answer
> 5 votes
I'm not sure there is one framework that spans multiple platforms but there are platform specific frameworks for sure. Two that come to mind for the iPhone are Scoreloop and OpenFeint.

# Answer
> 2 votes
Check out **OpenFeint** : Getting Started With OpenFeint SDK for Android 1.8 Easy to start !

# Answer
> 1 votes
Do the following:

(1) User gets a score in the game.

(2) Create the string "Username,score,timestamp" or something similar.

(3) Append a salt (secret string) to this string: "username,score,timestamp,SALTSTRING"

(4) Calculate a hash of this string with your favourite algorithm, (MD5, SHA...).

(5) Post "Username,score,timestamp" together with the hash you computed to your site: www.yoursite.com?str=username,score,timestamp&hash=MYHASH or something similar

(6) On your server, redo the calculation, i.e. create "username,score,timestamp,SALTSTRING" and then compare with the hash the user submitted. If no match, then something has been tampered with.

Note, if the user can obtain the class files, then they can be decompiled, and thus the salt can be seen. However, if the user can decompile your program, there is no way to prevent false high scores: the user may modify the code to make the game easier and use that version. You will have no way to check for that.

---
Tags: java, leaderboards, android
---


# Question
Title: Splitting logic into threads in Java tower defence game
I'm making a **tower defence** game in Java!
It's my first game development.
I want to know how many threads Do I need to create in a game, to split logic..
I've made this one:

* 1. Main App thread
    (adds component thread - add(screen))

    + 1.1.1 Thread (graphic updates)
        + 1.1.2 Bullets physic
        + 1.1.3 Mobs physic
        + 1.1.4 Towers physic

Is it normal to split this logic?

# Answer
Normally, it's not that common to split up in-game logic based on entity types; this is primarily due to the fact that there needs to be interactions between different entities computed as a part of the game in most situations, and separating them into multiple threads makes synchronizing and ordering those interactions a living nightmare, as opposed to establishing a fixed sequence of events.

Say for example that a bullet needs to hit a mob; it needs to do a collision check against the current positions of the mob and the bullet. If this occurs on the mob thread, for example, the bullet's actual position could change due to a race condition, if the bullet thread took over. In the best case, this would result in bullets being *slightly* off-target; in the worst case, this could result in catastrophic memory shenanigans, if an object is intended to be released or destroyed, or a property is set to null or something.

If I were you, I'd make sure you keep interactions on one thread, and feed the results of the collision checking into the rendering thread. If you must break up processing by entity type, have a loop across all bullets, then all mobs, then all towers (or something along those lines) within each processing step; otherwise, make them all a common Entity interface, and just let subclass implementations update their own physics in order of iteration. There are a number of other paradigms that could be used for this, but I've seen this used fairly frequently.
> 7 votes

---
Tags: java, physics, animation, multithreading
---


# Question
Title: How to handle collision resolution in a top-down car game?
I have a top-down car game which takes place in an arena. The game is very very light on physics, so I'm not actually using a physics engine. The cars' movement is mostly managed by a struct I called `Velocity`, which stores a movement vector, an angle and speed. The speed will be mostly at the car's top speed, but there's acceleration involved to make reversing and going forwards again a bit smoother; the angle is increased or decreased depending on player input for turning; and then, the movement vector is updated with the new speed and angle values.

For collision detection, I've opted for SAT and as far as detection goes, it's working well. When it comes to resolution, however, I'm a bit at a loss. Out of the SAT implementation, I can get the MTV, but I feel it doesn't quite work with cars. I was thinking something in terms of maybe using the overlap value of the MTV (to acknowledge how strong was the hit) and the cars' movement vectors to define what's gonna happen to them, but I'm not coming up with anything.

(For completeness' sake, I'm using C++, Marmalade and IwGame, but I think the solution to this problem would be pretty much platform independent.)

Any ideas? Thanks!

# Answer
So, after a few trips to the Physics section of Khan Academy for a refresher on momentum and some more research, I've found this series of articles on the matter:

(These articles originally have a linearity to them, and there's more articles in between those listed above in the series, but those that I listed are the ones that relate to the problem at hand.)

The solution above deals with the scenario of balls colliding, so it isn't exactly perfect for cars, but I've found a decent way around that: I store the resulting velocity from the collision in a different vector than the velocity vector from the car. Then, the car will follow the direction of the of both the collision vector and the velocity vector. Just so there's some actual change to the velocity vector after the collision, I use the projection of the collision vector onto the velocity vector as the resulting velocity of the car.

Here's the bulk of the resulting code:

```
// Get the normal vector from lhs->rhs
CIwFVec2 normalAB = other->getPosition() - this->getPosition();
normalAB.Normalise();

// Rotate 90° to get the tangential
CIwFVec2 tangenAB = CVector2Util::getLeftNormal(normalAB);

// The vectors in the normal and tangential direction will act as axes

// Calculate the initial velocity in N (normalAB)
float lhsIniVelN = this->movementModule.getVelocityVector().Dot(normalAB);
float rhsIniVelN =  rhs->movementModule.getVelocityVector().Dot(normalAB);

// Calculate the initial velocity in T, which will also
// be the final velocity in T
float lhsVelT = this->movementModule.getVelocityVector().Dot(tangenAB);
float rhsVelT =  rhs->movementModule.getVelocityVector().Dot(tangenAB);

// Get the masses
float mLhs = TEMP_ARBITRARY_MASS;
float mRhs = TEMP_ARBITRARY_MASS;

// Get the final velocities in N
float lhsFinVelN = (mRhs * rhsIniVelN * (C_E + 1) + lhsIniVelN * (mLhs - C_E * mRhs)) / (mLhs + mRhs);
float rhsFinVelN = (mLhs * lhsIniVelN * (C_E + 1) + lhsIniVelN * (mLhs - C_E * mRhs)) / (mLhs + mRhs);

// Finally, translate the final velocities in N-T to X-Y
CIwFVec2 lhsFinalVel;
CIwFVec2 rhsFinalVel;

// This can be done with the dot product of the final velocities
// in N and T with normalAB and tangenAB, respectively
lhsFinalVel.x = lhsFinVelN * normalAB.x + lhsVelT * tangenAB.x;
lhsFinalVel.y = lhsFinVelN * normalAB.y + lhsVelT * tangenAB.y;
rhsFinalVel.x = rhsFinVelN * normalAB.x + rhsVelT * tangenAB.x;
rhsFinalVel.y = rhsFinVelN * normalAB.y + rhsVelT * tangenAB.y;

// Pass the final velocities to the movement module
this->movementModule.resolveCollision(lhsFinalVel);
rhs->movementModule.resolveCollision(rhsFinalVel);

```
> 3 votes

---
Tags: c++, collision-resolution, car
---


# Question
Title: Besides OpenGL and DirectX, what other libraries can aid in 3-D graphics?
And how does DX and OpenGL "make 3D exist"? I want to know how I can write a 3-D a library to render a 3-D world witg models. But any help? Thanks. Also, my main question.

# Answer
> 2 votes
OpenGL and Direct3D are what you can call low-level graphics libraries. They provide a very thin layer over manually sending data to the GPU, and are the basis of almost all other 3D graphics libraries.

Libraries that make use of OpenGL and Direct3D are more commonly considered to be "rendering engines", as they abstract away much of the code that interfaces with the GPU. Some notable examples of these rendering engines are:

* Ogre3D \- solely a rendering engine out of the box, but provides a framework to easily add in sound, physics, or whatever other features you need
* Irrlicht \- again, this is pretty much just a rendering engine, but it also has collision detection (no physics, though)
* jMonkeyEngine \- Java game engine with a large focus on rendering; provides physics and networking on the side

There are countless others, but these are some of the most widely-used. They are more high-level, and are more suited to faster and simplified development rather than total control and performance. They are good enough for indie games if you don't want to spend a lot of time on writing your own rendering back-end.

If you value being able to do whatever you want with your engine without needing to work around the limitations of high-level frameworks, low-level APIs like OpenGL and Direct3D are for you.

---
Tags: 3d
---


# Question
Title: Does SFML render it's graphics using OpenGL internally?
By that, I mean that SFML has an abstraction for OpenGL? Sort of like SDL's blit functions, but using OpenGL internally?

"Yes SFML uses OpenGL for all the graphical stuff. "

Received this comment in an earlier question, which sort of baffled me since I find nothing about it.

# Answer
Yes, it does use OpenGL for some operations. You can get the full list from the source code. The major uses are, as of SFML 1.6:

* `RenderTarget.cpp`: set up render targets, clear screen, set matrix mode *etc*.
* `PostFX.cpp`: postprocess manager
* `Image.cpp` and `Sprite.cpp`: texture and sprite handling
* `String.cpp`: text writing

In the upcoming SFML 2.0, some of this is slightly modified because of the support for the fully programmable pipeline. For instance, `Sprite.cpp` no longer uses OpenGL directly, and instead fills vertex buffers for rendering by `RenderTarget.cpp` instead.

It is possible to use SFML without the application having knowledge of OpenGL, but its features will be pretty limited (basic sprite and text rendering, some post-process effects). The more common use case is to use SFML to create a GL context.
> 6 votes

---
Tags: c++, opengl, sdl, windows, sfml
---


# Question
Title: How can I get started in game development, and what language is best for beginners?
I'm very interested in game development, and I'd like to start on some basics. Sorry if this is a poor question, this is my first time on StackExchange.

# Answer
I'd say c++ with SDL is a good place to start.

SDL is a library that helps you manage input with keyboard, mouse, draws you the window you need for the game, and handles alot of the little details you don't need/want to know as a beginner, abstracting all that to give you a quick and simple framework to work on for a beginner.

Get SDL here: http://www.libsdl.org/ Use Code::Blocks or some other IDE. I like CB myself.
> 1 votes

---
Tags: game-industry
---


title: Forcing early-z with raytracing

text:
# Question
Title: Forcing early-z with raytracing
I'm working on a GLSL raytracer, and I need to be able to edit gl\_FragDepth in the FS. However, doing so disables early-z culling. The scene is rendered front-to-back and the FS can only push points further away, so the results of the z-test shouldn't affect the final render, even with a long pipeline.

Is there anyway to force early-z culling to run, or otherwise get around the "no fragdepth" restriction? I suppose I could do a z-test in the FS, but I'd rather let the hardware take care of it if possible.

# Answer
I think what you're looking for is called "Conservative Depth". There is an AMD OpenGL extension at least: GL\_AMD\_conservative\_depth But there is also a DX11 semantic which I have used in the past and works on both vendors, although it is poorly documented. It's described here on slide 81.

As for OpenGL on NVIDIA, I'm not sure. There is GL\_ARB\_depth\_clamp, but I don't think that will help with your situation.

EDIT: Oops, looks like AMD\_conservative\_depth has become ARB\_conservative\_depth since I last looked. So you should be good to go for most cards.
> 4 votes

---
Tags: glsl, depth-buffer, culling, raytracing
---