# Question
Title: Scrolling 2D sprites on a map with a camera
I'm working on a 2D sprite-based strategy-type game (ok, full disclosure: it's a tower defense game), and I'm having a problem getting the actors to behave correctly when I move the camera.

I've got a `Camera` class, which contains data and methods for moving the camera and exposing its' current position. When I draw the background, I offset the background thusly (and it works great):

```
var backPos = new Vector2(background_bounds.X - camera.CameraPositionX,
                          background_bounds.Y - camera.CameraPositionY);
spriteBatch.Draw(background_texture, backPos, Color.White);

```

My sprites each have a `GraphicsComponent` that directs the rendering. I've been playing around with different combinations, but none seems to give the proper (expected behavior); I lose collision detection (done via my `CollisionComponent` object), or the physics misbehave, etc, because actor's position is different than what the other components expected. Here's the `GraphicsComponent.Draw(...Camera camera)`:

```
 //...snip
 var adjustedPosition = new Vector2(actor.Position.X - drawOffsetX,
                                    actor.Position.Y - drawOffsetY);
 //Uncommenting this line doesn't work either - just makes things seem worse
 //actor.Position = adjustedPosition;
 DrawContext.Draw(actor.Texture, adjustedPosition,
                  actor.SpriteBounds, DrawColor);

```

How do you folks approach applying camera offsets to sprites in a way that avoids exposing the camera to every component? Do you offset the *actual* position by the camera's position, or do you simply render the position with the offset, and compensate elsewhere?

# Answer
> 2 votes
I just offset the drawing position like you've done there. Logically speaking, the actor's positions aren't changing just because the camera is changing. Positions should be relative to the map, the camera shouldn't come into play with the actual positions.

As to your question about exposing the camera to every element, I tend to set things up a little differently. I have a class that is in charge of graphics. This class contains the camera class, or at least a reference to it, as well as a draw method. Sprites are then drawn by this method, which offsets the position automatically, so you don't have to think about the camera at all while rendering. Sure, it necessitates an extra function call per draw, but since this is a linear time algorithm, unless your bottleneck is in drawing tons and tons of sprites, you shouldn't have an issue with this.

# Answer
> 0 votes
I know this is an old post, but for future reference, you *should not* implement a camera like this, i.e.a by offsetting all the objects in the world manually. That makes your life much harder than it has to be. That remains true for both 2D and 3D games.

Implementing a camera should be done using a view matrix instead. You simply calculate a view matrix based on the camera's position and orientation in the world, and pass that matrix as a parameter to SpriteBatch.Begin. XNA automatically applies that transformation to everything it draws, which gives the impression you're "watching the scene" from the camera's point of view.

Here's a writeup I did on the subject with a few extra catches:

http://www.david-gouveia.com/2d-camera-with-parallax-scrolling-in-xna/

---
Tags: 2d, xna, sprites, camera
---


title: How to rotate "stacked sprites" in XNA?

text:
# Question
Title: How to rotate "stacked sprites" in XNA?
I'm working on a simple Sinistar-style shooter in XNA, and I'm constantly running into trouble with transformations. I feel like I'll get it eventually, but this problem is really bending my mind.

My little ship has two states: idle and engines-firing. Idle is a single frame, and engines is a few frames that animate. Got all that. Part 1 of the issue: Instead of using rotated images, I just use XNA's rotation to orient the ship. Seems to work ok, but I think my origin point is off because it seems to rotate at a point just below the vertical axis of the ship (default orientation is ship's nose pointing up), instead of in the dead center of the ship. Likewise, when I switch to engines, the sprites are different heights (due to the flames) so the origin of rotation doesn't seem like it would be constant. Do I need to specify all my frames the same size so as to preserve the origin point?

Second bit: The gun turret sits on top of the ship, as a separate sprite. With a bit of trial-and-error and calculation, I can get the gun to align on top where I want it. But then when the ship rotates, it rotates out from under the gun! Would fixing the first problem adequately cover this one, or is there some trick to getting the gun's position to translate properly?

So:

1. Do I need to have all my sprite's frame-rectangles be the same dimensions?
2. Is there a standard technique in XNA for stacking multiple sprites so they act as one unit, including for rotations?

# Answer
What you want to do is get the center coordinate for you ship sprite and turn it on that point. I don't have the code with my here at work, but when I get home I'll share a little snippet that I made that does just want you want.

For this to work however your sprite has to be well centered in the first place. Your image needs to be very aligned and centered using Photoshop or whatever program you use. If your image is not aligned correctly then using the established techniques to rotate won't work because your picture center won't be the same as your pictureContent center.

**Edit**

Ok, I got back from work and here's a little example. I'm going to rotate a cannon barrel on a given point using the following code:

```
//Angle is just a float variable that saves the angle the cannon is facing.
players[currentPlayer].Angle -= 0.1f;

```

The code above is only run when the left key is pressed. I'm moving the angle to the left or counter-clockwise.

Now in the Draw method which in XNA is called 60 times every second I redraw the cannon. Using the .Angle property I modified earlier I know exactly where to draw it and at what angle.

```
spriteBatch.Draw(CannonBody, player.Position, null, player.Color, 0, new Vector2(0, CannonBody.Height), playerScaling, SpriteEffects.None, 0);
spriteBatch.Draw(CannonBarrel, new Vector2(xPosition + 20, yPosition - 10), null, player.Color, player.Angle, cannonOrigin, playerScaling, SpriteEffects.None, 1);

```

Basically, you want to draw the cannon using modified positions every given second; then each second modify the position so you get that fluid movement effect.
> 3 votes

# Answer
Old topic but I'd like to talk a bit about the subject. About grouping sprites together there are two nice ways to handle that, depending on whether you want all the sprites to be siblings (i.e. grouped but on the same level) or if you want to have an hierarchy (i.e. sprites inside other sprites, where transforming the parent also transforms the children). Here's the general idea for each of them.

**Scenario 1) All the sprites in the group are siblings:**

Let's say you have a Sprite class and a Group class with this interface (pseudocode)...

```
Sprite: Position, Rotation, Scale, Origin, Draw()
Group: Sprites, Move(displacement), Rotate(angle, origin), Scale(amount, origin)

```

Each Sprite object will hold its Position/Rotation/Scale/Origin in world space and when calling Draw those values are fed to a SpriteBatch instance and drawn.

As for the Group class, it keeps a list of all the Sprites in the group and provides methods to manipulate the group as a whole. Those methods take an origin parameter which is the "center" of the group (e.g. around which point do you want it to rotate). The implementation goes something like:

```
Move(displacement): For every sprite, Add displacement to Position
Rotate(angle, origin): For every Sprite, Add angle to Rotation & apply Matrix to Position
Scale(amount, origin): For every sprite, Add amount to Scale & apply Matrix to Position

```

Where that Matrix is calculated with the origin of the transformation taken into account, i.e.:

```
Matrix = CreateTranslation(-origin) *
         CreateRotation(angle) OR CreateScale(amount) *
         CreateTranslation(origin)

```

What this does is basically move the Sprite temporarily into a new space where the origin is at (0,0), then it applies the transformation, and reverts the original displacement back to normal. So as long as you manipulate the Sprites through the Group interface, they'll be bound together.

Note: To apply the matrix to Position you use the Vector2.Transform() method of XNA.

**Scenario 2) Sprite hierarchy**

On the other hand if you can have sprites inside each other, the strategy is different. Basically you need to create a hierarchy of Parent and Children sprites, and each sprite will keep a transformation matrix that is not defined in World Space but rather in relation to its parent.

So you can create something like:

```
class Sprite {
    List<Sprite> children;
    Matrix localTransform;
    void Draw(Matrix parentTransform);
}

```

