title: Sound effects system design

text:
# Question
Title: Sound effects system design
I'm creating a RPG/RTS game in Unity. There are a lot of characters and potentially a lot of different environments. I'm fairly confident with the coding part (so this question isn't really tied to the game engine). I also create music myself (solo work, pad-based live drums in a band, mixing for friends, etc), so I think I have a pretty good grasp of all the neccessary tools. However, I've never created sound design for a game, and I don't really understand how to do that.

How would you organize and use sound effects? For example, you have 5 different character types and 3 different grounds — grass, mud and wood, for example — would you create 5\*3 footstep sounds? Is adding random pitch for variety to a sample a good idea? What about environment sounds — do you create a main loop you just launch on the background, or do you place real sounds (water, wind, tree barks moving, birds) all over the game level?

Overall, I just have too many of this stupid random questions because I don't quite understand how this system should be designed; I would be very thankful if someone gave me a link to some sort of a guide or an article on the matter.

# Answer
From your question, it sounds as though you have no problem designing/acquiring sound effects, and just need to understand implementation approaches.

> How would you organize and use sound effects?

There's one major principle you need to understand when it comes to game audio which is obvious in hindsight, but not everyone gets on their first approach:

> "Anyone who still thinks there's a 1:1 relationship between a sound and a WAV file just doesn't get it." -Brian Schmidt

When a post-production studio edits a film's soundtrack, they ***don't*** place little "SOUND EFFECT INSTANCE" cues all over the timeline. They take a few different sounds and balance them together, triggered at different sequence points to make the soundtrack as organic as possible. It's really hard (and sometimes not desirable, as your game's aesthetic dictates) to do this in games.

The systems you can build (or use) for getting the most flexibility out of your engines vary. One way you can get familiar with this is to download both FMOD and Wwise and start reading their documentation and trying to use the tools (Wwise's installer contains a document describing the interaction between programmer and sound designer that is especially good).

> For example, you have 5 different character types and 3 different grounds — grass, mud, and wood, for example — would you create 5\*3 footstep sounds?

If your characters' footsteps sound different enough, then yes. It's also common to split it up into small, medium, and large footstep sounds because, for example, are human and elf sounds really going to be that different? Save on the disk space and memory and reuse some sounds.

> Is adding random pitch for variety to a sample a good idea?

Yes. Otherwise, you get the "machine gun" effect," which sounds like its name. It's especially bad with multiple impact sounds. For quick, repeated sounds, you typically grab a few different-enough samples and then trigger each of those with their pitch subtly adjusted on each instance of the SFX being triggered.

> What about environment sounds — do you create a main loop you just launch on the background,

Many games have certainly taken this approach. The most recent example I can think of is Bastion. If you hang out in the Bastion for 2-3 minutes, you'll eventually hear the background track fade down then fade up again as the background loop restarts. This is kind of lame. It's possible to make your background loop more dynamic.

To make your background loop more dynamic, think about decomposing the loop into its elements. For a given basic outdoor background loop, you can probably put in these:

* A base, soft wind, or another sound that acts as the bed, or "room tone" if you've done film sound.
* Slightly louder continuous sounds highlighting a feature of the area (eg: babbling brook)
* Frequently-active sounds that are short, but may trigger frequently (birds tweeting)
* Sounds that are very few and far between, but add interest and mystery to the area (occasionally wolf growl, maybe?)

You can effectively think of these categories as all being on their own timeline. Each timeline here has a bank of sounds they can choose at random, and parameters for how frequently they trigger. Examples of parameters:

* Any required delay time between the end of the last sound triggered and the next one beginning in a single category.
* If a particular sound category is allowed to have multiple sounds being played from it at once (might be appropriate for tweeting birds, if it's tuned to happen infrequently)

> or do you place real sounds (water, wind, tree barks moving, birds) all over the game level?

The placed-in-level sounds are sort of a special case since they act as your background loop in some instances, but you may also want *some* form of them in addition to a background loop.

What if a bird flew out of its nest as you approached it, but then you didn't hear a bird squawk until 12 seconds later in the background loop? That would be weird. Even if you have bird squawks in your background loop, it makes sense to also place a bird squawk here.
> 14 votes

# Answer
The brain tends to hear with the eyes, in speech it is described as the McGurk visual effect, but it applies to any sound.

Foley artists make use of this illusion in movies, to trick the brain into thinking the sound heard is produced by what we see, even when it is actually being produced by something entirely different.

If the user sees a different character and a different ground field, he probably will hear a different sound.

Another important thing is that sound design is an art on itself, so there is no recipe to give the right sound effect to every thing occurring in the game.

It boils down to trying different sounds for different things until it feels just right. Randomization plays an important role too, to make things appear real. With some experience it becomes second nature to find the right sound, to play in the right place at the right time.

I would say that reading all of these books is highly recommended to get you up and running. The order in which they appear in the list is by number of copies sold. So the really good ones are at the top.
> 3 votes

# Answer
(I already answered on Reddit but I may as well copy that answer here too.)

This is the sort of thing that is mostly handled automatically in FMod Designer, WWise, Sony's Scream tool, etc. It's a shame that Unity doesn't have something similar.

Yes, you would typically create 15 separate footstep samples. You would also create several of each in order to add variety, and pick which one to play randomly each time. Pitch and amplitude variation may help here but I think you still need more than 1 sample in each case. You need an abstraction layer that translates a request to play a footstep for a given character into picking one of several samples and playing that.

Environment sounds can be done in various ways, and require some further degree of support from the system because you can't just place a sound emitter in the world - players quickly notice when birdsong seems to be coming from one very specific position in 3D space, or when it moves from speaker to speaker when you turn around. But you do often need to be able to assign sounds to areas of the world. So what I've done in the past is assign each ambient sound a zone in which you hear it at full volume, and a larger encompassing zone where it's heard at partial volume, attenuating down to zero at the edge.
> 2 votes

---
Tags: architecture, sound, sound-effects
---


# Question
Title: Separating Axis Theorem fails at certain angles
I'm currently attempting to add an overlap tester for an axis aligned and orientated bounding box but the solution only seems to work accurately when the OBB's angle is between -10 and +10. As the angle approaches +90 degrees the collision area seems to at first move to the right half of the OBB and then become non existent. Between 90 and 270 I couldn't get an overlap and then when it comes round a full 360 the area registers accurately again.

Any light on this subject would be great. I'm using positive X for 0 degrees increasing CCW.

EDIT: Did a little more research and realized that projecting a vector onto another requires more than just a dot product. Could any one give me a correct version of one of the check axis methods below?

EDIT 2: Actually just a dot product should do I think since the vectors being projected onto are unit length.

```
public static bool overlapAABB_OBB(AABB a, OBB o)
    {
        float rads = MathHelper.ToRadians(-o.angle);
        T = Vector2.Subtract(o.position, a.position);
        Ax.X = 1;
        Ax.Y = 0;
        Ay.X = 0;
        Ay.Y = 1;
        Ox.X = (float)Math.Cos(rads);
        Ox.Y = (float)Math.Sin(rads);
        Oy.X = -Ox.Y;
        Oy.Y = Ox.X;
        if (checkAX(a, o) &&
           checkAY(a, o) &&
           checkOX(a, o) &&
           checkOY(a, o))
            return true;
        else
            return false;
    }

    private static bool checkAX(AABB a, OBB o)
    {
        float TAx = Vector2.Dot(T, Ax);
        float WoOxAx = Vector2.Dot(Vector2.Multiply(Ox, o.halfWidth), Ax);
        float HoOyAx = Vector2.Dot(Vector2.Multiply(Oy, o.halfHeight), Ax);
        if (TAx > a.halfWidth + WoOxAx + HoOyAx)
            return false;
        else
            return true;
    }

    private static bool checkAY(AABB a, OBB o)
    {
        float TAy = Vector2.Dot(T, Ay);
        float WoOxAy = Vector2.Dot(Vector2.Multiply(Ox, o.halfWidth), Ay);
        float HoOyAy = Vector2.Dot(Vector2.Multiply(Oy, o.halfHeight), Ay);
        if (TAy > a.halfHeight + WoOxAy + HoOyAy)
            return false;
        else
            return true;
    }

    private static bool checkOX(AABB a, OBB o)
    {
        float TOx = Vector2.Dot(T, Ox);
        float WaAxOx = Vector2.Dot(Vector2.Multiply(Ax, a.halfWidth), Ox);
        float HaAyOx = Vector2.Dot(Vector2.Multiply(Ay, a.halfHeight), Ox);
        if (TOx > o.halfWidth + WaAxOx + HaAyOx)
            return false;
        else
            return true;
    }

    private static bool checkOY(AABB a, OBB o)
    {
        float TOy = Vector2.Dot(T, Oy);
        float WaAxOy = Vector2.Dot(Vector2.Multiply(Ax, a.halfWidth), Oy);
        float HaAyOy = Vector2.Dot(Vector2.Multiply(Ay, a.halfHeight), Oy);
        if (TOy > o.halfHeight + WaAxOy + HaAyOy)
            return false;
        else
            return true;
    }

```

# Answer
> 1 votes
dot product is negative when the angle between the two vectors is greater than 90º, for the code to work properly you would need to take the absolute value of the dot product.

```
//...
private static bool checkAX(AABB a, OBB o)
{
    float TAx    = Math.Abs( Vector2.Dot(T, Ax) );
    float WoOxAx = Math.Abs( Vector2.Dot(Vector2.Multiply(Ox, o.halfWidth), Ax) );
    float HoOyAx = Math.Abs( Vector2.Dot(Vector2.Multiply(Oy, o.halfHeight), Ax) );
    if (TAx > a.halfWidth + WoOxAx + HoOyAx)
        return false;
    else
        return true;
}
//...

```

this also applies to `checkAY`, `checkOX`, and `checkOY`

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


# Question
Title: Need info on creating a tile grid data structure in Java
I'm trying to create a game with a fixed size map (2D Tile array). I suppose I can inherit other tiles from this base Tile, e.g.: a BankTile. Placing and removing tiles is all too easy, but forming rooms keeps me puzzled.

* Rooms can only be formed by adjacent tiles (4-way: above, below, left and right)

This way, 2 tiles can form a 'room', e.g. a Bank with a maximum amount of resources it can hold (sum of both its tiles).

I am wondering on how I should be implementing this, if there are any existing (and optimal) solutions to this.

Some things I considered:

* Tiles must keep a reference to the Room they are in AND rooms must keep a vector of all tiles they hold. So adding tiles and removing tiles becomes pretty efficient. Only obstacle this poses is the splitting of rooms: if 1 tile connects 2 rooms and this tile is removed, it should split the room and creating a new room for the split-off part.
* Rooms will be 2D vectors with a begin-position (the room will be a surrounding square of the actual room polygon)
* Rooms are 4-way linked lists of tiles
* ?

What needs to be done with rooms:

* tiles need to be added and removed
* allowing rooms to merge and split
* calculating size of a room
* finding a room quickly on a map

This image clarifies what I need:

Should I pick data structure 1? Rooms are 2D arrays with null-pointers for not-room-tiles. Or should I pick data structure 2? Rooms are 4-way linked lists of tiles. Or should I think of something else, e.g. vector of tiles = room? Given the operations I need to be able to perform on them, which is best?

# Answer
**Just realized by looking at your image, it looks like it's more like " Data structure 1"**

Edit:

I think you're looking for something like this then:

```
//In Your Game manager or whatever
public setRoom(Room r, startX, startY){

   Tile[][] tiles = r.getTiles();
   int sizeY = tiles.size();
   int sizeX = tiles[0].size();

   for(int y=0; y < sizeY; y++)
      for(int x=0; x < sizeX; x++)
          //Adds the tile, for any empty tile you need additional checking
          worldGrid.setTile(tiles[y][0],startX+x,startY+y);
}
 //In Your worldGrid or whatever

  private Tile[][] grid;

 public function setTile(Tile t, x, y){

    grid[y][x] = t;
 }

```

Same can be applied for removing a room. Just make sure you don't overlap rooms. Unless you want that ( empty tiles should be able to overlap without problem). But it needs additional checking so keep that in mind.

In this scenario logic is applied by reading the tiles from worldgrid, whether it's passable, non-passable, other gamelogic etc. The Rooms simply hold the tiles which make up for the room. These tiles are translated to the grid:

You can keep track of the room by adding a member in your Tile:

```
Public class Tile(){
    {
       private int roomId= -1;

        public Tile(){
        }

        public int getRoomdId() {return roomId}
    }

```

So if you need any information on the Room you could just do currentTile.getRoomId(). For example this id could serve as an index position of your Room in an Array. A Room manager for instance that holds all the room objects.

Of course you could make it more complex by making managers for each aspect and keep track of what Tile belongs to what room. It's up to you.

Players position in the 2D array is as follows

```
int indexX = Math.floor(player.x / tileSize);
int indexY = Math.floor(player.y / tileSize);

```

This will give us the indices of the current tile in our worldgrid. --\> grid\[indexY\]\[indexX\]

As for merging rooms have a manager that couples Room objects together. If you go by my example you should be able to retrieve the Room object by Tile. You can then "ask" the RoomManager what room is merged with the current one and read its properties like: size, type etc.

> Or should I pick data structure 2? Rooms are 4-way linked lists of tiles

If you go with a "world grid" as in my example you don't need to. Simply request the surrounding tiles and see if they are passable once the player overlaps with a tile. Unless you move from tile to tile, as in snapping to another tile, then it would be as easy as checking player input. When the player hits the down arrow key, you simply test if the tile below the current one; which is \[y+1\]\[x\]; is passable. If not, nothing happens.
> 3 votes

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


# Question
Title: Good Tools & Methodologies for designing Game Arch
I'm currently developing a multiplayer and turnbased silverlight card game and using WCF Polling Duplex communication. I've almost finished the game but I'm still dealing with the methods and animations during the game end. Sometimes I'm loosing control and can't even debug and leave it for days to get some more motivation.

What I'm asking is that there should be some methods to design the gameflow on papers such as GameState charts or similar. I did some by myself to track states of some objects but it didn't work out. There should be some tools or methods to do this.

# Answer
Try doing some Test Driven Development (TDD) if you are having difficulty debugging something. Use concise methods that do one thing. Don't have large methods that act/do many things. Separation will allow you to test each method individually.

As for charting you could look at Message Sequence Charts to help organize the flow of your game:
> 2 votes

# Answer
> What I'm asking is that there should be some methods to design the gameflow on papers such as GameState charts or similar. I did some by myself to track states of some objects but it didn't work out. There should be some tools or methods to do this.

You can use UML diagrams to plan out your ideas if you like. UML Sequence diagrams are good for communication (and look like Luis Estrada's picture) and UML State diagrams are often useful for modelling state changes in the program.

But there are no standard ways of using game states (and not every game even has discrete states like that) so there isn't really specific tooling for it.
> 1 votes

---
Tags: architecture, project-management
---


# Question
Title: How can I instantiate my variables in Boo?
I have a Player Attributes class:

```
import UnityEngine

class Stat ():
    public current as int
    public max     as int

class PlayerAttributes ( MonoBehaviour ):
    public Name          as string
    public level         as int
    public hp            as Stat = Stat()
    public ep            as Stat = Stat()

public strength      as int   // How accurate and how much damage with melee attacks
public dexterity     as int   // How accurate and how much damage with ranged attacks
public vitality      as int   // How many hit points he has
public power         as int   // How much damage his energy attacks deal
public resistance    as int   // How much defense he has against energy attacks
public agility       as int
public speed         as int   // How fast character attacks

public meleeAtk      as int
public rangedAtk     as int
public defense       as int
public powerAtk      as int
public powerDef      as int
public initiative    as single

public exp         as Stat = Stat()

def SetInitialStats (
            name       as string,
            strength   as int,
            dexterity  as int,
            vitality   as int,
            power      as int,
            resistance as int,
            agility    as int,
            speed      as int,
            exp        as int
          ):
   self.level      = 1
   self.Name       = name
   self.strength   = strength
   self.dexterity  = dexterity
   self.vitality   = vitality
   self.power      = power
   self.resistance = resistance
   self.agility    = agility
   self.speed      = speed
   self.exp.max    = self.level * (self.level + 1) * 500
   AddExp(exp)

def AddExp ( experience as int ):
   exp.current += experience

   while exp.current >= exp.max and level < 99:
     exp.current -= exp.max
     exp.max      = level * (level + 1) * 500
     level       += 1
     IncreaseStats()

def IncreaseStats ():
   strength   += 1
   dexterity  += 1
   vitality   += 1
   power      += 1
   resistance += 1
   agility    += 1
   speed      += 1

   meleeAtk   = (level * 7) + strength
   rangedAtk  = (level * 7) + dexterity
   defense    = (level * 2) + agility
   powerAtk   = (level * 7) + power
   powerDef   = (level * 2) + resistance
   initiative = 20 + ((speed * level)/1500)

   hp.max     = ((level * 5) + vitality) * 10
   hp.current = hp.max

   ep.max       = ((level * 5) + power)
   ep.current = ep.max

```

Jut anything simple really. Well I read in the docs to not use constructors with MonoBehaviour, but I try instantiating my variables with the Start() function which is SetInitialStats (...)

So In another script in the Start() function I call it up like this

```
    Player = PlayerAttributes.SetInitialStats('Robo', 20, 21, 19, 20, 18, 22, 22, 57000)

```

I get the warning: ' An instance of type 'PlayerAttributes' is required to access non static member'

Not sure what else I can do to setup my beginning stats.

I got this to work I Unityscript which worked with a constructor without MonoBehaviour so I don't know where else to go from here. I would like to stay using Boo.

# Answer
> 4 votes
To access non-static members of a class, you need an instance of said class.

I'm not familiar with Boo (and it's been a long time since I've used Python), but try this:

```
Player = PlayerAttributes()
Player.SetInitialStats('Robo', 20, 21, 19, 20, 18, 22, 22, 57000)

```

---
Tags: unity, boo
---


# Question
Title: How do I set shape density in PhysX 3.1?
I'm using PhysX 3.1. I need to give shapes different densities (there are several shapes for my single rigid actor). I know that the shape's density can be set by `NxShapeDesc::density` in PhysX 2.8, but I can't find such an interface in PhysX 3.1.

I know mass properties can be set in PhysX 3.1 just as the snowman example in the SDK. Is there a direct interface to set density for each shape?

# Answer
> 2 votes
You can't directly set shape density in PhysX 3.1, but you can achieve the same results using the helper methods `PxRigidBodyExt::updateMassAndInertia`, and `setMassAndUpdateInertia`. They permit you to specify densities indirectly.

---
Tags: physx
---


# Question
Title: What is the view perspective angle of most 2.5D isometric games
I examined several quite popular games to determine what perspective angle they are using. For the purpose I created a grid that is 45 and 60 degrees isometric viewed and put it onto a screenshot (of Diablo II in this case). None of these grids fit to the game's perspective. So I tried to find the angle that fits best to the perspective and it is close to 53.5 degrees. However, this number seems like coming from nowhere and I believe there is a strong logic behind the number that defines the perspective angle. I tried 9/16 * 90 degrees and 3/4 * 90 degrees (coming from ratios of screens resolution 16:9 and 4:3) but none of my assumptions seem to be correct. Here are screenshots of what I mean:

60 degrees

45 degrees

Something between the two - 53.5 degrees - quite near to the real number

I really need to know what the real degrees are and where it derives from. Any help is quite appreciated! Thank you!

# Answer
> 28 votes
I believe your intuition was correct, just not your formula.

```
atan(4 / 3) = 53.1301024 degrees

```

This ratio can be useful because it forms a Pythagorean triangle, meaning that the length of the diagonal is an exact integer value.

# Answer
> 11 votes
The camera angle used by most "isometric" games is actually 30 degrees (a true isometric view where the x, y, and z axis have the same length is 35.264 degrees). The reason for this angle is so that the width of the tile ends up being twice its height. This way you can get an even 2:1 ratio when drawing the diagonals so the tiles line up neatly without any gaps.

---
Tags: isometric, perspective, angles
---


title: AndEngine Sprite position

text:
# Question
Title: AndEngine Sprite position
I had noticed the AndEngine a few days ago, and I tried to create basic game with a few Sprites.Sure, the engine makes the development process much more easier.However I found the sprite lacking a major functionally:

Whenever there is a need to refer to the position of an Sprite the engine manipulates the position based on the top-left corner of sprite,this is not the best thing because there is a need to subtract/add the width/height to its position in order to refer to its center.However when we refer to he scale of the Sprite it scaled according to its center point (which is great)

I find it very confusing to refer to its position each time differently.I solved that by extending the Sprite class and implementing my methods of setCenter and getCenter, I guess that not the best way to do so.

Do you have any suggestion?

# Answer
I'v decided to completely decouple the logic of the game from the Engine via interfaces.This seems to work quite well and I guess that is the best way (that I found so far) to overcome the drawbacks of this engine.
> 1 votes

# Answer
There's a branch of GLES2 called Anchor-Center. That will allow you to position based on where you set the Anchor-Center.
> 1 votes

---
Tags: android, andengine
---


# Question
Title: Most efficient method to render 1,000s of unique space scenes?
I'm an artist with a concept, not the developer, and I'm trying to wrap my head around the approach I should be taking for the following scenario, namely whether to model in Photoshop or 3DS Max.

Say I have a simple animation loop of a rotating planet with a moon orbiting it that I want to play in the background of a game menu screen. Thanks to your help I have some ideas as to how to represent this illusion in 2D. But what if instead I had thousands of different scenes of this nature I wanted to represent in-game, using different planets, moon configurations, orbiting ships, passing asteroids, various backgrounds, etc. I assume that attempting to render these as video files and apply individually as movie texture is out of the question due to hardware and/or storage limitations on mobile devices, and that the scenes would be too complex for spriting.

Would I be best off using a 3D game engine to individually render constituent objects (a rotating planet, an orbiting moon, a drifting debris field) and then place them in front of a static backdrop (a JPEG of a nebula and star field, for example)? I assume for the same reasons as above that you wouldn't actually pre-render these objects, but instead send instructions to the game engine to draw a sphere, map a couple of textures to it, give it rotational parameters, etc.? Is this basically how it works? What about for the non-simple shapes like asteroids, ships, etc., can you also send a model parameter?

Keeping in mind that these scenes will be backgrounds only and non-interactive, am I on the right track?

# Answer
> 6 votes
Well, first, you're right that if you want to have thousands of permutations of these scenes, which operate in "real-time", your options are either to make a stupid amount of videos/slideshow images which would be altogether prohibitive in size...

So you've got a few answers...

You can certainly build a 3D scene, where you build a render-engine which takes models/textures, and animate them.

You probably don't want to have thousands of stars on screen, though.

The alternative is similar... ...build an engine, and instead of making 3D models, just use images (transparent) of batches of stars.
You can move the image of a star (or stars) around.
Likewise, those sprites (think of it like using collage cutouts, you're moving around on a board), you could treat some of them like a slideshow -- so mini videos or mini slideshows of just small groups of stars and tiny details which you couldn't make models.

And then you can randomize collections of those pieces, their positions, movements, et cetera...
Voila, reusable pieces (smaller size), useful for creating many different scenes.

# Answer
> 0 votes
Yes, you are on the right track. The magic term you are looking for is called **procedural generation**. It is frequently used in games as well as animation to create an almost unlimited variety of possible terrain/creatures/vegetation/items/backgrounds or virtually anything.

A computer can draw. A computer can model. A computer can determine where to put the created objects down. A computer can animate and make your planets float around. It is thus perfectly possible to let the computer create a whole new scene out of nothing.

It is however very hard to get it look right. After all, drawing one beautiful nebula yourself is much easier than to write a system that lets the computer generate many different nebulae.

---
Tags: 3d, unity, graphics
---


# Question
Title: How do I make camera follow the player within some bounds?
I am creating a simple ambient/explorer platformer. Because I want the player to only be able to see a new area once they have reached it, I decided to split up the world in rooms.

To not make things like pushing boxes from room to room overly complicated, this camera behavior is implemented by simply adding or subtracting the screen width/height to/from the camera when the player is out of the screen bounds.

Or, in pseudocode:

```
if(player.x < camera.x)
    camera.x -= screen.width;
if(player.x > camera.y + screen.width)
    camera.x += screen.width;
if(player.y < camera.y)
    camera.y -= screen.height;
if(player.y > camera.y + screen.height)
    camera.y += screen.height;

```

However, I also want to implement a slight parallax effect. For this I obviously need to move the camera around a little. So I need rooms that are slightly bigger than the screen size, and to make the camera follow the player until the player is at one of the sides of the room.

How do I create a smooth camera movement for this?

# Answer
> I am creating a simple ambient/explorer platformer. Because I want the player to only be able to see a new area once they have reached it, I decided to split up the world in rooms. However, I also want to implement a slight parallax-effect.

These effects always manage to look awesome.

> How do I create a smooth camera movement for this?

The code you posted up there probably produces a kind of "snappy" camera movement as the player is walking around.

Keep track of where your camera is and where it needs to be next, and update it every frame by a tiny amount. In other words, perform *interpolation* from camera's currentPosition to nextPosition over time. This will create the smooth effect.

From here on, it's easy to clamp the camera to the sides of the room - make sure your nextPosition is within the boundaries of the room.

For these types of effects, I usually write a *Camera Animator* class with different interpolations.
> 2 votes

---
Tags: camera, movement, platformer, parallax-scrolling
---


# Question
Title: Should Client->Server/Server->Client packets be separate?
When working on network packet structure for games, what is more efficient (in terms of code structure) for packet reading for client/server?

Currently, Our packet structure is to send the packet ID as an Int32, which is read when it is coming into the server. But to minimize the amount of packet ID's we use, instead of having a (for example) *LoginRequest* AND a *LoginResponse*, we use just a *Login* packet. The data is structured differently whether it is the server, or client sending the packet.

Should we use an individual Packet for each Request/Response? Or is there a better way?

**EDIT:**

And by data being different for whether it is the client or server sending, it is different in terms of complete packet structure. So while it still has the same ID, it uses entirely different data types.

**Example (Using a Lobby Request/Lobby Response as one packet)**
*Client Request*

* Packet Id (Int32) (Lets say ID = 5)
* LobbyName (String)
* LobbyPassword (String)
* GameLobby (Boolean)

*Server Response*

* Packet Id (Int32) (still ID = 5)
* LobbyName (String)
* GameLobby (Boolean)
* MemberCount (Int32)

# Answer
When your client-\>server packet #5 has a different structure than your server-\>client packet #5, you are already separating them. A 5S packet (the i-want-to-join-a-lobby-request) has an entirely different meaning than a 5C packet (this-is-the-lobby-you-are-in-message).

When you keep using this structure, you will soon encounter the problem that not every server message has an equivalent client message and vice versa. There will be messages which will only be sent by one party, because there is no reason for a reaction from the other side. And there will be messages to which the other party can respond to with many different messages which would all warrant an own message type.

For that reason I would recommend you to decouple client-sided message type IDs and server-sided message type IDs.
> 3 votes

# Answer
First note: If you are using an Int32 for packet ids you are not going to run out. Even using a ushort is still a lot of packet ids. How many ids are you going to need?

Usually with packets you want to send the least amount of data possible. So sharing a Login packet would probably send unneeded data. You could argue that the Login packet is just used once at logon...so you are not going to have any performance problems.
> 3 votes

# Answer
As Luis mentioned, you're unlikely to run out of ID's for your packets, it might be useful to have the highest bit of your packet ID represent if it is a request or response.

If you can ensure requests are responded to in-order, you could then also have an expected response buffer at each site, and more easily match incoming responses with their requests. In this way, you wouldnt even need an ID for responses.
> 1 votes

# Answer
Use 1 ID per message type. Trying to save IDs by using 1 ID for 2 different messages based on the direction of travel is just extra confusion for no gain. Even if you only used an 8-bit int for message IDs, you'd still have 256 available.
> 1 votes

# Answer
There are times where it makes sense to use some level of coupling between the server and client side exchange of data, particularly in a conversation. But generally I've usually followed the notion that the underlining numeric representation has no relation between one another.

As an example:

* 0x01C7 = CMSG\_WHOIS\_REQUEST
* 0X09FE = SMSG\_WHOIS\_RESPONSE

While reading over the code source, the use of the names makes it easy to understand the context of its use without having to follow the exchange from start to finish. It's very descriptive and helps when debugging something that isn't working as you expected.

We generally keep the numeric representation entirely agnostic of the exchange of data they represent. We did this on purpose to allow us to randomize the packet ids each build as a means to deter outsiders from being able to reverse engineer the protocol as easily. It naturally doesn't prevent reverse engineering, but does slow their process tremendously :P.

As others have eluded, I really don't see any purpose in having any coupling between their numeric representations. You typically wouldn't be using the numeric value anyway in the code and would be using some defined enumeration key or defined constant variable in its place for long-term maintence ease.
> 1 votes

# Answer
I would split up the Packets over multiple libraries (dll's, jar's or whatever you are using)

Since you use the same packet for both directions, when you want to change a packet to contain specific data client -\> server communication, you also have to test the server -\> client again.

You'd have to (unit)test your entire communication every time you update a package and you have the chance to introduce new bugs on every update you do.

When you split the packages whenever you update the client -\> server message, you are sure the other messages are not affected.

Also, I would not use ID's to identify different Packets, I would do this based on classname.

For example, the packet that is send when a client connects to the game I would call ClientWantsToConnectPacket. On the server side, I would handle each packet based on the classname.

This way, your client server connection starts to look a bit more like a ServiceBus solution then raw socket connections.
> -1 votes

---
Tags: networking, client-server
---


title: Handle Multiple Scene

text:
# Question
Title: Handle Multiple Scene
For my game, now I adopt the strategy to create multiple scene. For this I have to ask two question please provide your view for my and other members for improvement.

I have created single TextureManager class in which I load all the graphics of the game which is at least 50 MB.

-\> My first question is that this much loading of texture will create any problem in game performance,So all the scene in the game have reference to this TextureManager class and they access corresponding texture region using dot operator. if other better strategy for this texture loading then please suggest me.

-\> My second question is that my actual game scene uses bound camera and I perform scrolling on that camera but my other scene uses the normal camera. So in this situation what to do? how to use multiple camera for single engine? or how to reset available current camera?

My current working platform is andengine.

Thank for you support.

# Answer
> My second question is that my actual game scene uses bound camera and I perform scrolling on that camera but my other scene uses the normal camera. So in this situation what to do? how to use multiple camera for single engine? or how to reset available current camera?

Our 3d game engine allows us to create as many render targets we wish. A render target is basically a window where we actually project the 3d scene. Generally, there is typically only one render target, but in some cases in the editor and tools, we do have up to 3 render targets.

A render target allows us to create as many viewports we wish within the render target's area and place them as we wish. Such a design allows you to create a minimap viewport or even a split-screen viewport often found in co-op or two-player console games. Viewports are basically a means of dividing the render target's area in specialized regions.

Then, in order to create multiple scenes, we do this by creating a new scene manager for each scene we want to manage. Each scene manager allows us to define as many cameras we want. I could place 10 cameras easily into a scene all with different vantage points of a scene.

The key here is that the viewports associated to the render target can be attached to a specific camera. By attaching a specific camera to a viewport, I now have associated a specific scene to a viewport and the perspective rendered is that of the attached camera.

I find such a design to be helpful in keeping things decoupled at various layers and is very flexible.

> -\> My first question is that this much loading of texture will create any problem in game performance,So all the scene in the game have reference to this TextureManager class and they access corresponding texture region using dot operator. if other better strategy for this texture loading then please suggest me.

It isn't uncommon to do some loading of resources, creating textures that may be needed later and keeping those in memory for use when needed. If you think about any console game, there is usually this "Loading" game state where a lot of this activity happens. The nature of consoles often require such management of resources and memory since background loading of assets isn't optimal as it may be on a PC for example.

In our case, we use a single TextureManager across all scenes. Our rule is that two scenes can't expect to use the same texture name if they're expected to be actually be different. Such a design imposes the responsibility on the scene loader to handle the cases as needed but allows the sharing of texture resources across multiple scenes if the need existed.

In the cases where the textures need to be different, the loader just loads the textures in the manager with a name *scenename.texturename* so that they are allocated uniquely per scene.
> 4 votes

---
Tags: flash, cocos2d-iphone, cocos2d, andengine, cocos2d-x
---


title: How does the Wii controller work?

text:
# Question
Title: How does the Wii controller work?
I've never played the Wii or Kinect, but to my understanding, the Wii captures user movement with 4 cameras and translates them to controls.

How does this work? Has Nintendo published anything on this? I'd appreciate a mathematical explanation.

# Answer
Your description sounds more like the Kinect, though it doesn't have 4 cameras either. Maybe you're referring to a camera in each of the 4 Wii controllers. Wikipedia has a nice explanation of how the Wii controller works.

A summary of the article: An optical sensor in the controller captures the infrared LEDs in the sensor bar. It then calculates its distance, orientation and relative position based on the known fixed distance between the LEDs in the bar.
> 5 votes

# Answer
Wii uses 3 mechanisms to track its controller:

* infrared LEDs placed in a sensor bar
* accelerometer
* gyroscope (introduced in MotionPlus remotes)

Basic implementation was a simple optical calculation of remote's orientation using infrared-sensitive "camera" on top of a controller.

With MotionPlus gyroscope and accelerometer work together (similarly to a smartphone) to detect remote's movement and rotations. It's a much more precise measurement and you don't have to point the controller towards the sensor bar.

The only problem is, it's a relative, not absolute changes we detect, so after some time measurement errors start to add up.

So once in a while infrared camera kicks in and recalibrates the system to fit the LEDs on sensor bar.
> 5 votes

---
Tags: camera, movement, motion-control, wii
---


title: Sound effects in separate thread?

text:
# Question
Title: Sound effects in separate thread?
Does it make sense to carry out all audio (music, sound effects, etc.) in a separate thread?

In your experience, how large would you expect the performance impact of playing some MP3 music and 10-30 sound effects to be?

Could performance be an issue with starting to play many different sound effects (e.g. in the same frame)?

# Answer
> 4 votes
First things first: If you're targeting XBLIG and Windows desktop, you're using XACT, right? Just making sure. Unless you have a compelling reason not to, you should be using XACT. It's got warts, but it solves too many problems for it not be used. That is, unless you're looking to also compile with MonoGame or deploy to Windows Phone. Then it's not so useful.

> Does it make sense to carry out all audio (music, sound effects, etc.) in a separate thread?

Many audio playback libraries start a background thread to load/stream audio into memory and write to the output buffer. You adding another thread on top of this wouldn't do much without a lot of main loop tweaking and tuning (which is probably futile if you aren't specifically targeting XBLIG).

> In your experience, how large would you expect the performance impact of playing some MP3 music and 10-30 sound effects to be?

Yes, there's an impact. How much that impact matters depends on the minimum hardware you want to target and what else is happening in the game at that time. But, before you run into performance problems, you'll run into ear fatigue problems with that many sound effects if you don't do some clever mixing.

> Could performance be an issue with starting to play many different sound effects (e.g. in the same frame)?

You'll probably get a framerate dip if there's a *ton* of sounds starting up in one frame.

If it really becomes a performance problem, consider staggering their playback across frames. Players' ears won't notice the difference, and you give the CPU some extra milliseconds to start mixing the samples.

Rough crappy example that uses SoundEffect:

```
public class AudioManager
{
    private const MaxSoundTriggersPerFrame = 15;

    private struct PlayInfo
    {
        public SoundEffect sfx;
        public float volume;
        public float pitch;
        public float pan;
    }

    Queue<SoundEffect> queuedSFX = new Queue<SoundEffect>();

    PlayOneShot(SoundEffect sfx, float volume, float pitch, float pan)
    {
        queuedSFX.Add(new PlayInfo() {
            sfx = sfx,
            volume = volume,
            pitch = pitch,
            pan = pan
        });
    }

    // Assuming this is called every update frame from Game1.cs or whatever
    public void Update()
    {
        int playCount = 0;

        while (queuedSFX.Count > 0 && playCount <= MaxSoundTriggersPerFrame) {
            var playInfo = queuedSFX.Dequeue();
            playInfo.sfx.Play(playInfo.volume, playInfo.pitch, playInfo.pan);
        }
    }
}

```

It would be neat to pre-populate some metadata about a particular sound effect. In-memory sounds could have their own limit, and sounds that have to be streamed and decoded could have a separate limit.

This also uses a .NET queue, and if you're concerned about performance maybe look into how this is implemented (I don't know off the top of my head). You want it to behave like a `List<T>`, such that internally it stores an array of `PlayInfo` objects and not a linked list of them.

But again: ***If you're thinking at this level, twenty bucks says you have too many sounds playing at once to be pleasant or useful.***

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


# Question
Title: Can other programs and tools be emedded in a video game for games downloaded on line?
I have a two questions about video games I'd like to ask that I bet you can answer.

1. Can someone embed a separate free-standing program or separate tool inside of a typical video game that would be downloaded on-line simultaneously to the game installation?
2. If so, is this a common practice and could you give me any examples of these?

The idea I am exploring is a tool that already exists that would create $$ for non-profits and large charities at no cost to any company. player or to the non-profit.

# Answer
> 2 votes
Yes, this is possible. It's actually something people do regularly. You would probably better know the strategy by the name **Trojan Horse**. This is a method that hackers and other people with ill intent do with their software to install programs that the user doesn't actually want. The extra software they install is typically used for collecting information the user doesn't want to give, installing a bot net client or some other harmful software.

It's highly recommend you don't participate this this activity. Users could easily see this as an attack. If you want to distribute software with a game, allow the user to choose to download the software separately.

Strategies for implementing this functionality is most likely off topic for this site.

Do keep in mind that if this is a tool that utilizes the players computer resources or internet, it does indeed cost them money. Processing takes electricity and some people have caps or pay-per-gigabyte data plans for their internet. It's always best to get full consent for any software you install.

# Answer
> 1 votes
> 1) Can someone embed a separate free-standing program or separate tool inside of a typical video game that would be downloaded on-line simultaneously to the game installation?

It's possible to "embed" software to appear as though it's not getting installed along with the primary package, but it's sneaky and wrong.

It's also possible to request that users install additional programs in addition to the one they're currently installing. This isn't "embedding" per se, but rather is a request for the user to install an additional program.

The mechanism for requesting this differs by platform. On non-AppStore-like environments, the two software companies can make a deal where one agrees to include the other's installer along with their own.

In a modern consumer computing environment (such as the AppStore for Mac and iOS and the new Marketplace in Windows 8) this kind of application behavior won't get approved. You need to present some sort of request to the user indicating that you'd like them to download this other piece of software.

The "request" part is important. The AppStore and Windows Marketplace are enforcing this because installing software without a user's permission is a characteristic of malware. It's like somebody bringing an uninvited guest into your home without your consent. Sure, there's enough people doing it where it's not uncommon, but we all find *that guy* to be really irritating.

> 2) If so, is this a common practice and could you give me any examples of these?