And when drawing the sprite you need to get the global transform by multiplying the current sprite's transform by its parents' (which I'm passing as a parameter), then decompose that transform into values that SpriteBatch can understand, and finally draw the children. Something like (not 100% accurate, just to give an idea):

```
void Draw(Matrix parentTransform)
{
    // Get actual matrix
    Matrix globalTransform = localTransform * parentTransform;

    // Translate into values
    Vector2 position; float rotation; float scale;
    DecomposeMatrix(globalTransform, out position, out rotation, out scale);

    // Draw sprite
    SpriteBatch.Draw(texture, position, rotation, scale);

    // Draw children
    foreach(Sprite child in children) children.draw(globalTransform);
}

```

And here's my implementation of DecomposeMatrix (the one I use on my project):

```
    private static void DecomposeMatrix(ref Matrix matrix, out Vector2 position, out float rotation, out Vector2 scale)
    {
        Vector3 position3, scale3;
        Quaternion rotationQ;
        matrix.Decompose(out scale3, out rotationQ, out position3);
        Vector2 direction = Vector2.Transform(Vector2.UnitX, rotationQ);
        rotation = (float) Math.Atan2(direction.Y, direction.X);
        position = new Vector2(position3.X, position3.Y);
        scale = new Vector2(scale3.X, scale3.Y);
    }

```

Using this strategy you could have the turret be a child of the tank, and whenever you rotated and moved the tank, the turret would follow automatically.
> 6 votes

---
Tags: 2d, xna, sprites
---


# Question
Title: Recommended method for XML level loading in XNA
I want to use Blender as my level designer tool for an XNA game. Using an existing plugin, I can export my levels to DotScene format which is basically an xml file like this one:

```
<scene formatVersion="1.0.0">
  <nodes>
    <node name="scene-staircase.001">
      <position x="10.500000" y="1.400000" z="-9.600000"/>
      <quaternion x="0.000000" y="0.000000" z="-0.000000" w="1.000000"/>
      <scale x="1.000000" y="1.000000" z="1.000000"/>
      <entity name="scene-staircase.001" meshFile="staircase.mesh"/>
    </node>

    <node name="Lamp.003">
      <position x="11.024290" y="5.903862" z="9.658987"/>
      <quaternion x="-0.284166" y="0.726942" z="0.342034" w="0.523275"/>
      <scale x="1.000000" y="1.000000" z="1.000000"/>
      <light name="Spot.003" type="point">
        <colourDiffuse r="0.400000" g="0.154618" b="0.145180"/>
        <colourSpecular r="0.400000" g="0.154618" b="0.145180"/>
        <lightAttenuation range="5000.0" constant="1.000000" linear="0.033333" quadratic="0.000000"/>
      </light>
    </node>

    ...

  </nodes>
</scene>

```

Using naming conventions I could easily parse the file and load the correspondent in game content. I am new to XNA and I have seen that there are several methods to load XML files into a game like serializing and deserializing. Which one would you recommend?

# Answer
> 1 votes
I would actually recommend using the newer XDocument class instead of XmlDocument. Check:

https://stackoverflow.com/questions/1542073/xdocument-or-xmldocument

According to that thread it's also compatible with XBox and WP7, but I haven't tried since I'm currently developing for Windows.

# Answer
> 3 votes
I realized I can add my XML files as resources to the Content Manager specifying I don't want any binary conversion to take place and I want the files to get copied. Then, I can load the XML files as in a normal C# program:

```
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Content.RootDirectory + "\\XML\\file.xml");

```

---
Tags: xna, c#, blender, xml
---


title: How to draw a sprite in 3D

text:
# Question
Title: How to draw a sprite in 3D
Until now, I've always used sprites to draw in 2D:

```
spriteBatch.Draw(myTexture, rectangle, color);

```

(I suppose the texture is bound internally to 2 triangles and then scaled.)

Now, I'm porting my game to 3D and I have to draw several planes (walls, floor, roof,..). Do I need to manually bind a texture to a geometry (for example using `VertexPositionColorTexture` with `VertexBuffer` and `IndexBuffer`), or is there any simpler way to do that?

I'm looking for something like `spriteBatch.Draw` with the rectangle clip specified in 3D space:

```
spriteBatch.Draw(myTexture, rectangleIn3D, color);

```

# Answer
As a complement to Andrew's link, here's a more recent post Shawn wrote on this:

Link

But I don't recommend it either. That technique might be neat to create billboards and impostors, or placing text within a 3D world. But not to generate the floors and walls of an entire level.

If you're thinking about taking your 2D level data and procedurally generating a 3D level, I think you'd be better off writing an algorithm to generate all of the geometry from it (i.e. create and fill vertex index buffers, etc.).
> 2 votes

# Answer
Model and texturize your scenario with a 3d modeler like blender or 3ds max, export it to fbx, and load it as a 3d model in xna.
> 2 votes

---
Tags: xna, c#, 3d, sprites
---


# Question
Title: What is a good way to store tilemap data?
I'm developing a 2D platformer with some uni friends. We've based it upon the XNA Platformer Starter Kit which uses .txt files to store the tile map. While this is simple it does not give us enough control and flexibility with level design. Some examples: for multiple layers of content multiple files are required, each object is fixed onto the grid, doesn't allow for rotation of objects, limited number of characters etc. So I'm doing some research into how to store the level data and map file.

This concerns only the file system storage of the tile maps, not the data structure to be used by the game while it is running. The tile map is loaded into a 2D array, so this question is about which source to fill the array from.

Reasoning for DB: From my perspective I see less redundancy of data using a database to store the tile data. Tiles in the same x,y position with the same characteristics can be reused from level to level. It seems like it would simple enough to write a method to retrieve all the tiles that are used in a particular level from the database.

Reasoning for JSON/XML: Visually editable files, changes can be tracked via SVN a lot easier. But there is repeated content.

Do either have any drawbacks (load times, access times, memory etc) compared to the other? And what is commonly used in the industry?

Currently the file looks like this:

```
....................
....................
....................
....................
....................
....................
....................
.........GGG........
.........###........
....................
....GGG.......GGG...
....###.......###...
....................
.1................X.
####################

```

1 - Player start point, X - Level Exit, . - Empty space, # - Platform, G - Gem

# Answer
So reading through your updated question, it seems you're most concerned about "redundant data" on disk, with some secondary concerns about load times and what the industry uses.

First off, why are you worried about redundant data? Even for a bloated format like XML, it would be pretty trivial to implement compression and get the size of your levels down. You're more likely to take up space with textures or sounds than your level data.

Second, a binary format is more than likely going to load faster than a text-based one that you have to parse. Doubly so if you can just drop it in memory and have your data structures just there. However, there are some downsides to that. For one, binary files are next to impossible to debug (especially for content creation people). You can't diff or version them. But they will be smaller, and load faster.

What some engines do (and what I consider an ideal situation) is implement two loading paths. For development, you use a text-based format of some kind. It really doesn't matter which specific format you use, as long as you use a library that's solid. For release, you switch to loading a binary (smaller, faster loading, possibly stripped of debug entities) version. Your tools to edit the levels spit out both. It's a lot more work than just one file format, but you can kind of get the best of both worlds.

All that being said, I think you're jumping the gun a bit.

Step one to these problems is always describe the problem you're running in to thoroughly. If you know what data you need, then you know what data you need to store. From there it's a testable optimization question.

If you have a use case to test against, then you can test a few different methods of storing/loading data to measure for whatever you consider to be important (loading time, memory usage, disk size, etc.). Without knowing any of that, it's hard to be more specific.
> 14 votes

# Answer
* XML: Easy to edit by hand but once you start loading a lot of data, it slows down.
* SQLite: This may be better if you want to retrieve lots of data at once or even just small chunks. However, unless you're using this elsewhere in your game, I think it's overkill for your maps (and probably overcomplicated).

My recommendation is to use a custom binary file format. With my game, I just have a `SaveMap` method which goes through and saves each field using a `BinaryWriter`. This also allows you to choose to compress it if you want and gives you more control over file size. i.e. Save a `short` instead of an `int` if you know it's not going to be larger than 32767. In a large loop, saving something as a `short` instead of an `int` can mean a lot smaller file size.

Also, if you go this route, I recommend your first variable in the file be a version number.

Consider for example, a map class (very simplified):

```
class Map {
    private const short MapVersion = 1;
    public string Name { get; set; }

    public void SaveMap(string filename) {
        //set up binary writer
        bw.Write(MapVersion);
        bw.Write(Name);
        //close/dispose binary writer
    }
    public void LoadMap(string filename) {
        //set up binary reader
        short mapVersion = br.ReadInt16();
        Name = br.ReadString();
        //close/dispose binary reader
    }
}

```

Now, let's say you wanted to add a new property to your map, say a `List` of `Platform` objects. I picked this because it's a little bit more involved.

First of all, you increment the `MapVersion` and add the `List`:

```
private const short MapVersion = 2;
public string Name { get; set; }
public List<Platform> Platforms { get; set; }

```

Then, update the save method:

```
public void SaveMap(string filename) {
    //set up binary writer
    bw.Write(MapVersion);
    bw.Write(Name);
    //Save the count for loading later
    bw.Write(Platforms.Count);
    foreach(Platform plat in Platforms) {
        //For simplicities sake, I assume Platform has it's own
        // method to write itself to a file.
        plat.Write(bw);
    }
    //close/dispose binary writer
}

```

Then, and this is where you really see the benefit, update the load method:

```
public void LoadMap(string filename) {
    //set up binary reader
    short mapVersion = br.ReadInt16();
    Name = br.ReadString();
    //Create our platforms list
    Platforms = new List<Platform>();
    if (mapVersion >= 2) {
        //Version is OK, let's load the Platforms
        int mapCount = br.ReadInt32();
        for (int i = 0; i < mapCount; i++) {
            //Again, I'm going to assume platform has a static Read
            //  method that returns a Platform object
            Platforms.Add(Platform.Read(br));
        }
    } else {
        //If it's an older version, give it a default value
        Platforms.Add(new Platform());
    }
    //close/dispose binary reader
}

```

As you can see, the `LoadMaps` method can not only load the latest version of the map, but also older versions! When it loads the older maps, you have control over the default values it uses.
> 9 votes

# Answer
**Short Story**

A neat alternative to this problem is to store your levels in a bitmap, one pixel per tile. Using RGBA this easily allows four different dimensions (layers, ids, rotation, tint, etc.) to be stored on a single image.

**Long Story**

This question reminded me of when Notch livestream'd his Ludum Dare entry a few months back, and I'd like to share in case you don't know what he did. I thought it was really interesting.

Basically, he used bitmaps to store his levels. Each pixel in the bitmap corresponded to one "tile" in the world (not really a tile in his case since it was a raycasted game but close enough). An example of one of his levels:

So if you use RGBA (8-bit per channel), you can use use each channel as a different layer, and up to 256 types of tiles for each of them. Would that be enough? Or for instance, one of the channels could hold the rotation for the tile like you mentioned. Besides, creating a level editor to work with this format should be pretty trivial too.

And the best of all, you don't even need any custom content processor since you could just load it into XNA like any other Texture2D and read the pixels back in a loop.

IIRC he used a pure red dot on the map to signal an enemy, and depending on the value of the alpha channel for that pixel it would determine the type of the enemy (e.g. an alpha value of 255 might be a bat while 254 would be a zombie or something else).

Another idea would be to subdivide your game objects into those that are fixed in a grid, and those that can move "finely" between tiles. Keep the fixed tiles in the bitmap, and the dynamic objects in a list.

There might even be a way to multiplex even more information into those 4 channels. If someone has any idea on this, let me know. :)
> 9 votes

# Answer
You could probably get away with almost anything. Unfortunately modern computers are so fast that this presumably relatively small amount of data wouldn't really make a noticeable time difference, even if it is stored in a bloated and badly constructed data format that craves a huge amount of processing to be read.

If you want to do the "right" thing you make a binary format like Drackir suggested, but if you make another choice for some silly reason it probably won't come back and bite you (at least not performance wise).
> 3 votes

# Answer
See this question: 'Binary XML' for game data? I would also opt for JSON or YAML or even XML, but that has quite much overhead. As for SQLite, I would never use that for storing levels. A relational database is handy if you expect to store a lot of data that is related (eg has relational links/foreign keys) and if you expect to ask a large amount of different queries, storing tilemaps doesn't seem to do these kinds of things and would add needless complexity.
> 2 votes

# Answer
The fundamental problem with this question is that it conflates two concepts that have nothing to do with one another:

1. File storage paradigm
2. In-memory representation of the data

You can store your files as plain text in some arbitrary format, JSON, Lua script, XML, an arbitrary binary format, etc. And none of that will *require* that your in-memory representation of that data take on any particular form.