This isn't as common as it once was. Commonly you would get the Yahoo Toolbar or the Gator Toolbar bundled with an application that you wanted to install. These programs typically sucked up a lot of resources, or introduced vulnerabilities that compromised the security of user's computers.

If the software you are requesting the user to install has a valid reason for being there, and you are up front about why you want it installed, users may check out the software out of curiosity. Honesty is key.

Download any games by Zynga or Atari or EA and similarly large companies on a mobile device. They will frequently show you popups asking you to download other software.

**Update**

Pulling up Qqwy's comment into the answer because it's important for Travis to readr:

> Important to note: There are still many programs that include other optional programs in their installer. Indeed these are not 'hidden', but because the users will need to úncheck the checkmark, many people still end up with installing the google toobar, yahoo toolbar, etc. even tough they don't really want it.

# Answer
> 1 votes
Can other programs be included in a game? Sure. They can be included in MANY programs.

Many (most?) modern software installations (and definitely games) are composed of multiple files in a hierarchical file structure. Typically for a game these are sound files, images, model files, levels and such. And considering that an executable is simply a file like any other file (but one that can execute), there's no reason why executables can't be part of an installation.

Is it common practice? Yes, but not in the malicious way that some think.

Many installations of software include multiple executables. One common extra file you may see an uninstaller. My Photoshop directory has 3 executables in it, only one of which is the actual program. MS Office has over 20. My "VIM" installation has 8. iTunes has two. And for games it's not unreasonable for the installation to include tools or SDK programs.

# Answer
> 1 votes
> Note: The idea I am exploring is a tool that already exists that would create $$ for non-profits and large charities at no cost to any company. player or to the non-profit.

Anything you install on the players computer that isn't the game is a "cost." It's not a physical monetary cost that comes out of their credit card at the time, but it potentially costs the user bandwidth, electricity, and experience degredation.

That being said, "professional" games do sometimes bundle adjunct software. Here's one offender (note that if you see what people on the internet are saying about PMB, the chatter is mostly about "how can i remove this annoying software I didn't want that is chewing up my costly bandwidth".

---
Tags: open-source
---


title: Drag and Drop Team Selection

text:
# Question
Title: Drag and Drop Team Selection
I have a Fantasy F1 Website, currently users select their teams using dropdown menus. It works OK but isn't as user friendly as I would like.

I would like to implement a drag and drop type of system, there's jQuery code out there that would go part of the way to allowing me to do this:

http://jqueryui.com/demos/draggable/

But I am not sure about how to integrate that into PHP and MySQL, my jQuery skills are limited!

I'd also need to stop them spending more than a certain amount of money, each driver has a value and the teams can only spend a certain amount of money.

There's also limits for example you can only pick a driver once, but you can have three different drivers.

Finally, how would you decide that the user had picked their team, I don't want a submit button as that kind of defeats the object of the exercise!