It is the job of your level loading code to convert the file storage paradigm into your in-memory representation. For example, you say, "I see less redundancy of data using a database to store the tile data." If you want less redundancy, that's something your level loading code should look to. That's something your in-memory representation should be able to handle.

It is *not* something your file format needs to be concerned with. And here's why: those files have to come from somewhere.

Either you are going to be writing these by hand, or you are going to be using some kind of tool that creates and edits level data. If you're hand-writing them, then the most important thing you need is a format that is easy to read and modify. Data redundancy is not something your format even needs to consider, because you will be spending most of *your* time editing the files. Do you want to actually have to manually use whatever mechanisms you come up with to provide data redundancy? Wouldn't it be a better use of your time to just have your level loader handle it?

If you have a tool that creates them, then the actual format only matters (at best) for readability's sake. You can put *anything* in these files. If you want to omit redundant data in the file, just design a format that can do so, and make your tool use that ability correctly. Your tilemap format can include RLE (run-length encoding) compression, duplication compression, what ever compression techniques you want, because it's *your* tilemap format.

Problem solved.

Relational Databases (RDB) exist to solve the problem of performing complex searches over large datasets that contain many fields of data. The only kind of search you ever do in a tile map is "get tile at position X, Y". Any array can handle that. Using a relational database to store and maintain tilemap data would be *extreme* overkill, and not really worth anything.

Even if you build some compression into your in-memory representation, you'll still be able to beat RDBs easily in terms of performance and memory footprint. Yes, you will have to actually implement that compression. But if the in-memory data size is such a concern that you would consider an RDB, then you probably want to actually implement specific kinds of compression. You'll be faster than an RDB and lower in memory at the same time.
> 2 votes

# Answer
* XML: really simple to use, but overhead becomes annoying when structure gets deep.
* SQLite: more convenient for larger structures.

For really simple data, I'd probably just go the XML route, if you're already familiar with XML loading and parsing.
> 1 votes

---
Tags: xna, c#, xml
---


title: Designing a unit combat system (java)

text:
# Question
Title: Designing a unit combat system (java)
I am looking to make a program that will allow me to test units for balance when in combat. The idea is that there will be two teams of so many units of different types. I would loop through a battle system that would pick units, have them attack, etc, and then see which team won and do this many many times for an average.

The thing I am having issues with is how to design or make the classes for the units. I tried making a class for a generic unit and then classes that pulled from it for each different unit. The issue was when I called a unit from a team, tried to add one etc. I need to know what the unit type was, that was I couldn't write one function that understood all the unit classes.

I am looking to make a system for the units that allows me to have each unit have the same basic stats, health, speed, etc. But that each unit will also have their own functions for abilities that would be different then other units. It would also allow me to make a method where I can say get a unit from an arraylist and call its get speed method and it wouldn't demand I know the unit class. For instance, grunt g = new grunt() instead something where I can get the unit and just call, unit.getspeed();

Any help or ideas for how I can do this, please ask for more information if needed.

# Answer
> 3 votes
Your units need to inherit from a single parent class.

```
class grunt extends unit

```

Then you can just do something like

```
unit u = grunt()

```

and call e.g.

```
u.getspeed()

```

Then, you can test with

```
if(grunt.class == u.class)

```

if u is a grunt, and then cast it to

```
((grunt)u).pokeStuffWithPointyStick();

```

to call functions specific to the grunt class.

So, you have a variable of the parent class and just put in a child class. This variable can use all functions of the parent class and can be casted to specific classes to use specific functions of specific classes.

# Answer
> 2 votes
maybe something like this:

```
import java.util.*;
abstract class Unit {
    Unit() {
        this(10, 1);
    }
    Unit(int health, int firepower) {
        this.health = health;
        this.firepower = firepower;
    }
    boolean isAlive() {
        return health > 0;
    }
    void fireAt(Unit unit) {
        unit.health -= firepower;
    }
    public String toString() {
        return "" + health;
    }
    int health;
    int firepower;
}
class Grunt extends Unit {}
class Marksman extends Unit {
    Marksman() {
        super(10, 2);
    }
}
class Team {
    boolean fire(Team other) {
        for (Unit unit : units) {
            if (unit.isAlive()) {
                boolean foundAliveOpponent=false;
                for (Unit opponent : other.units)
                    if (opponent.isAlive()) {
                        unit.fireAt(opponent);
                        foundAliveOpponent=true;
                        break;
                    }
                if(!foundAliveOpponent)
                    return true;
            }
        }
        return false;
    }
    public String toString() {
        String s = "";
        for (Unit unit : units)
            s += unit.health + " ";
        return s;
    }
    Set<Unit> units = new HashSet();
}
public class Main {
    public static void main(String[] args) {
        Team red = new Team();
        red.units.add(new Grunt());
        red.units.add(new Grunt());
        Team blue = new Team();
        blue.units.add(new Marksman());
        blue.units.add(new Grunt());
        while (true) {
            System.out.println("blue attacks");
            if (blue.fire(red)) {
                System.out.println(red);
                System.out.println("blue wins");
                break;
            }
            System.out.println(red);
            System.out.println("red attacks");
            if (red.fire(blue)) {
                System.out.println(blue);
                System.out.println("red wins");
                break;
            }
            System.out.println(blue);
        }
    }
}

```

---
Tags: game-design, java
---


# Question
Title: Bounding box of a rotated rectangle (2d)
I can see this has been asked before in various ways. I am struggling to work it out though hence asking again.

2d sprite that moves and rotates. I'm looking to contain it in a bounding box as it appears that is the most efficient way to do collision detection.

I had no problems getting it to work without rotation but that is simple! Now the sprite rotates I can't seem to find the right way of writing the code.

To create a bounding box for the sprite, my understanding is I need to work out the 4 corners of the sprite after rotation and use these to work out the width + height of the correctly sized bounding box.

I've used the article here - http://msdn.microsoft.com/en-us/library/dd162943(v=vs.85).aspx \- specifically the formula:

```
x' = (x * cos A) - (y * sin A)
y' = (x * sin A) + (y * cos A)

```

The code I'm currently using:

```
x1 = (positionX * Math.cos(rotation)) - (positionY * Math.sin(rotation));
y1 = (positionX * Math.sin(rotation)) + (positionY * Math.cos(rotation));

x2 = (positionX+width/2 * Math.cos(rotation)) - (positionY+height/2 * Math.sin(rotation));
y2 = (positionX+width/2 * Math.sin(rotation)) + (positionY+height/2 * Math.cos(rotation));

```

positionX and positionY is the current top left hand corner position of the sprite.

rotation is the radians the sprite has been rotated by (and rotation is from the centre).

width and height are of the sprite.

I thought the code above would give me the co-ordinates of the top left and top right corners of the rectangle, rotated appropriately. However, on my canvas, I'm drawing a line from x1,y1 to x2,y2 and it doesn't follow the sprite at all!

Any suggestions? Sorry for the long post!

Cheers!

# Answer
> 3 votes
I always try to solve these geometrical problems using transformations instead of trigonometry, because at least for me it's easier to visualize. Here's how I do it on my application in XNA.

Let's say I have a sprite that's been translated, rotated and scaled arbitrarily and I want to fit an AABB to it. I only need to know two things about this sprite:

* The world matrix containing all three transformations combined
* The sprite's *untransformed* extents (i.e. it's *original* width and height)

(BTW, these two bits of information combined are also all you need in order to represent an OBB)

Knowing that, I proceed to calculate an AABB like this:

```
// Calculate the position of the four corners in world space by applying
// The world matrix to the four corners in object space (0, 0, width, height)
Vector2 tl = Vector2.Transform(Vector2.Zero, matrix);
Vector2 tr = Vector2.Transform(new Vector2(extents.x, 0), matrix);
Vector2 bl = Vector2.Transform(new Vector2(0, extents.y), matrix);
Vector2 br = Vector2.Transform(extents, matrix);

// Find the minimum and maximum "corners" based on the ones above
float minX = Min(tl.X, Min(tr.X, Min(bl.X, br.X)));
float maxX = Max(tl.X, Max(tr.X, Max(bl.X, br.X)));
float minY = Min(tl.Y, Min(tr.Y, Min(bl.Y, br.Y)));
float maxY = Max(tl.Y, Max(tr.Y, Max(bl.Y, br.Y)));
Vector2 min = new Vector2(minX, minY);
Vector2 max = new Vector2(maxX, maxY);

// And create the AABB
RectangleF aabb = new RectangleF(min, max - min);

```

Maybe it's longer but at least I understand every step of the process this way.

# Answer
> 1 votes
You have a parentheses issue. Use `((positionX+width/2) * Math.cos(rotation))` instead of `(positionX+width/2 * Math.cos(rotation))`, and repeat everywhere for `X` and `Y`.

(**Edit**: removed off-topic part after clarification from author)

# Answer
> 0 votes
I have come across a similar problem in a game I'm developing. The code below should work for any matrix. Basically it takes the top left and bottom right points, transforms them and then calculates which point is the new top left, new width, new height and stores it into a Rectangle. This is for C# XNA. Probably not the fastest method, but it works for all matrix transformations.

```
    private Rectangle transformRectUsing(Rectangle tileBounds, Matrix m)
    {
        Vector2 x = new Vector2(tileBounds.Left, tileBounds.Top); x = Vector2.Transform(x, m);
        Vector2 y = new Vector2(tileBounds.Right, tileBounds.Bottom); y = Vector2.Transform(y, m);
        Vector2 newTopLeft;
        if (x.X < y.X)
            newTopLeft.X = x.X;
        else
            newTopLeft.X = y.X;
        if (x.Y < y.Y)
            newTopLeft.Y = x.Y;
        else
            newTopLeft.Y = y.Y;

        Rectangle result = new Rectangle(Convert.ToInt32(newTopLeft.X), Convert.ToInt32(newTopLeft.Y), Convert.ToInt32(Math.Abs(x.X - y.X)), Convert.ToInt32(Math.Abs(x.Y - y.Y)));
        return result;
    }

```

---
Tags: collision-detection, sprites, rotation, bounding-boxes, aabb
---