Thanks for any advice, I don't expect anyone to write the code for me but some pointers would be greatly appreciated.

# Answer
> 2 votes
It sounds as if you should look at using JavaScript for this part of your interface. You can use JavaScript to validate choices as the user makes selections. For example, when the user chooses a driver, call a function that subtracts the driver's cost from available funds, removes that driver from the list of possible drivers, and updates the count of how many drivers have been chosen so far. You can make the menu more user-friendly by only allowing the user to choose from drivers that they can currently afford (unaffordable drivers could be greyed out, for example). For more complex interactivity such as the drag-and-drop menus you are describing, jQuery would certainly be useful.

You can also use jQuery's .ajax() methods to send data to your PHP scripts. This way more of your game logic could remain in PHP, which might be advantageous if you are trying to prevent cheating (JavaScript can easily be tampered with by the user).

# Answer
> 1 votes
> But I am not sure about how to integrate that into PHP and MySQL, my jQuery skills are limited!

In most cases, you'll have to store the driver's IDs (primary key in the database maybe?) on the client side. When the player has filled the list of drivers, you need to take this list of IDs and send it over to your server.

One approach is to store the ID as a data attribute of your container tag:

```
<div class="driver" data-driver-id="5">
    ...
</div>

```

Using jQuery you can easily extract these attributes back.

```
var selectedDriverIds = $('.driver').data('driver-id');

```

Use the droppable *events* to listen for changes (the driver has been dropped over), and send that to the server using jQuery's AJAX functionality.

Finally, you'll need to write a PHP function that accepts what data is sent, performs a bit of validation if needed, and returns the appropriate response to jQuery's AJAX call.

The way you implement your status codes, such as "OK", "Not enough drivers", etc is up to you. You can send a JSON string back with a number that the client knows how to interpret and display the appropriate message. Alternatively, you can use HTTP's own codes.

```
$.ajax({
  type: "POST",
  url: "http://.../drivers.php",
  data: JSON.stringify(selectedDriverIds),
  success: function(result) {
      if (result.message === "OK") {
          // proceed as planned
      } else {
          // handle the errors
      }
  }
});

```

It's an involved process and does take knowing JS, jQuery, and a bit of PHP\<-\>AJAX knowledge. There are plenty of resources that will walk you through how to do this.

---
Tags: game-design, php
---


title: Kinds of anti aliasing?

text:
# Question
Title: Kinds of anti aliasing?
I'm looking into the newer OpenGL's with GLFW, but I'm stuck in a decision. What kind of anti aliasing is the best, or something that makes it look real, not "real". I don't want the picture blurred, I want it clear. I'm thinking about super sampling but that does not seem like the best due to that it uses a ton of resources. What's your experience with what AA and did you like it? Can someone explain all the types of AA? Thanks!

# Answer
> 5 votes
There was a SIGGRAPH 2011 course on antialiasing in games, which will probably give you far more information about many more types of AA than you really want. :)

When you run a typical PC game and in the options it gives you a choice of "2X, 4X, or 8X" antialiasing, it's referring to multisample antialiasing, MSAA. This stores super-resolution frame buffers and resolves visibility per sample, just like supersampling - but the pixel shader is run only once per pixel, not per sample, and the color it outputs is replicated to all samples in that pixel. That improves performance, but MSAA still requires a lot of extra memory, and induces complications with things like deferred shading.

The latest hotness is to do postprocess antialiasing, where you render the frame normally without MSAA or anything else, then run a filter on the image afterward that tries to identify sharp edges and blur along them or otherwise "repair" them to remove jaggies. This has been quite successful since it's faster and consumes much less memory than MSAA, and it's relatively easy for developers to add to their games. (In fact, GPU vendors are even starting to add postprocess AA options to their *drivers*, so the game doesn't even need to support it directly.) There are many flavors of postprocess antialiasing; the major ones are detailed in that SIGGRAPH course. One of the most popular types currently is fast approximate antialiasing, FXAA.

---
Tags: c++, opengl, antialiasing, glfw
---


# Question
Title: Are there any game engines out there that support cryptography?
Are there any game engines out there that support cryptography? Obviously when one creates a game engine in one of the more established languages, like C++ or Java, one can just get some cryptography libraries and use those. I'm mainly asking about engines that allow one to create games using mainly a scripting language like lua or javascript.

# Answer
I'm assuming that the presence of crypto isn't the only thing that's part of your evaluation of game engines. My suggestion would be to start making a list of features you require (including crypto), and start whittling down the list of engines.

Additionally, what you want to do with it is a factor as well. If you just want to encrypt a local file, that's going to be pretty easy perhaps. If you want to encrypt data transmission between your client and a server, that's getting more complex. But at the same time client/server encryption is pretty common, including just using HTTPS.

Also note that a quick Google shows libraries do exist, including ones for JavaScript and Lua.
> 2 votes

---
Tags: encryption
---


# Question
Title: One Dimensional Perlin noise vs Multi-Dimensional
I am reading through a book called "The Nature of Coding" and I am working on porting the examples from Processing.js to Regular old Java. The example I am on uses the following method call in processing...

```
noise(x)

```

I noticed this class provided by Perlin himself, however, it is three dimensional. Can I just do something like this to make it one dimensional (seems too easy)...

```
static public double noise(double x) {
    return noise(x, 0, 0);
}

```

Or is there some other changes I have to make?

# Answer
> 7 votes
**No**, you should avoid doing that. 3D Perlin noise is 7 or 8 times as expensive as 1D Perlin noise. You'd be better off reimplementing the 1D function, because it's very simple. If I'm not mistaken:

```
static public double noise(double x) {
   int X = (int)Math.floor(x) & 255;
   x -= Math.floor(x);
   double u = fade(x);
   return lerp(u, grad(p[X  ], x  ),
                  grad(p[X+1], x-1));
}

static double grad(int hash, double x) {
   return ((hash&1) == 0 ? x : -x);
}

```

# Answer
> 10 votes
Noise along any of the axes will be consistent noise. Just imagine you're flying through a cloud of noise sampling a single line of data.

So **yes**, `return noise(x, 0, 0);` is exactly like traveling along a single line of noise inside a cloud of noise. You'll be traveling along the line that represents the x axis. You could even do `return noise(x, x, x);` and travel diagonally through the noise if you wanted to. The point being, as long as you're moving linearly through the noise you'll get consistent noise with consistent values of `x`.

---
Tags: java, perlin-noise
---


# Question
Title: RTS game unit damage & defense calculation
How can I model armies attacking each other in an RTS?

I know how I would do it if it is an RPG game. Character has few stats that affect damage/defense and then compare it with enemy character and make calculations.

But what to do when you have an RTS game with lets say 3 kind of units (archers,knights,cavalry).

How would you do a calculation:

eg. 3 archers, 2 horsemen, 4 knights attack 3 knights and 5 horsemen?

One idea I had was to model units as having a certain amount of attack/defense against other units.

eg. Archer - 70% damage against knight, 10% defense against knight (90% damage against horseman (higher chance to hit bigger object)) (10% defense against horseman (if he comes closer))

Knight - 30% damage against archer, 20% defense against archer (50% damage against horseman, 40% defense against horseman)

Horsemen - 90% damage against archer, 20% defense against archer (70% damage against knight, 70% defense against knight)

In my game, players control armies (groups of units), which they send to attack enemy towns. At that point, I need to calculate how much damage the attacking army inflicted on the town (and vice-versa). I'm looking for some sort of formula or algorithm to help determine this.

# Answer
> 0 votes
One way I would solve this problem (albeit simplistically) is simple math. Assign each unit damage and health, eg:

* Archer: 3 attack, 2 health
* Horseman: 7 attack, 5 defense
* Knight: 4 attack, 4 defense

Then simply total it up and see who wins, eg.

3 archers, 2 horsemen, 4 knights = total of 37 attack, 32 health 3 knights, 5 horsemen = total of 47 attack, 37 health

If (again, simplistic model) both sides inflict damage simultaneously, both armies would die.

If another case occurred where, say, 30/36 health remains in one army, you choose how to distribute that amongst the units to decide which survives and which dies.

This is, as I said, a simple addition/subtraction model; you can add a lot more complexity, such as:

* Which army attacks first
* How damage is inflicted (one point to each unit round-robin, or fully on the first unit until it dies, or the strongest, or something else?)
* Who survives
* Attack precedence (eg. calculate archer damage first, then knights, then horsemen)
* etc.

# Answer
> 0 votes
Speaking broadly, I would invent rules for the game I was designing (including, but not limited to, a procedure by which things such as 'damage' would be calculated), and would then implement these rules in a programming language of some sort.

"How to calculate damage" is not a question you can really outsource to StackExchange; it's a core part of your game -- probably *the* core part of your game. We can't answer it in an objectively correct way. You need to decide for yourself how you want your game to work.

---
Tags: rts, strategy, statistics
---


# Question
Title: Peer-to-peer hostless competitive games of chance?
I'm wondering - have any games been ever created that are:

* peer-to-peer without one peer being designated as host
* competitive (not cooperative, players play against one another)
* provably fair (there is no possibility of any player cheating)
* Don't give any player more information than they need (for example, not revealing other players' secrets even to the running applications)