# Question
Title: Java enum pairs / "subenum" or what exactly?
I have an RPG-style Item class and I stored the type of the item in enum (itemType.sword). I want to store subtype too (itemSubtype.long), but I want to express the relation between two data type (sword can be long, short etc. but shield can't be long or short, only round, tower etc). I know this is wrong source code but similar what I want:

```
enum type
{
    sword;
}

//not valid code!
enum swordSubtype extends type.sword
{
    short,
    long
}

```

**Question:** How can I define this connection between two data type (or more exactly: two value of the data types), what is the most simple and standard way?

1. Array-like data with all valid (itemType,itemSubtype) enum pairs or (itemType,itemSubtype\[\]) so more subtype for one type, it would be the best. OK but how can I construct this simplest way?
2. Special enum with "subenum" set or second level enum or anything else if it does exists
3. 2 dimensional "canBePairs" array, itemType and itemSubtype dimensions with all type and subtype and boolean elements, "true" means itemType (first dimension) and itemSubtype (second dimension) are okay, "false" means not okay
4. Other better idea

Thank you very much!

# Answer
> 5 votes
This sounds more like you're trying to simulate a class hierarchy with enums. Just do items -\> weapons -\> swords -\> longsword/shortsword types, with appropriate virtual functions to provide the necessary functionality.

Using enums would lead to type switches all over your code, which is exactly the problem polymorphism is designed to solve.

# Answer
> 4 votes
Instead of using enums or making classes for each kind of object, I think the type object pattern is a friendly solution here. In your example, you don't really show how the enums are being used, so it's hard to show what a corresponding type object implementation would look like, but it would be something like:

```
class ItemType {
  public ItemType(ItemType parent, Integer damage) {
    this.parent = parent;
    this.damage = damage;
  }

  public int getDamage() {
    // Here a subtype can just choose to completely override the
    // damage or inherit it. A more complex system could maybe
    // add them or combine them in some other way.
    if (damage != null) return damage;

    return parent.getDamage();
  }

  private ItemType parent;
  private Integer damage;
}

class Item {
  public int getDamage() {
    return type.getDamage();
  }

  private final ItemType type;
}

ItemType swordType = new ItemType(null, 4);
ItemType shortSwordType = new ItemType(swordType, 3);
// inherits damage
ItemType longSwordType = new ItemType(swordType, null);

Item sword = new Item(swordType);

```

Cool stuff about this:

1. You only ever need to define two Java classes, `ItemType` and `Item`.
2. You can define how subtypes refine their parent types however you want: they can overide values, or stack them, or whatever. You could even support multiple inheritance of you wanted by giving `ItemType` a list of parent types.
3. Makes it *much* easier to make your item types data-driven. You just create new instances of `ItemType` with different values that you've read from some file.

In the context of games, this is one of my absolute favorite design patterns and one I wish more people knew about. Every time I see a hard-coded class named `Sword`, I cry a little on the inside.

You can see a bigger example of this here. There's no inheritance in `ItemType` in Amaranth, though, because the data format itself handles that.

**Edit: Responding to tenpn's comment below.**

The assumption with the type object pattern is that your different "types" of object will vary mostly in attributes or maybe select from a few different pre-defined behaviors. If each type of item really does behave wholly differently, then it may be a better fit to just use full-on classes.

But, if the types do pull from a set of well-defined behaviors, or you want to define your behavior in data instead of hard-coding it, type objects can still work. In many cases, behavioral differences can be modeled either using different attributes, or through the strategy pattern.

Answering your use cases specifically:

> What if the shortsword only damages orcs

```
class ItemType {
  public ItemType(ItemType parent, Integer damage,
      Map<MonsterType, Float> multipliers) {
    this.parent = parent;
    this.damage = damage;
    this.multipliers = multipliers;
  }

  public int getDamage(MonsterType monster) {
    return getBaseDamage() * getMultiplier(monster);
  }

  protected int getBaseDamage() {
    if (damage != null) return damage;
    return parent.getDamage();
  }

  protected float getMultiplier(MonsterType monsterType) {
    Float multiplier = multipliers.get(monsterType);
    if (multiplier != null) return multiplier;
    if (parent == null) return 1;
    return parent.getMultiplier();
  }

  private ItemType parent;
  private Integer damage;
  private Map<MonsterType, Float> multipliers;
}

MonsterType orc = ...
ItemType shortSword = new ItemType(null, 123,
    Collections.singletonMap(orc, 0);

```

Now you've got an extensible way to make certain items have different strength against different monsters, and you can still make it data-driven.

My roguelike does something similar, though it adds a couple of levels of abstraction. An ItemType may have one or more Powers which modify the item (think "Sword of burning" where "of burning" is the power). A Power can have a set of flags. There are flags like "hurts-orcs" that modify the damage against a Group, and then, finally, a MonsterType can be in one or more Groups. The last allows items to be strong against different overlapping sets of monsters.

For example an undead dragon is in both the "undead" and "dragon" groups, so a weapon that does extra damage against *either* of those will be effective against the monster.

> What if the dagger does random damage?

```
interface Dice {
  int roll();
}

class FixedDice implements Dice {
  public FixedDice(int value) {
    this.value = value;
  }

  public int roll() { return value; }

  private int value;
}

class RangeDice implements Dice {
  public RangeDice(int min, int max) {
    this.min = min;
    this.max = max;
    this.random = new Random();
  }

  public int roll() {
    return random.next(max - min) + min;
  }

  private int min;
  private int max;
  private Random random;
}

class ItemType {
  public ItemType(ItemType parent, Dice damage) {
    this.parent = parent;
    this.damage = damage;
  }

  public int getDamage() {
    if (damage != null) return damage.roll();
    return parent.getDamage().roll();
  }

  private ItemType parent;
  private Dice damage;
}

ItemType dagger = new ItemType(null, new RangeDice(2, 20));

```

This is how my roguelike works now. Most attributes on a type are instances of a Roller class that can select from a couple of different number generators. These can be specified in the data files like:

```
123  // fixed amount
2-10 // equally weighted random range
3d6  // d&d style dice roll

```

# Answer
> 0 votes
you can sorta do nested enums:

```
enum dogs {
    boxer, collie;
}
enum cats {
    siamese, tom
}
enum Animal {
    cat(cats.tom), dog(dogs.boxer);
    Animal(Enum e) {
        this.e = e;
    }
    Object[] subValues() {
        return e.getDeclaringClass().getEnumConstants();
    }
    final Enum e;
}
public class Main {
    public static void main(String[] args) {
        for (Animal animal : Animal.values()) {
            System.out.print(animal);
            for (Object o : animal.subValues())
                System.out.print(" " + o);
            System.out.println();
        }
    }
}

```

i wrote some code for an ad&d 2.0 game here that has character classes, races, weapons classes and a dice roller that may be useful.

---
Tags: java, rpg
---


# Question
Title: How do I prevent identity spoofing in a multiplayer game?
I'm thinking about clients spoofing IP addresses, tricking other clients that they are the server; that sort of stuff. (I don't know much about this, so if this is completely wrong, please correct me.)

What should I do to prevent this? Because it is a real-time game, if I were to use encryption, I would use something fast and secure like RC4. Should I encrypt packet data with a key, that the server gives to the client?

If it makes any difference, I'm using UDP.

# Answer
One possible solution is to authenticate the user using TCP+TLS; then, within the same channel, use something like Diffie-Hellman to negotiate a symmetrical key. Finally encrypt each UDP packet using a symmetrical algorithm like RC4.

You technically do not need to use TCP+TLS to negotiate the symmetrical key if you use something like SRP \- just remember that clean Diffie-Hellman is vulnerable to a MITM attack.

You could go even further and use the custom SEQ field in your UDP packets (if you are using some form of reliable UDP) to implement a form of counter-mode encryption - where you add the SEQ number to the negotiated key for each packet; making it that much more difficult to mount a known-plain-text attack.

Don't let your server just hand out keys at will - a 'spoof' server could just as easily hand out it's own key; defeating the purpose of your whole encryption scheme. The only assured way is to either use TLS or mutual knowledge (such as a password/hash).
> 9 votes

# Answer
I have a distant (2 years ago) background in hacking, the hardest packets to ever crack (and what I suggest you use) is using a symmetrical key encryption method which Jonathan Dickinson described in short. You should use TCP+TLS as he also mentioned. However, he said a counter sequence.

I've run into times where a programmers "hack proof" system was easily spoofed because they have a strange enough counting system that I could crack it without programming knowledge and first year algebraic logic. As long as you pick a proper sequential method then your target should receive data exactly as expected, also meaning you should use TCP for the most secure operations.

Back on track to "in my experiences", one system I found works fantastically. A sequential method based on time sent and time expected. Since the packets must always be received in the proper order, to spoof a packet then was nearly impossible since I could never predict when a packet would be sent and when it was expected (between one packet and another) without first hacking the client program.

**The short answer**

In short: Each packet structure would also have a time stamp as when it was sent down to the millisecond. That's damn simple and it's really easy to check if a time is before/after another time. The reason why it makes sense so well is because the server may still receive packets in order with spoofing, without the time for authentication.

This obviously isn't the only sequential method or even the best of any method. It's just one that I've found that works very well. Combined with TCP+TLS you shouldn't have too many issues.
> 8 votes

# Answer
Personally, I wouldn't go overboard too early. Even if you encrypt your packets like Jonathan is recommending, hackers like my brother will just access the packet data before it's encrypted. If malicious users want in, they will find a way in.

Now that that's out of the way, there are ways for indie developers to minimize the damage malicious users can do. You should probably encrypt your outbound packets, but that will only stop certain kinds of attacks, don't fool yourself into thinking it's now "hack proof". To really turn hackers off, give the clients as little game-changing control as possible. One of these big MMOs out there used to allow the clients to tell the server how much XP they've earned. Guess what happened there? Don't do that. Let the client tell the server that they want to cast some super-spell on the creature, and then let the server resolve the action and then add the XP when the creature is dead. The clients should be thin, dumb, terminals that can send and receive commands, and can do some prediction (if necessary). The server should be running *the* game and react to commands sent by the clients.

Large game companies use the above in addition to something like VAC or PunkBuster to prevent known hackers from continuing to disrupt paying customers. How these security measures work is kept fairly secret, but I do know one method that they use: they scan currently-running applications and compare those against lists of known hacks. Once you have been caught cheating, you will be unable to join VAC/PunkBuster secured servers.