An example of such a game would be a poker game where each player and their games would only be able to know their own hand, but not the hands of other players without relying on any of them being the host of the game. I know there are a few games out there that are provably fair, but all that I know exist in a server-client configuration.

# Answer
I don't know whether such games have been created, but they sure have been theorised. Several papers have been published on the topic. You may want to research commitment schemes which offer an explanation of how two disagreeing parties can flip a coin while being physically distant (see also this 1981 paper: Coin Flipping by Telephone).

One very thorough paper is for instance Cheat-Proof Peer-to-Peer Trading Card Games:

> We propose a **cheat-proof peer-to-peer protocol** for implementing online trading card games. We break down actions common to all TCGs and explain how they can be executed between **two players without the need for a third party referee** (which usually requires an unbiased server). In each action, the player is either prevented from cheating or **if they do cheat, the opponent will be able to prove they have done so**. We conclude by showing how these methods are secure and how they may be intermixed for other styles of TCGs and other peer-to-peer games.

Also Cheat-Proof Playout for Centralized and Peer-to-Peer Gaming:

> We propose a protocol that has **provable anti-cheating guarantees, is provably safe and live**, but suffers a performance penalty. We then develop an extended version of this protocol, called asynchronous synchronization, which avoids the penalty, is serverless, offers provable anti-cheating guarantees, is robust in the presence of packet loss, and provides for signiﬁcantly increased communication performance. This technique is applicable to common game features as well as clustering and cell-based techniques for **massively multiplayer games**. Speciﬁcally, we provide a zero-knowledge proof protocol so that players are within a speciﬁc range of each other, and otherwise have no notion of their distance. Our performance claims are backed by analysis using a simulation based on real game traces.
> 20 votes

# Answer
Although not a game of chance, I'm developing an AIR game that is close to your requirements.

1. Developed using Flash's RTMFP multicast protocol. Neither client is considered host.
2. Physics based competitive system.
3. Verifies opponent input and disqualifies game on invalid data.
4. Does not transmit certain physics information for bandwidth/latency reasons (this disabled certain cheating methods as well).

However, please note...

I consider "no possibility of...cheating" a false statement. If you do not control all aspects (hardware & software) then cheating is possible.

Although not a game, I think the *Bitcoin* network is a prime example of what you are looking for.

**Edit**

I'm going to expand a little on your main question.

First, I can't see any game requiring "provably fair" conditions without some level of authoritative requirement. From leaderboards to micropayments, centralized systems and authority go together.

Second, the best example game I can think of is the early Pokemon games. Although the inner network logistics might not have been peer-to-peer, it follows the same principle.

Finally, the mobile platforms are especially fitted for peer-to-peer games. I consider this field to be very lacking, that is why I'm currently developing a line of peer-to-peer games.
> 4 votes

# Answer
A few pieces that might help, depending on use cases:

If you need to get simultaneous input from users without the possibility that one can use information to their advantage prematurely, you can use commitment scheme. Essentially this is:

1. Both player provide a hash of the action they wish to take.
2. After both have provided their commitment, both can provide their plaintext actions.
3. The plaintext can be compared with the hashes to verify that nobody changed their answer after learning the other person's action.

This can be used for a variety of things, including a shared random number (both provide an integer via commitments and xor them together after sharing to get the shared value.)

That is insufficient for a game like poker however, because it requires cards to be known to only one person, while continuing to be able to draw from the shared deck. Wikipedia has a fairly good algorithm for shared shuffling using a scheme where both players encrypt each card individually multiple times. This sets up a situation where 2 keys are required to decrypt any given card, and both players have 1. The article cites performance concerns, but I don't think AES or similar is prohibitively expensive at the scale required for 2 player poker.

If I were designing an algorithm I would have players calculate a random value at the beginning of the game to use as a seed for all of the rest of the operations and share a hash of that value. That way they can share that value after the game, and you can verify that they followed the protocol correctly, with no shenanigans.
> 1 votes

---
Tags: game-mechanics, peer-to-peer
---


title: Dealing with binary data and endianness

text:
# Question
Title: Dealing with binary data and endianness
When distributing my game, I am going to compile all the resources and level data into a single binary package file, which is loaded from by the game. Do I have to worry about my machine being a different endian-ness than the end-user's, or are discrepancies here obsolete?

If this is going to be a problem, what is the best way to circumvent or solve it?

# Answer
Endianness matters when it comes to game consoles. The Wii, the PS3, and the XBox 360 all run big-endian, while all major desktop computers (as of the date I'm writing this answer) run little-endian. If there's a chance you'll want to compile your code for one of those game consoles someday, or if someone releases another popular big-endian desktop machine someday -- it wasn't so many years ago that all Macintoshes were big-endian, after all -- then you need to think about endianness. And if you don't think about it now, then from personal experience I can tell you that it'll be extremely painful when you have to add big-endian support to a whole completed codebase which was written without it.

Similarly, endianness can matter when you're communicating with internet servers. If you want cross-platform server software, then all your network code should really be transmitting/receiving using the standard network byte ordering: big-endian.

A related issue which you don't mention is that of struct padding. A single struct or class can have different sizes on different platforms or even just between different compilers, and its fields can exist at different offsets within the struct. Put simply: Even if you decide not to care about endianness, you still can't simply treat a struct or class as a binary buffer and naively write it to a file or a network packet. In order to transmit a struct of data from one machine to another, you need to individually read or write each field, rather than treating the struct as a single blob of memory. And honestly, if you're doing that (because you have to in order to support cross-platform), then you might as well convert the values to/from network byte ordering at the same time.
> 6 votes

---
Tags: c++, assets, file-format, hardware, binary
---


# Question
Title: How can I process continuously-held keys with SDL?
I have created a cube in opengl using SDL. Now I am trying to move the camera in X direction if user presses left or right arrow keys and Y direction if user presses up or down arrow keys. Right now the camera moves by a fixed amount in a particular direction if the key gets pressed once. It doesn't matter how long does a person hold the key down, it moves by that fixed amount only. I want the camera to move continuously as long as the key is pressed.

Below is the code for keyboard polling.

```
        while ( SDL_PollEvent( &event ) )
        {
            switch( event.type )
            {
            case SDL_ACTIVEEVENT:
                if ( event.active.gain == 0 )
                isActive = FALSE;
                else
                isActive = TRUE;
                break;
            case SDL_VIDEORESIZE:
                surface = SDL_SetVideoMode( event.resize.w,
                            event.resize.h,
                            16, videoFlags );
                if ( !surface )
                {
                    fprintf( stderr, "Could not get a surface after resize: %s\n", SDL_GetError( ) );
                    Quit( 1 );
                }
                resizeWindow( event.resize.w, event.resize.h );
                break;
            case SDL_KEYDOWN:
                handleKeyPress( &event.key.keysym );
                break;
            case SDL_QUIT:
                done = TRUE;
                break;
            default:
                break;
            }
        }

```

And below i have mentioned the keypress handler function

```
void handleKeyPress( SDL_keysym *keysym )
{
    switch( (keysym->sym) ){
        case SDLK_ESCAPE:
            Quit(0);
            break;
        case SDLK_LEFT:
              eye[0] -= 0.1;
              break;
            case SDLK_RIGHT:
              eye[0] += 0.1;
              break;
            case SDLK_UP:
              eye[1] -= 0.1;
              break;
            case SDLK_DOWN:
              eye[1] += 0.1;
              break;
            default:
              break;
      }

    return;
}

```

What changes should I make in my code to handle continuous keystroke detection?

**Note:** The following code does the required job but I don't understand why

```
if ( ( SDL_EnableKeyRepeat( 100, SDL_DEFAULT_REPEAT_INTERVAL ) ) )
{
        fprintf( stderr, "Setting keyboard repeat failed: %s\n",
             SDL_GetError( ) );
        Quit( 1 );
}

```

# Answer
> 21 votes
```
void Main::processInput()
{
    Uint8* keystate = SDL_GetKeyState(NULL);

    //continuous-response keys
    if(keystate[SDLK_LEFT])
    {
    }
    if(keystate[SDLK_RIGHT])
    {
    }
    if(keystate[SDLK_UP])
    {
    }
    if(keystate[SDLK_DOWN])
    {
    }

    //single-hit keys, mouse, and other general SDL events (eg. windowing)
    while(SDL_PollEvent(&event))
    {
        switch (event.type)
        {
            case SDL_MOUSEMOTION:
            break;

            case SDL_QUIT:
            case SDL_KEYDOWN:
                if(event.key.keysym.sym == SDLK_ESCAPE)
                    done = true; //quit
            break;
        }
    }
}

```

Usage:

```
Main::Main()
{
    //set up SDL etc.
    //set up timing variables etc.
    timeStepMs = 1000.f / yourUpdateFrequency; //eg. 30Hz
    //set up game world etc.

    //main loop, run like the wind!
    while(!done)
    {

        timeLastMs = timeCurrentMs;
        timeCurrentMs = SDL_GetTicks();
        timeDeltaMs = timeCurrentMs - timeLastMs;
        timeAccumulatedMs += timeDeltaMs;

        while (timeAccumulatedMs >= timeStepMs)
        {
              processInput();
              //update world: do ai, physics, etc. here
              timeAccumulatedMs -= timeStepMs;
        }
        render(); //render update only once
    }
}

```

# Answer
> 4 votes
If you're using SDL version 1.x, use SDL\_GetKeyState() to determine whether a key is up or down.

If you're using SDL version 2.x, use SDL\_GetKeyboardState() to determine whether a key is up or down.

# Answer
> 1 votes
I don't know exactly how to do it in SDL, but in pseudo code this is the approach

```
bool[] isKeyDown
bool[] isKeyPressed

public void Check(){
    foreach Key k in Keys
        if(k.isDown && !isKeyDown[k]){
               isKeyDown[k] = true;
               isKeyPressed[k] = true;
        }
        else if(k.IsDown && isKeyDown[k]){
            isKeyPressed[k] = false;
        }
        else{
            isKeyDown[k] = false;
            isKeyPressed[k] = false;
        }
    }
}

```

This way isKeyPressed\[k\] is true and only true the first time k was pressed, you can use that for menu navigation. Alternatively isKeyDown\[k\] is true the entire time that k was pressed.

Now I'm pretty confident that SDL has a way to request the current key state, but if you can only repsond to events you just clear isKeyPressed\[k\] at the start of every game loop, make isKeyPressed\[k\] and isKeyDown\[k\] true on every KeyDown event and make isKeyDown\[k\] false on every KeyUp event.

# Answer
> 1 votes
You're going to want it to read SDL\_KEYUP and SDL\_KEYDOWN. You can either have it so it sets a boolean to true when the key is pressed and to false when the key is unpressed and then have it check the booleans and perform an action if true, or you can do something like this...

```
if(SDL_PollEvent(&event)) {
    if(event.type==SDL_KEYDOWN) {
        switch(event.key.keysym.sym) {
            case SDLK_UP:    yVel-=2; break;
            case SDLK_DOWN:  yVel+=2; break;
            case SDLK_LEFT:  xVel-=2; break;
            case SDLK_RIGHT: xVel+=2; break;
        }
    }
    if(event.type==SDL_KEYUP) {
        switch(event.key.keysym.sym) {
            case SDLK_UP:    yVel+=2; break;
            case SDLK_DOWN:  yVel-=2; break;
            case SDLK_LEFT:  xVel+=2; break;
            case SDLK_RIGHT: xVel-=2; break;
        }
    }
}

```

And then simply add the x/yVel to the x/y position of what you want to move...

```
x+=xVel;
y+=yVel;

```

---
Tags: input, sdl
---


# Question
Title: How to resolve duplicate data in Entity Systems?
Whilst working on examples and upgrades for my C++ Entity System, something randomly caught the attention of my mind, by surprise: duplicate data. What I'm referring to is how an entity system that uses other libraries (e.g. Ogre3D, SFML, etc.), which already store some information about your entities, handles storing information in custom components.

## The Problem:

Say you have two define component types, called: `Position` component (which holds the location of an Entity) and `Velocity`component (which holds how fast an Entity is moving, and the direction it is moving toward). And of course, you have a `Movement` system, which moves entities with a `Position` and `Velocity` component attached to it. Now... here comes the tricky part, how would you store the Position component effectively/efficiently, so that you do not duplicate data? By duplication of data, this is what I mean (this is a simple example): a Sprite object typically has it's own x/y position (take for example, SFML's Sprite class), therefore if I had a Position component with it's own x/y values, then I would be duplicating data, would I not? I thought about using pointers/references\* in a Position component, but that doesn't really work out if I want to save entities to files.