Related: Game logic on the server! Good or bad?
> 4 votes

---
Tags: networking, security, udp, authentication
---


# Question
Title: Does there exist a library of animations for easing, skewing, bouncing, and squishing?
I'm specifically referring to the types of animations that are typical in 2D hand held games on the Nintendo platform, where menus slide in, bounce, squish, etc.

I'm looking for something that is somewhat canned but allows for tweaks. Does something like this exist in any form (don't really care what language or for what targeted platform, I'm just looking for the pure math behind it).

# Answer
Here is a good tweening library for javascript. Sourcecode is clean and easy to read.

http://sole.github.com/tween.js/examples/03\_graphs.html
> 4 votes

# Answer
UlanB made a great answer. It's actually a pleasure to work with the specific javascript example he posted. Ajax and jquery works great for this stuff. I really wish you would have asked this in about 1 month from now though, because I'm working on a library made just for this. With a lot of control that is. So animations aren't predefined, just supported with ease of use.

To remain on topic: I recommend doing these things for yourself. It may sound like a pain at first. But writing my library has been quite a learning experience. Especially note that things "aren't always as they seem"+"sometimes it's just that simple" in general when it comes to this stuff what ever works, works.

You can create ease by simply animating something over time with a speed that increases or decreases over time. To make it "bounce" or something, have it quickly move downward and when it hits where you want it to bounce at, stretch it sideways maybe 5-10% and downwards up to 60% over that time as well. And on the returning to normal time, you could either have the same thing happen in reverse, or the method I use which is to reverse the frames of that specific menu objects animation structure.

**EDIT:** In general though, it's still animation. Animation happens over time, and is straight forward. You can use pathing, and have time constant, slowing or speeding up at a given rate. You can also use key frames and predetermine the methods for animation.
> 3 votes

---
Tags: 2d, animation, interface
---


# Question
Title: how to script a match 3 game without waiting for matches to finish
I have developed a full match 3 game without the ability of making another move until all cascading is finished.

I was stuck trying to figure out how to do it with the ability of making moves even if the previous moves have not finished yet. I can't figure out the programing logic behind it, I tried different approaches with no luck so far, the results came up messy.

Can any one help.

Thanks in advance.

# Answer
You should have a model that represents the board, typically an array with rows and cols. As the tiles fall, they may do so at the same or even different rates, once they have completed traveling the distance required to cover one space, they de-list themselves from their starting location, and list themselves with their new location.

Some notes:

* It is wise to measure this based on the center of the tile, such that once the center has moved into the next cell, you count it as in that next cell. This will look better overall.
* Separate the model of where the tile is, from how the tile falls. Once you've detected that the tile is above an empty cell, have it enter the free-fall mode, sending off 'I've switched cells' notices as it moves down a cell. Falling more than one cell down will naturally arise from this and you will not need to create logic to control that.
* This all assumes you don't have a rotating board or anything fancy like that.
* This is by no means the only way to do it, it just is one way to do what most match-3 games do.
> 3 votes

---
Tags: game-mechanics, matchmaking
---


# Question
Title: Is it possible to create a Facebook game that is a Windows executable?
I'm thinking of trying to make a game, and I heard Facebook is good place to make it popular, but I don't want to make a sprite-based Flash game, I want to use OpenGL for rendering to get nice graphics and good performance with it.

I know there is Java which supports OpenGL (I think), but I would like to make my game closed-source so that people cannot make their own mods for it like what happened with Minecraft.

Another option I thought was to make OpenGL executable **and** a Flash version, but I think it might be too much work for one guy. Not to mention I have never done anything in Flash.

So, is there any way to develop closed-source game that can be also played through a browser? By closed-source I mean the people have no way of getting the source code by decompiling it in any way.

# Answer
> 2 votes
Something will only get popular on Facebook if you build all the Facebook infrastructure, ie. a website with various links into the Facebook API to allow people to log in, share links, comment on it, etc. It's probably not worth the effort unless you have a specific reason to want to use the Facebook system.

To have something playable on the web and also as an executable, and to directly use OpenGL, then pretty much your only choice right now is Java. You can get accelerated 3D in the browser with Unity, but you don't have low level OpenGL access. And Flash's 3D support is rapidly becoming usable, but I don't know how you access those APIs.

# Answer
> 2 votes
If you ever reconsider the closed-source approach, then I think JavaScript and WebGL are what you need. I have a few randomly picked arguments for you:

* JavaScript can be obfuscated to a point where it's not worth reverse-engineering, simply because it can be redone in less time.
* don't think your **code** is worth much, it's your **idea** that will be copied, and what you will achieve *alone* in 2 years will be redone by a team of six in less than 4 months.
* even if you ship compiled code, you will have a hard time preventing anyone from modifying your assets.

If you really don't want to go that way, I have never used it myself, but haXe was recommended to me several times including very recently. It is a high-level language similar to ActionScript that compiles to JavaScript, Flash, C++ and more. It has OpenGL bindings that alas do not appear to be maintained.

My personal expectation is that solutions such as Google's NativeClient will some day become the norm, because that will make a fantastic amount of code portable to web applications. Right now I can write OpenGL ES code with NaCl that runs at native speed and I am extremely satisfied with the very little amount of code I had to change. The Ogre engine was successfully ported to NaCl. The drawback is that the code only works in Chrome, and the Mozilla developers have made it clear that they don't want NaCl in Firefox.

---
Tags: opengl, flash, windows, facebook
---


title: How does networking in XNA work?

text:
# Question
Title: How does networking in XNA work?
I am quite confused over how networking works in XNA. I'm currently developing a game for Xbox. I want to create a multiplayer environment and read some tutorials about it.

But I'm confused over how packets are transmitted over the network - E.g.; what is the difference between a `LocalNetworkGamer`, a `NetworkGamer` and a `LocalGamer`? Why do I need to iterate over all `LocalGamers` when reading packets?

I know that's not a typical SE question, but can anyone point to a tutorial that explains how the networking operates as opposed to how to use it?

# Answer
> 6 votes
You can read this tutorial from msdn website (it's for xna 3.1 but it will work for xna 4):

http://msdn.microsoft.com/en-us/library/bb975645(v=xnagamestudio.31).aspx

Alternatively you can use lidgren for networking, you can find it here :

http://code.google.com/p/lidgren-network-gen3/

And a tutorial here :

http://xnacoding.blogspot.com/2010/07/how-to-lidgren-network.html

EDIT:

On xbox you can't use lidgren.

One thing you can do is to look into existing project. Like the one on App Hub :

http://create.msdn.com/en-GB/education/catalog/?devarea=19

# Answer
> 3 votes
Using the built-in networking in XNA, all networking centers on the NetworkSession. Once you have an active session (you can check the MSDN link abve or AppHub examples for creating and joining sessions) you have two types of players in the session:

* LocalNetworkGamer \- players on your Xbox participating in the session
* NetworkGamer \- players attached to other Xboxes participating in the session

The NetworkSession has three properties that let you find out who is who. LocalGamers gives you only players connected to the local Xbox, RemoteGamers gives you all players connected to other Xboxes in the session, and AllGamers gives you both.

Data is sent across the network through the session by calling SendData on a LocalNetworkGamer. There are several overloads of this method - some send data to all players in the session (including the person sending it), others send data only to target gamers. When you call NetworkSession.Update the framework collects all the outgoing SendData requests since the last update and sends the appropriate packets to the correct machines. NetworkSession.Update also receives all earlier sent data and stores it in a buffer per gamer. To actually do something with the data sent over the network you need to pull it out of these buffers; this is done by calling ReceiveData on all the LocalNetworkGamers in your network session. If you don't call ReceiveData you will eventually have issues where the incoming data buffer is full and overflows.

---
Tags: xna, networking, xbox360
---


# Question
Title: Why does my sprite jitter when it arrives at its destination?
I have just started looking into XNA for WP7 - and I am definitely the sort of person who likes to find answers to my questions without begging for help!

I searched here to find an answer but I found it hard to word my question, so apologies if it has been asked.

Basically I have a sprite, which I am moving to and from set locations on the screen. I have defined these locations and set up the methods to detect the input on the screen (I only want to be able to swipe left and right to select the location).

The sprite moves to the correct location when I swipe, but sometimes when it arrives at its location, it jitters very quickly backwards and forwards. My guess is that because of the maths used to calculate the vectors, it never actually hits the exact location, so keeps moving.

My theory was to set up some sort of boundary, where if the sprite was detected within x amount of pixels of the actual location, the sprite is snapped to the correct location. Would this be a good way of doing something? I imagine it isn't the most elegant solution as it will have that snapping motion towards the end, or am I just over-exaggerating what that will look like in my mind?

can anyone suggest a way of getting around this jumpy sprite? Code that i think is relevant below :)

Initialising:

```
player = new Player();
playerMoveSpeed = 12.0f;
player.Position = positionsSet.getLocation(1);

```

I defined my 4 locations like this:

```
Vector2 position1 = new Vector2(10.0f, 30.0f);
Vector2 position2 = new Vector2(210.0f, 30.0f);

```

My calculating the movement happens like this and is where I believe the stuttering to occur:

```
Vector2 direction = goTo - player.Position;
direction.Normalize();
player.Position = player.Position + direction * playerMoveSpeed;

```

Oh, and to get there I call this method (the gametime parameter is something I was trying, its not actually being used at the moment :) ) :

```
if(player.Position != goTo)
moveToLocation(goTo,gameTime);

```

Any advice would be massively appreciated guys and girls, I think I am getting there, but it is just annoying me now :)

# Answer
Vector2 uses floating point numbers, so when you calculate the difference between where you want to go and where you are (goTo - player.Position) it will almost never be exactly zero. This leads to some jitter, which is likely worse at some locations.

If you can't switch to integer-based positions (i.e. Point) you will end up having to cap the movement as you have found out. One way of doing this is to compare length of the direction vector before you normalize it and if it is under a set value simply go to the target position. If your margin of error before snapping is small enough you will not notice the snapping at all.
> 3 votes

# Answer
The following code has the problem that you could go far beyond `goTo`:

```
Vector2 direction = goTo - player.Position;
direction.Normalize();
player.Position = player.Position + direction * playerMoveSpeed;

```

You need to stop moving when you reach your destination. I suggest rewriting it this way:

```
Vector2 direction = goTo - player.Position;
if (playerMoveSpeed > direction.Length())
{
    player.Position = goTo;
}
else
{
    direction.Normalize();
    player.Position = player.Position + direction * playerMoveSpeed;
}

```

Also, you will soon find out that your game is not framerate-independent. This is already obvious because you are adding a speed to a position, which is inconsistent: somewehere you will need to multiply that speed by a duration. See this thread on MSDN which is very closely related to your current code.
> 4 votes

---
Tags: xna, c#, vector, windows-phone-7
---


# Question
Title: Is there a testing framework for bounding volume classes?
This may be a long shot, but is there a small framework out there anywhere for testing custom bounding classes and other collision objects? (for example between rays, spheres and AABB's)

# Answer
I don't think you'll find any testing frameworks specifically geared towards testing bounding volumes and other geometric primitives or operations, but you can accomplish what you want with unit testing frameworks.

* UnitTest++ is quite simple and compact. I'd probably recommend that as a starting point.
* I've also used Google Test as well, which is a bit more complicated but integrates well with Google Mock (which is likely complete overkill for your needs).
* There's also CppTest, which I've never used, and similarly
* Boost.Test which is used to help test Boost itself.

Note that you don't need to create strict unit tests to actually employ a unit testing framework; it's perfect acceptable to use them to simply drive some quick automated tests. I would peruse the above, plus whatever else you might find on Google, pick a framework you like working with, and write your tests in that.

When building tests, I find it beneficial to create one test for all classifications of input. This actually tends to be fairly easy when writing tests for mathematical operations -- for example, were I writing a set of tests for the sign() function I would have at least three: one for zero, one for a positive input, and one for a negative input.

It's also helpful to work through the expected test results by hand prior to writing the test. This will both help you reinforce the math yourself and help ensure you use the same conventions used in your actual math routines.
> 3 votes

---
Tags: c++, collision-detection, testing, bounding-boxes
---


# Question
Title: How can I create a simple, sprite-based Mac game in Xcode?
I am using Xcode and I am new to Objective-C and Cocoa programming. I want to create a very simple sprite game in Xcode, but I do not know what code I should type or where/how to get started.

It's a simple game where you play as a ball (I was thinking of using an `NSButton` with a picture) and you jump around until you touch a flag to complete the level. I also want to add a system of sprite detection so that you can kill enemies if you jump on their heads.

# Answer
There is a game engine called Cocos2d. Check that out. It's pretty easy to use.
> 1 votes

---
Tags: game-design, sprites
---


# Question
Title: How can I make orange/lemon skin normal map?
What would be the easiest way to make a bump map of the dimples on a citrus fruit such as an orange or lemon in gimp/photoshop without using pictures of it? e.g:

# Answer
> 5 votes
The skin is fairly smooth with some big dimples. A first approximation would be (in the GIMP):

1. Take a black image (in greyscale mode)
2. Filters | Noise | Hurl to get some dimple locations
3. Colors | Threshold to reduce it to black and white
4. Filters | Gaussian blur at a small radius (maybe 2px)
5. Colors | Curves to restore the necessary contrast and normalise the background to 127 or 128 (whatever the "no bump" value is).

I suspect you'll find that that gives too much clumping, so the second approximation would be to replace step 2 with random nudging from a hex grid. Either do this in code or create a hex grid in the GIMP and use Filters | Noise | Spread.

# Answer
> 0 votes
Create a flat plane of orange skin in high definition 3D (ie. a Lot of polygons + an orange colour texture).

Bake it.

Use it :-)

This link Might help you get the general idea of baking.

---
Tags: graphics-design, normal-mapping
---


# Question
Title: How important it is for a game to work on a browser in means of popularity?
I've heard many people saying that it makes games more successfull if you can just play them on your browser without downloading a file at all.

Has there been any research about this? Because i find it hard to believe that the people are so lazy they cant click one download button and just unzip the game.

I find it hard to believe because: i have never played a (good) browser game from a browser; i've always launched the Java or Flash directly in its own window, because the webpages are always full of adverts with flashing stuff that distract me too much. I hope others feel the same and i can just forget this "problem" and focus on making games on normal Windows/Linux/Mac executables instead. But i would like to see some evidence on it before i decide to do so.

**Edit:** I dont care about the target audience or etc, just in general, are browser games more popular than downloadable games? and is it really because the users dont want to download any files? more specifically: is there correlation between success and capability to play on a browser?

# Answer
> 6 votes
There's an important distinction to make between in the psychology of the player between free games and paid games.

With a paid game, people are already invested in the product by the time they get around to installing it. Clients are willing to go through more rigmarole to get your product working because they've already made the decision to use it and just tossing it isn't really an option because they've already spent the money.

With a free game, there is no investment by the player. Every gate that you put in front of your user is going to result in a percentage of players not continuing to use your product. Even page load times are an issue. I don't know if this is a reliable source, but Amazon found that every additional 100ms page load time decreased sales by 1%.

Even the Unity plugin, which as far as I'm concerned has a near seamless installation process (no admin rights required, no browser restart required) only has a 60% plugin install success rate.

In the freemium analytics world, this is called "funnel tracking". You want your player experience to be as seamless as possible. That means, for the most amount of exposure, you want:

1) No installation process 2) No sign up process 3) Fast loads 4) Clear, brief menus

Now there are a couple of exceptions to this, obviously. After a certain critical mass people will come seek your product out. But if you're trying to go wide, you're not doing yourself any favors by requiring any additional player steps.

# Answer
> 3 votes
In general, games playable in a browser will have a higher player count. Unfortunately, I cannot find any hard data on this, though a few by the numbers posts suggest that it's really easy to get a few *million* plays on a Flash game, whereas even top selling AAA games only sell a few million copies. Additionally, I've heard from many other developers who used to do downloadable games that they received higher player counts when they switched to Flash or Unity games. Additionally, compare the reviews and comments on games at competition sites like Ludum Dare for browser games and games that require a download. On average, browser games get more reviews and comments (and thus, likely, more plays).

So why is this? People are lazy. Generally, the more work required to play your game, the fewer people that will play it. Add to the general rule a lot of users receive of "never download an .exe file" and you might turn away even more casual users. Offering the absolute lowest barrier to entry (a game that can be played by clicking a single link in the browser) will get you the absolutely highest number of plays.

That said, there *are* plenty of people willing to download and unzip a game to play it, but there's definitely going to be *fewer* of those than people who will simply play a browser game.

Finally, popularity is a factor of a lot of things. Advertising your game on various sites is probably going to be more important to player count than what platform you're game uses. Again, this is where browser/flash/unity games excel, since there's thousands of Flash game portals, and only one site where people would have to find to play a downloadable game. (and of course, having a game made is also important to this whole thing)

# Answer
> 1 votes
It depends on your target audience. Casual gamers are more likely to choose a game that can just be played in your browser, while hardcore gamers might be more willing to install a game client.

Providing your game as a browser based experience makes it possible to play everywhere, then again, not every user has flash/java installed.