\*Yes, I do know that `sizeof(float) == sizeof(float*)`, but `sizeof(vec2/3) != sizeof(vec2/3*)`. This doesn't really seem much of a problem at first: but what if I had bigger objects to store, such as:

## A Mesh:

How would I store a Mesh effectively in a component? I was thinking of just storing a string to where the mesh data was located, but then I thought, what if it's not in a file? How do I resolve that? I also thought to store the raw data in the component, but if I use a 3rd party graphics library (such as Ogre3D or Irrlicht), then I require to actually create the Mesh data via another object.

So, the summed up question is: what's the best way to reduce duplicate data, using an Entity System design, in your game?

Would I have to re-make everything from scratch so that it just "fits" in my entity-system? I'd prefer not to do that, especially if I decide to change the design pattern that I use to make games.

# Answer
> 4 votes
It's typical than an Entity System will duplicate some data.

Some solutions I've seen is that the Position component contains a transform representing the world position & orientation of the entity. The renderable component has a reference to the position component, as does the physics component. In other designs, the renderable system and physics systems connect to signal emitters on the transform component or register for some event/message notification when the position is modified.

When such a signal/callback/notification fires, the renderable and physics components both update their internal state by copying the vector from the position component.

By duplicating the data, you eliminate coupling, can avoid using pointers which often can be a source of bugs if a dangling pointer isn't cleaned up and has some benefits to potential running various updates in parallel without contention (ie: can run physics while rendering allowing physics to update the position but the rendering can render to the old location until its safe for the renderable to update its position value).

Also keep in mind that you may be creating the position component first. If you expect your position component to have a scene node or sprite position pointer but you haven't created the renderable component yet to allocate a scene node or a sprite component to create a sprite object, then you have no pointer you can yet reference. Now you've imposed a dependency order needed on creating & adding components to entities. I generally prefer to avoid this and have some dependency check system in place when adding components that allow them to link up as they need in a special init phase for an entity.

Lastly, there is nothing stopping you from creating a Mesh component that allows you to

* Specify the filename for the mesh to load and use.
* Specify the data buffer needed to render the mesh

Whatever code examines the mesh components can check to see what values were provided and based on them, decide how to decode the component data for rendering.

In our engine, we have the ability to specify a list of skins that a mesh can use. By selecting a particular skin, the appropriate mesh is rendered. For mesh components where there is only one skin, the list simply has a single value. If we need something specialized, we have a choice: new component or modify an existing component if it makes sense to do so.

---
Tags: c++, entity-system, memory-efficiency, data, data-oriented
---


# Question
Title: Entity systems with mixed responsibilities (eg render + handle input)
I am using an entity system for my hobby game, specifically the Behaviour / Attribute model discussed in Radical Entertainment's Theory and Practice of Game Object Component Architecture presentation.

I have read discussions of this model here and here and I believe I understand it except for a specific case:

Say I am developing a top-down game that has has multiple units (entities) on screen. Each unit can be selected, which outlines the unit with a green box. Think Starcraft, where you can select units and then issue an order.

At the moment I have the classic `RenderBehaviour` which simply draws the entity. I now want to add a `SelectableBehaviour`. The SelectableBehaviour will have "logic" responsibilities such as ensuring the unit can be selected, deselecting the unit under certain circumstances (death events), etc.

My problem, essentially, is **who is responsible for drawing the green outline around the unit when it is selected - the render behaviour, or the selectable behaviour?**

I am trying to follow what the presentation says, which is that Behaviours should be very generic in their responsibilities. If possible I **do not** want to add code into the `RenderBehaviour` that says "if entity has selectable behaviour" because now my behaviour is no longer generic - in fact, this exact scenario is mentioned on slide 16 of the presentation (but it just says "don't do it").

I am basically being mindful of mixing "presentation with logic". The only thing I can think of at the moment is to have another behaviour that is responsible for rendering the select box.

I understand there are no hard and fast rules regarding entity systems but I am curious to hear how this can be handled neatly.

# Answer
> 4 votes
The specifics of a component-based system or even entity system have little to do with the answer to this question.

A renderer takes data describing the renderable objects in your scene, culls the ones not currently visible to the camera, and then submits the necessary drawing commands to the GPU to visualize the scene.

The key part of that is "data describing the renderable objects." If you have selection indicators of some kind around an object, you create a new renderable object representing that indicator. You have a mesh or particle effect to represent selection. You do not change the selected object to be selected, but rather create a second object at the same position that is the selection.

If your engine supports parenting (attaching one object to another), you would do this by letting your selection behavior create the child object when the unit becomes selected and then destroying the selection object when the unit is deselected.

The rendering hence has zero logic involved about rendering selections, when to render selections, how to render selections, or so on. The renderer just renders all renderable objects. When a unit is selected, there is a new renderable object, so the renderer naturally renders that new object. When the unit is deselected, that goes away, and the renderer stops drawing it. Absolutely no new logic involved in at all anywhere involving graphics.

Note also that no behavior is responsible for rendering anything. That is not how a properly architected efficient modern GPU-accelerated graphics engine works. It is purely data-driven. The behavior *cannot know* how to properly render anything, because the behavior is not running with all the knowledge the renderer has internally. The behavior does not know how to batch geometry. The behavior does not know how stream in content or control LOD. The behavior does not know how to optimize particles vs static objects vs skinned meshes. The behavior does not know how or when to sort translucent objects vs opaque objects. The behavior at absolute best can just submit a work item to the render queue for a specific mesh/material/shader, which in turn is exactly what creating a new object with a renderable component does (because every renderable component in the scene is implicitly a work item in the render queue each frame).

If you need actual line drawing around units rather than a (much nicer looking) textured quad or particle effect, simply create some new renderable components for representing bounding boxes. Again letting the renderer properly optimize those by batching together all the visible bounding boxes into a single line batch for the GPU.

# Answer
> 2 votes
I would follow Sean's advice and consider a separate entity for this type of renderable effect. You simply attach this new entity as a child to the avatar entity when a selection occurs and remove it when the selection stops. We do similar things like this for highlight/hover effects as well.

In fact since you can only highlight/target a single object at a time in gameplay mode, we preallocate those special entities when the world gets initialized. They are merely hidden until needed. Once needed, they get attached to the right parent, visibility flag toggled. To remove, just detach, set not visible.

---
Tags: entity-system
---


# Question
Title: Is C++ here to stay for at least a decade more?
C++\DX\OpenGL is the best bet for creating video games and game engines.

Will C++ mantain its spot as the industry standard in the future?

# Answer
> 5 votes
First: Game Industry is moving really, really slow. It's a huge (financial sense) industry, so there are always many people against everything which is new/unknown/maybe smarter than them and/or no competitor uses it and/or no projects are known which were successful using this new stuff. some kind of catch-22.