You not only need to make sure your players have the needed plugins installed, their browsers might be lacking certain capabillities your game needs. For example, lynx ( http://en.wikipedia.org/wiki/Lynx\_%28web\_browser%29 ) runs on the console and lacks most graphics capabillities of other browsers. (ok, extremely overdrawn example, but not so far fetched.)

So, if providing a browser based game works for you and your audience, go with it, otherwise, don't.

---
Tags: browser-based-games
---


# Question
Title: How should one design an analytics system for an online multiplayer game?
For my simple MMO, the MySQL database stores things like user experience, user level, user coins, health points, etc.

We wanna have an analytics system that can show me trends through daily averages, medians, totals of different stats and actions of the game's user base.

Some answers that need to be answered by this analytics system:

* Average health points over time
* How many users are what level over time
* How many quests were started by users over time vs how many were completed
* Cohort analysis on certain groups of users

I was looking into BI systems and thought maybe building an OLAP database with a star schema might be appropriate. But I'm not sure what are good dimensions to use for this and how to deal with changes to the transactional database over time. And it seems like a lot of work to build out a ETL and reporting system as well.

Anything else that's simpler and yet still robust? Are key-value datastores a good option? What are some commonly used systems for doing this type of analytics?

# Answer
I wouldn't think key/value stores are a good solution for this - they're not very good at calculating over many records.

In my experience, there are 3 common routes:

* run your reporting queries directly against the production database. This is the easiest option, but can affect performance - so, for a game, probably not that useful.
* duplicate your production database - e.g. through replication - and run your reporting queries against the copy. This has minimal impact on the production database (replication has a slight overhead), is relatively easy to set up, and uses your knowledge of the existing schema. It may not scale to *huge* amounts of data, though; to mitigate this, the first step is to pre-calculate commonly needed data. For instance, you might run a nightly batch to calculate daily statistics, a weekly batch for weekly stats etc.
    + create a proper data warehouse with a schema customized for OLAP. This supports huge data sets, and allows you to use high-end reporting tools allowing non-technical folk to create very sophisticated queries (Cognos and the like).

I wouldn't recommend jumping straight to the data warehouse option - it's a whole new world, designing star schemas is a specialist skill, and you will get far better results by implementing your reports using "traditional" SQL queries, and then moving to the data warehouse when you really, really need to.
> 3 votes

# Answer
I would go the OLAP way (maybe because I'm a bit biased as working for icCube) as this is a solid foundation. You're sure to be able to evolve the system in the future.

You do not need to be a specialist to setup a model with a few dimensions to start with. You could create some dedicated SELECT statements (or VIEWS) to create the cubes and once loaded into icCube, your prod DB won't be used anymore (this is an in-memory OLAP server). Later you could decide to create a dedicated DB if required. I do not see requirements for an ETL in your case.

For the reporting side, we're providing a Google Visualization DataSource for very easy access from Javascript to create dedicated dashboards that does exactly what you want the way you want. Or use existing tools connecting using XMLA (Excel, ...).
> 0 votes

---
Tags: databases, analytics
---


# Question
Title: How to create a XNA texture from a GDI Image with source rectangle?
A Texture2D in XNA can only hold so much. Depending on which profile I use that limit is either 2048 or 4096 pixels wide. As far as I could tell from my research (someone correct me if I'm wrong) GDI Images do not have any limitation other than not exceeding the user's memory.

I'm looking for the most efficient way to take a GDI Image and a source rectangle (within XNA's size limitations) and create a new Texture2D from that data at runtime. The process must also take into account XNA 4.0's pre-multiplied alpha!

*OR...*

A way to take Texture2D.FromStream and adapt it so that it takes a source rectangle too, as that would be even better for my needs.

The requirements are:

* No content pipeline, I need to be able to load them at runtime.
* Using only Reach profile if possible!
* Only care about Windows. Don't worry about portability.

---

TL;DR:

I need a method such as:

```
Texture2D Texture2DHelper.FromStream(GraphicsDevice, Stream, SourceRectangle);

```

Or

```
Texture2D Texture2DHelper.FromImage(Image, SourceRectangle)

```

Preferably the first.

---

Big picture:

Ignoring the source rectangle for a moment (to make things easier to visualize), I've tried loading a whole texture in GDI and passing the data to a Texture2D using a completely a brute-force approach:

```
using (System.Drawing.Image image = System.Drawing.Image.FromFile(path))
{
    int w = image.Width;
    int h = image.Height;
    System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image);
    uint[] data = new uint[w * h];
    for (int i=0; i!=bitmap.Width; ++i)
    {
        for (int j=0; j!=bitmap.Height; ++j)
        {
            System.Drawing.Color pixel = bitmap.GetPixel(i, j);
            Microsoft.Xna.Framework.Color color = Color.FromNonPremultiplied(pixel.R, pixel.G, pixel.B, pixel.A);
            data[i + j * w] = color.PackedValue;
        }
    }
    _texture = new Texture2D(device, w, h);
    _texture.SetData(data);
}

```

And the result was *really* slow. It took many many times longer than simply doing:

```
Texture2D.FromStream(GraphicsDevice, new FileStream(path, FileMode.Open));

```

I also thought about using Bitmap.LockBits and a Block Copy but doing that would leave out the pre-multiplied alpha correction, and I don't know how to apply it after the copy.

I'm tempted to think that a better solution would be to work around Texture2D.FromStream directly... I'm not too familiar with how Stream works but I've seen some methods in .NET that take a Stream and a Rectangle. How would I achieve something like that? Either an entirely new FromStream method or a wrapper around any Stream that provides "Rectangle" functionality.

# Answer
OK, managed to find the solution to this, GDI-style! I've wrapped it up in a static helper class:

```
public static class TextureLoader
{
    public static Texture2D FromFile(GraphicsDevice device, string path, Microsoft.Xna.Framework.Rectangle? sourceRectangle = null)
    {
        // XNA 4.0 removed FromFile in favor of FromStream
        // So if we don't pass a source rectangle just delegate to FromStream
        if(sourceRectangle == null)
        {
            return Texture2D.FromStream(device, new FileStream(path, FileMode.Open));
        }
        else
        {
            // If we passed in a source rectangle convert it to System.Drawing.Rectangle
            Microsoft.Xna.Framework.Rectangle xnaRectangle = sourceRectangle.Value;
            System.Drawing.Rectangle gdiRectangle = new System.Drawing.Rectangle(xnaRectangle.X, xnaRectangle.Y, xnaRectangle.Width, xnaRectangle.Height);

            // Start by loading the entire image
            Image image = Image.FromFile(path);

            // Create an empty bitmap to contain our crop
            Bitmap bitmap = new Bitmap(gdiRectangle.Width, gdiRectangle.Height, image.PixelFormat);

            // Draw the cropped image region to the bitmap
            Graphics graphics = Graphics.FromImage(bitmap);
            graphics.DrawImage(image, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), gdiRectangle.X, gdiRectangle.Y, gdiRectangle.Width, gdiRectangle.Height, GraphicsUnit.Pixel);

            // Save the bitmap into a memory stream
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Png);

            // Finally create the Texture2D from stream
            Texture2D texture = Texture2D.FromStream(device, stream);

            // Clean up
            stream.Dispose();
            graphics.Dispose();
            bitmap.Dispose();
            image.Dispose();

            return texture;
        }
    }
}

```

In case you didn't notice Texture2D.FromFile was removed from XNA 4.0 so I took the chance to replicate the old behavior when not passed a source rectangle.

*And the best part is that since at the end it still relies on Texture2D.FromStream, the whole premultiplied alpha phase is automated! Runs relatively fast too.* **Okay this is not true! You still have to do the premultiply alpha calculations.** I just didn't remember well since I already had code to do that in place.

But still wondering if there's a way to do this directly from the Stream without having to pass through GDI. Mind wandered towards decorating the Stream in some way but didn't arrive anywhere. :)

And from browsing through my old code I found a comment about Texture2D.FromStream being bugged and not being able to read all of the formats the documentation says it does, so I've been using GDI anyway. So I'll be staying with this method for now.
> 4 votes

---
Tags: xna, c#, textures, image
---


# Question
Title: How do I change my gravity and jumping logic to put the character at a specific height at a specific point in time?
I'm making a 2D platformer on Android using libGDX. One thing I've had a problem with recently is gravity and jumping. I found a few tutorials on the internet and was able to come up with this...

```
public static final int JUMP_HEIGHT = 64;
public static final float JUMP_GRAVITY= -6.0f;
public static final float MAX_GRAVITY = 20.0f;
public static final float GRAVITY= 19.0f;

private void updateGravity(float delta) {
    if(Gdx.input.isTouched() && !jumping) {
        jumping = true;
        gravity = Config.JUMP_GRAVITY;
    }

    if(jumping) {
        // change frame to jump
        sprite.setRegion(walkFrames[0]);
        sprite.translate(0, (-1*gravity));
        // runner has landed?
        if(sprite.getY() <= idleY) {
            jumping = false;
            sprite.setPosition(Config.RUNNER_X, idleY);
        }
        // slowdown / fall
        if (gravity < Config.MAX_GRAVITY) gravity += Config.GRAVITY*delta;

    }
}

```

The code works and my character will jump and fall smoothly. Although the time it takes for him to jump and comedown is independent from delta the height he jumps is not. If the device lags while jumping he will jump only a portion of how high he should. For the life of me I cannot get it to make sure it jumps a specific height (JUMP\_HEIGHT) and in a specific time independent of the delta.

# Answer
> 3 votes
Keep in mind your units.

What is your gravity variable supposed to represent? Gravity (in physics) is acceleration, which is distance / time squared. You're translating your unit by some arbitrary number (`gravity`), and not taking into account time. So you're treating your acceleration value as if it were a distance value.

A naive solution is simply to multiply your gravity by delta (so imagine your `gravity` is in distance/time), so it's more-or-less framerate independent, but there will be integration errors. Also if your framerate is variable, your end jump height might be different. Usually what I do in these situations is that if your translation would put you beyond your jump height, just clamp that frame's jump height to the max jump height. This would mean that your guy jumping would move at a constant speed (other than the final frame if you do clamping) instead of accelerating up or down.

Now if you want your jumping to be more an acceleration rather than a velocity, you want to do some math like this article describes: http://gafferongames.com/game-physics/integration-basics/ It would involve you adding some velocity/acceleration variables to your character and doing a bit more math, but it's pretty simple. In that scenerio you would always apply gravity to the player, and your jump would be a separate acceleration impulse upwards.

# Answer
> 0 votes
Have a read of this too: http://www.niksula.hut.fi/~hkankaan/Homepages/gravity.html

# Answer
> 0 votes
And I redirect you to the top answer on another post on this site: Good 2D Platformer Physics

The webpage he recommends is pure gold.

---
Tags: android, physics, libgdx
---


# Question
Title: Math behind simulating a simple light source for rotated rectangle?
Say I have a 2D Rectangle. By offsetting its position by x y and rendering a shadow by an offset, it gives the illusion of a shadow. If I rotate the rectangle Z degrees and try it with the same offset, it appears as though the light source has moved. How can I compensate for the angle so it appears as though the shadow is always coming from the same direction?

# Answer
> 7 votes
I tried recreating this and to me it seems like the light source is fixed correctly, e.g. here the light source remains to the top right of the figure:

So I think maybe what you're doing wrong is the **order** in which you apply the rotation and the offset. You need to apply the *rotation first*, and then the *translation*. (And if you had a scale, it would also need to come before the translation)

I'm using XNA so SpriteBatch already got the multiplication order right for me by default :) But here's my code for reference anyway:

```
private Vector2 position = new Vector2(450, 200);
private Vector2 offset = new Vector2(-100, 100);
private float rotation = 0f
private Vector2 origin = new Vector2(shadow.Width/2f, shadow.Height/2f);

spriteBatch.Begin();
spriteBatch.Draw(shadow, position + offset, null, Color.Black * 0.2f, rotation, origin, Vector2.One, SpriteEffects.None, 0f);
spriteBatch.Draw(shadow, position, null, Color.White, rotation, origin, Vector2.One, SpriteEffects.None, 0f);
spriteBatch.End();

```

On this example I'm also rotating the rectangle around its *center*, but I tried with the origin set to zero and it didn't cause any problems for the shadow.

And to show you why order of multiplication matters when applying transformations check this image:

The reason for this behavior is simply because transformations are always applied using the "origin" of the current space. Translation remains the same regardless of the origin, since it's just a displacement and does not need a point of reference. But scaling and rotation vary greatly as you can see from the picture.

Applied to your example of shadows if you don't keep in mind the correct order you'll get a shadow that's glued to your figure!

---
Tags: mathematics, algorithm, shadows
---


# Question
Title: Learning C++, algorithms and vectorial algebra
I need your recommendations for a good study source about videogame orientated C++, algorithms and vectorial algebra.

I will be applying to a videogame programmer course in January so I need to start getting ready asap.

Cheers!

# Answer
> 3 votes
Here are my recommendations:

**Data structures for game programming** LINK

Excellent book for a thorough but easy to understand breakdown of all the useful data structures that games use. What's more, the author provides samples that come in the form of mini-games or interactive demos. Absolutely must have book for beginners.

**Essential Mathematics for Games** LINK

Great resource. This is probably one of the rare few books on mathematics that is geared towards games and that is actually always on my shelf. It does get heavy (hey, it's a math book!) at times, so unless those topics are taught in the current semester, skip over them if you feel nausea set in!

**Design Patterns: Elements of reusable OO programming** LINK

Do you have a computer science background? If yes, then you probably already heard of it and if you did not hear of it, then this is a must. It is not for games only, but it will prepare for you for problem solving. This is not a beginners book. By that I mean, if you are just entering college/university, I would stay away from this book until you understand why you need design patterns in the first place (that is, you are past the stage of "Finally! My code compiles! Now to make it run!")

**OpenGL SuperBible** LINK

Do not bother with the red book. That is a reference, which in my opinion, the internet has made obsolete. This is *the* book to buy for OpenGL. For DirectX, you are on your own :)

**Game Engine Architecture** LINK

You may not want to read this early on. Maybe down the road, when you have good grasp on programming and what a game engine consists of. A great high level overview of game engines.

**Game Engine Design** LINK

WARNING: This is a very very heavy book (literally and conceptually). Just keep it in mind until you are craving for more and the above books look like child's play to you. This is a book filled with concepts that other authors usually do not dare go into simply because they are so hard to understand and even harder to write about to make others understand. Also, the author (who is very knowledgeable btw) is very active in the sense that he always replies to my emails in a couple of days or so.

# Answer
> 2 votes
Adding to Samaursa's list, but trying not to get too long, I'll just add a few of the ones that really stood apart from my library:

**C++ For Game Programmers** LINK

A book which approaches C++ from an intermediate point of view and focused on techniques relevant to game programming. A lot of emphasis on performance and efficiency. Since you asked for that specifically, you might want to give it a try. It's quite good in fact.

**Effective C++** (and it's 2 sequels) LINK

But I'd recommend even more reading this series to get a solid grasp on C++. There's two books on general C++ and one on the STL. All I can say is that these remain to date my favourite C++ books. The books are divided into small sections that tackle specific C++ problems. And even if it's not a game programming book, it's where I learnt most of my C++.

**Game Programming Gems** LINK

This entire series is filled with secrets of the trade from all areas of game development, from programming to graphics, sound, math, AI to networking. They're rather expensive, but I kept an eye open on the used books at amazon and managed to get most of them at a fraction of the price. There's 8 volumes so far, but I find the very first volume to be the most valuable for a beginner since it covers so many things that a game programmer simply needs to know. Check the table of contents of each book online here.

And finally, I know you didn't mention graphics but you will probably eventually get interested in it. For graphics my opinion is...

**Realtime Rendering 3rd Edition** LINK

This is *the* book to get all the concepts and theory of graphics programming. This book is huge, covers virtually any graphic programming topic I could think of, and as an added bonus, it's *beautiful* \- the entire book is in full color and in quality paper. I was really surprised both with the content and the packaging.

And once you have the theory down, jump into practice with "gem-styled" series such as GPU Gems which are available for free, and the ShaderX/GPU Pro series.

---
Tags: c++, algorithm, linear-algebra
---


title: Wanting to make a quick java game

text:
# Question
Title: Wanting to make a quick java game
Hey guys I have experimented in making games in java. So far I have created A text game in JOptionPane that is kind of like Zork but with yes and no buttons (that were changed to "left" and "right"). I have also made a small game where a ball bounces around a screen but with was with heavy help from a website tutorial. Do you guys have any advice or stories about your first game programming? I really want to get into it but it seems like such a steep learning curve. Any help on where I should start or advice? Thanks guys!

# Answer
a quick search will give you lots of results. Check this question out: Game Programming in java

Two great game engines you can tinker around with seem to be:

JMonkeyEngine

Lightweight Java Game Library

Good luck :)
> 1 votes

---
Tags: java
---


# Question
Title: What client front-end options can I use to make a Facebook game?
I have been requested to make a port of an iOS game for Facebook.

The game itself is fairly simple, it is a puzzle game using a 2d array for a grid with XML passed from a server for loading objects onto the the grid, to create levels. The game will ask questions at stages which will be passed to my server and stored for research purposes.

I have looked into both Flash and HTML5/js both of which I have little to no experience in (I'm experienced in Java/C#/Ruby + Rails).

Javascript seems like a nightmare from what I have read, even looking into javascript game engines, but at least it is free.

My backend will most likely be rails for handling server logic.

* Is javascript for programming games really a problem for simple games on Facebook?
* Are js game engines worth using? Does anyone have any experience with them?
* Would prevention of cheating be possible with a js/rails game, do server side checks work?\*
* Are there any alternatives for a front end for someone with C#/Java/Ruby background?\**

I've never seen any Unity or Java apps on Facebook (I don't use it much) and as this is a research project is for my university, I would like to avoid licensing issues.

# Answer
> 1 votes
I'm not an expert in this field, but fundamentally any kind of web-based tech can be used to make a facebook game. As long as you can make the appropriate API calls via some mechanism, and you can put your game in an iframe, you are good to go.

The biggest market is obviously flash games, mainly because it's pretty close to ubiquitous and you don't have to worry as much about cross platform compatibility.

HTML5 games are getting more popular, but that's primarily as there was a push to make games that work on smartphones.

As I linked to in the comments, there are definitely Unity powered games on facebook.

I don't know any Java applet games off hand, but I'm sure it could be done.

---
Tags: flash, javascript, html5, facebook
---


# Question
Title: How to move a 2d sprite to a target location while avoiding obstacles?
How can I get a 2d sprite to move to a position clicked on the screen, without bumping into other objects? I'm programming in java using the android API library

I have created a surface view and loaded my sprites as a bitmap object.

# Answer
It depends on your game. If you have a dense environment with restricted moving paths (eg. something like a maze), then you should look into path-finding. If you have only few and spaced obstacles which may even be moving, then look into steering-behaviors, especially obstacle-avoidance.

**Update:** While path-finding usually works with a starting location and a target-location (eg. your sprites current position and the position you clicked), this might not be so obvious with steering-behaviors. In the case of steering-behaviors, you can use a combination of behaviors. Eg. start with a behavior like "Arrival" where the target is where you last clicked. During this behavior, check for obstacles in the way and switch to the *obstacle-avoidance* behavior if you detect an obstacle in your path. As soon as the way is clear, re-apply the *arrival* behavior. Alternatively you could also implement your own behavior that takes everything into account.
> 5 votes

---
Tags: android, java, collision-detection, sprites, input
---


# Question
Title: Non axis aligned bounding box collision and physics
Exactly how much more expensive, and while we're at it, difficult, is it to have non-axis aligned bounding boxes in your framework?

I realise that it very much depends on what you're trying to do, so here's a little bit of detail; My small demo framework has a number of bots running around shooting each other. when they die, they explode into cubes. When they're hit, or the bullets miss and hit a wall; more cubes.

At the moment I'm taking advantage of the fact that my framework has no floor, just walls, so you can't really tell if the cubes are resting exactly on the floor or not - as a result I'm using bounding spheres as a cheats collision detection. The main visual problem is when a bot dies from a point blank shot; the middle of the agent blows out backwards but the bottom and top parts sort of collapse into a little pile of cubes.

I'd love to be able to have much more realistic physics on all the cubes so they collide and tumble realistically over one-another.

How would I go about achieving this? and how feasible is it? to have a little physics engine which is just cube on cube.

# Answer
The bounding sphere solution is an excellent start. I suggest having two spheres instead, one of radius `a×sqrt(3)/2` (when those spheres *do not* collide, you know your cubes do not collide) and one of radius `a/2` (when those spheres *do* collide, you know your cubes also collide).

Bounding box collision checks are not trivial, but they aren't that difficult. Usually one uses the separating axis theorem, which works with any convex shape: if an axis can be found where the projection of the two boxes do not overlap, then the boxes do not collide. Dynamic Collision Detection using Oriented Bounding Boxes from Geometric Tools is a comprehensive paper on the subject. You may also find the object/object intersection table useful because it links to sample code, too, and covers much more than box/box collisions.

As for your final question, I believe a cube/cube physics engine will be difficult. Right now you seem to be doing only static collision checks but you will soon need dynamic collisions with moving, and, worse, rotating objects, together with friction. Luckily you are not the first one to try to implement this! A good, opensource library that does rigid body physics is Bullet. There is also ODE but the project is a lot less active.

Since you are apparently writing your framework, I recommend that you try to implement your own physics engine, because you will learn and understand a lot more than if you use a third-party framework. But it will take some time. Just search online for "rigid-body" and "physics" and you will get all the documentation you need.
> 4 votes

---
Tags: c++, collision-detection, physics, directx, physics-engine
---


title: Cloud gaming Services

text:
# Question
Title: Cloud gaming Services
I am interested in learning about the new movement about cloud gaming services such as Gaikai and onLive which offer remote rendering on clouds for games. I want to know which is the most popular option out there to develop a game upon. I want to develop a small game, without paying anything(open source is what i prefer), so which is the best option out there?

Also on a side note, What is the future do you think? WebGL OR Cloud Gaming?

**EDIT:**

I am kinda looking for a cloud-based gaming API service to power games on the cloud If its available yet... something similar to amazon's cloud service, but for high performance graphics applications. Best if its open source :D

# Answer
> 1 votes
Gaikai and onLive are not platforms you can "develop a game upon", they're simply a way to play games that require powerful systems for people who might not have very good computers. For instance, you could play Skyrim at the highest graphics settings even if you had a five year old computer with an onboard graphics card. Anything that counts as a "small game" wouldn't be something that cloud gaming services would be interested in hosting. If you're interested in developing a small game, then the best option depends heavily on factors like "is your game 3d or 2d?" and "do you want to make a mobile game, a web game, or a downloadable game?"

To answer your side note: WebGL and Cloud Gaming have such a different purpose that there's no competition that'll exist between the two.

As for your edit: A cloud based graphics API isn't really needed, since current cloud based services render the game on their servers, and stream the rendered game to you via the internet. Existing graphics APIs can be used without having to learn about a whole new API. There'd be very little to gain from a cloud-based gaming API.

---
Tags: game-industry
---