Second: Performance matters. Way (!) more than in other development areas. So, a possible successor of C++ must be at least as fast as C++. Also, to compensate the massive amount of RAD-Tools for C++ Game development, the new thing must boost productivity as much as ruby/rails did in in the web-development world.

Third: crossplatform. In the last months, Microsoft lost credit in every area. Blizzard doesn't like Windows 8. Steam moves in giant steps to Linux, in collaboration with eg.: nVidia, the new Steambox will run on top of Linux. Microsoft even started dropping development of some of their core technologies, starting with Silverlight. The amount of OS X Users increases steadily. And in the future, the biggest selling points will probably be the tablet/"smart"phone-market. In this cluttered market you have many Operation Systems and derivates to handle simultanly. C++ is quite nice for crossplatform development, since it "just" needs a compiler on/for the target system.

So: "the next big thing" is not here today. C++ just works fine. The next thing has to fulfill all the 3 points above and must be somewhat different from C++, because people don't switch just for a small gain (development/re-learning time matters, too).

# Answer
> -6 votes
**Hell Yep, Buddy!!**

(now fire up your MS VS!!)

:)

---
Tags: c++
---


# Question
Title: Confusing with an articles wording on Clamping a Vector2
I have been reading an article on Collision Detection and how to resolve it.

http://www.wildbunny.co.uk/blog/2011/04/20/collision-detection-for-dummies/

In the section describing an AABB vs Circle, it states:

> The first step is to get the centre of the circle and project it on to the boundary of the AABB. Fortunately this is as easy as forming the vector V between AABB and circle and simply clamping it against the half extents of the AABB.

In the picture provided, it makes sense. You get the vector between the two objects, and then get the closest virtice to the circle and use that in your computation.

But, how DO you take the width/height into account to that new vector? He says "..simply clamping it against the half extends of the AABB"

Can anyone clarify what he means?

# Answer
> 3 votes
A clamp (or saturate) is constraining a value to be within a range of values, that is:

`v' = max(low, min(high, v))`

In this case, he wants you to clamp each component of the vector to the corresponding min/max on that axis.

```
x = max(-halfWidth,  min(halfWidth, circleX-boxX))
y = max(-halfHeight, min(halfHeight, circleY-boxY))

```

This will yield a point on the boundary of the box if the circle center is outside the box, or a point inside the box if the circle is inside.

By doing this, you can treat the box as a circle centered at the box center, with the circumference going through that point.

---
Tags: collision-detection, vector, collision-resolution
---


# Question
Title: Pygame performance issue for many images
I've made a script for generating a game world based off of image pixel data.

Trying to make a python map editor

My progress so far has resulted in a program which loads an image and draws sprites in positions correlating with the map, like this:

Now the problem is that even for small levels, I'm noticing a drop in frame rate. The provided example level will make pygame drop from 100 fps to 80 fps. If the map is 40 x 40 the frame rate will be around 17.

This is concerning, for two reasons. The program is not doing anything else than drawing images right now, how bad will the frame rate be when game logic is also being calculated every frame? Second, the aim is to ultimately make a two-player strategy game, in which the levels would be significantly larger than the example, and in that case 20 frames per second is way below acceptable parameters.

Every sprite in the game is a 48x48 pixel png image with some portion of transparency. Everything except rendering the sprites is done once when the game starts. This is the only code being run on every frame:

```
    def draw(self):
    self.screen.fill((0,0,0))

    for e in self.map_layout.fixed_list:
        self.screen.blit(e.picture, e.rect)

```

I'm guessing pygame's method for rendering images does not scale very well. Windows task manager shows my CPU utilisation at 2% with a map of size 40x40.

My question is: What can I do to improve frame rate? I don't mind switching from (or complementing) pygame to something else, so long as the transition is not very difficult for a novice programmer like myself.

# Answer
> 2 votes
I was able to significantly improve frame rate by changing the code so that every tile displays a sprite generated from a texture atlas, instead of blitting a separate png to the display surface for every tile.

I based the code on aquasheep's improved spritesheet function, found in this stackoverflow entry.

When previously a 40x40 map would bring the frame rate down from 100 to 17, a map of the same size now has ~90 fps. This is still far from optimal though, as a map of size 127x127 (desired standard size) will have a frame rate of just under 40.

I am still looking for a way to replace pygame for the purpose of rendering, or to make the algorithm at least twice as fast.

---
Tags: rendering, python, image, pygame
---


# Question
Title: ObjectDisposedException when Texture2D isn't disposed
I'm making a particle engine so I develop a texture programatically and I want to display it in a Windows Form picture box. So I create the Texture2D which goes fine. Then I use this code to convert from a Texture2D to an Image for the picture box.

```
    public static System.Drawing.Image Texture2Image(Texture2D texture)
    {
        if (texture.IsDisposed)
        {
            return null;
        }

        MemoryStream memoryStream = new MemoryStream();

        texture.SaveAsPng(memoryStream, texture.Width, texture.Height);

        memoryStream.Seek(0, SeekOrigin.Begin);

        System.Drawing.Image image = System.Drawing.Bitmap.FromStream(memoryStream);

        memoryStream.Close();
        return image;
    }

```

I get the error at the texture.SaveAsPng(...). It says 'Cannot access a disposed object. Object name: 'Texture2D'.'
But as you can see, I just checked to make sure it wasn't disposed. I looked at the Locals info which also says the IsDisposed flag is false. No where in my code to I call texture.Dispose() or anything of the sort. I have no idea where this error is coming from. Any help would be greatly appreciated, thanks in advance.

# Answer
> 7 votes
This is a bit of an oddity in the way XNA works - you could even call it a bug in XNA.

**Basically there are two ways that `Texture2D` can decide that it has been "disposed":**

First of all, there's the normal, managed way - when you call `Dispose` \- that sets the `IsDisposed` flag and also unloads the native texture.

And then there's the wacky, native, internal, DirectX, *magic* way. Basically when the graphics device is "lost" (for example: the user minimises the window, or locks their session) the native objects that back textures (and other `GraphicsResource`s) are invalidated. XNA clears them out and will attempt to recreate them when the graphics device is available again. It is possible for this recreation to fail - or you could be trying your operation while the device is lost, before they are recreated.

The bug in XNA is that operations on `Texture2D` check for the existence of the native texture, throwing `ObjectDisposedException` if it is not available. However this second way of losing the native texture *does not set the `IsDisposed` flag!*

(While it is arguably the wrong exception type, there's not much XNA can do in this case other than throw an exception - so it's not really a major bug. I can see why the XNA team might have not put in the effort to differentiate between the two cases.)

So, it's likely that the device your texture is on has been lost when you attempt to save it. If it's not something expected (like a minimised window) - and given that you're working with `System.Drawing` \- I wonder if you're messing about with the `GraphicsDevice` that the `Texture2D` is bound to?

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


# Question
Title: How does this background scrolling code work?
I'm glad that this code does exactly what I wanted it to do...But I can't make sense of it although I wrote it from scratch myself. What I wanted to do was create an infinitely scrolling background.

What I figured I'd need to do was have it draw the entire background twice so that the second one comes in after the first one, and when the first one gets to the end it starts over behind the second one, and it would loop like this forever. However, after I wrote the code to make it scroll and tested it, it scrolls infinitely by just having the code draw the background once...

I have the function to draw the background like so...

```
void drawBackground(int xStart,int yStart,SDL_Rect *clip) {
  int x,y;
  for(y=yStart;y<SCREENH;y=y+TILEH) {
    for(x=xStart;x<SCREENW;x=x+TILEW) {
      drawClip(x,y,background,&clip[45]);
    }
  }
}

```

And then I use the function like this to scroll the background...

```
bgX -= 1;
if(bgX==SCREENW) bgX=0;
bgY -= 1;
if(bgY==SCREENH) bgY=0;

drawBackground(bgX, bgY, bgClip);

```

It works perfectly...I just don't understand what makes it loop around with no gaps.

# Answer
There's actually a bug in your second code sample: assuming that `SCREENW` and `SCREENH` are positive, the `if` statements will never succeed and your `bgX` and `bgY` will just keep getting more and more negative. (Well, until they wrap around, anyway, which could take a while.)

Why does it still work, then? Well, you're drawing the tile repeatedly from `bgX` up to `SCREENW` and from `bgY` up to `SCREENH`. Presumably, your `drawClip()` function ignores attempts to draw outside the screen, so only the parts of the tiles that visible on the screen get drawn, and those parts *are* enough to cover the entire screen.

That said, if you left the code running for long enough, it would probably start to get slower as it wasted more and more time calling `drawClip()` for tiles that are entirely outside the screen.

So, how should you fix the bug, then? Well, `bgX` and `bgY` clearly must never be greater than zero, otherwise part of the screen would not be drawn. There's also no point in trying to draw tiles that are entirely outside the screen, which happens whenever `bgX <= -TILEW` or `bgY <= -TILEH`, so your code should look like this:

```
bgX -= speedX;
bgY -= speedY;

while (bgX > 0) bgX -= TILEW;
while (bgY > 0) bgY -= TILEH;
while (bgX <= -TILEW) bgX += TILEW;
while (bgY <= -TILEH) bgY += TILEH;

```

(Ps. I used `while` instead of `if` just to make sure that `bgX` and `bgY` end up in the valid range even in the unlikely case that the background movement speed exceeds one tile width/height per frame. It probably won't make any practical difference, but it's generally better to play it safe anyway. Of course, if you really were expecting such high movement speeds, you should rewrite this to use the `%` operator instead.)
> 2 votes

# Answer
I'll explain it in one dimension only (the same is true for the other one):

```
for(x=xStart;x<SCREENW;x=x+TILEW)

```

This will start on the left border of the screen (or a bit outside depending on your bgX offset). It will then loop till the new drawing position is outside the screen (i.e. passed the right border of the screen; once the full line is drawn).

Just to note: you shouldn't wrap your offsets based on screen width/height (as these might not necessarily be multiples of your tile width/height). Usually you'd use the tile width/height so wrapping isn't noticeable and you don't draw too much outside the visible area.
> 4 votes

---
Tags: sdl, c
---