# Question
Title: Why does the player jitter when it moves between tiles?
I have just implemented a 2D player camera for my game, everything works properly except the player on the screen jitters when it moves between tiles. What I mean by jitter, is that if the player is moving the camera updates the tileset to be drawn and if the player steps to the right, the camera snaps that way. The movement is not smooth.

I'm guessing this is occurring because of how I implemented the function to calculate the current viewable area or how my draw function works.

I'm not entirely sure how to fix this. This camera system was entirely of my own creation and a first attempt at that, so it's very possible this is not a great way of doing things.

My camera class, pulls information from the current tileset and calculates the viewable area. Right now I am targeting a resolution of 800 by 600. So I try to fit the appropriate amount of tiles for that resolution. My camera class, after calculating the current viewable tileset relative to the players location, returns a slice of the original tileset to be drawn. This tileset slice is updated every frame according to the players position.

This slice is then passed to the map class, which draws the tile on screen.

```
//Map Draw Function
//This draw function currently matches the GID of the tile to it's location on the
//PNG file of the tileset and then draws this portion on the screen
void Draw(SDL_Surface* background, int[] _tileSet)
{
  enforce( tilesetImage != null, "Tileset is null!");
  enforce( background != null, "BackGround is null!");
  int i = 0;
  int j = 0;
  SDL_Rect DestR, SrcR;

  SrcR.x = 0;
  SrcR.y = 0;
  SrcR.h = 32;
  SrcR.w = 32;

  foreach(tile; _tileSet)
  {
                      //This code is matching the current tiles ID to the tileset image
    SrcR.x = cast(short)(tileWidth * (tile >= 11 ? (tile - ((tile / 10) * 10) - 1)  : tile - 1));
    SrcR.y = cast(short)(tileHeight * (tile > 10 ? (tile / 10) : 0));

                       //Applying the tile to the surface
    SDL_BlitSurface( tilesetImage, &SrcR, background, &DestR );

                        //this keeps track of what column/row we are on
    i++;
    if ( i == mapWidth )
    {
      i = 0;
      j++;
    }
    DestR.x = cast(short)(i * tileWidth);
    DestR.y = cast(short)(j * tileHeight);

  }
}

```

Camera Class

```
class Camera
{
private:
  //A rectangle representing the view area
  SDL_Rect viewArea;

  //In number of tiles
  int viewAreaWidth;
  int viewAreaHeight;

  //This is the x and y coordinate of the camera in MAP SPACE IN PIXELS
  vect2 cameraCoordinates;

  //The player location in map space IN PIXELS
  vect2 playerLocation;

  //This is the players location in screen space;
  vect2 playerScreenLoc;

  int playerTileCol;
  int playerTileRow;

  int cameraTileCol;
  int cameraTileRow;

  //The map is stored in a single array with the tile ids
  //this corresponds to the  index of the starting and ending tile
  int cameraStartTile, cameraEndTile;

  //This is a slice of the current tile set
  int[] tileSetCopy;

  int mapWidth;
  int mapHeight;

  int tileWidth;
  int tileHeight;

public:
  this()
  {
    this.viewAreaWidth    = 25;
    this.viewAreaHeight    = 19;

    this.cameraCoordinates  = vect2(0, 0);
    this.playerLocation    = vect2(0, 0);

    this.viewArea = SDL_Rect (0, 0, 0, 0);

    this.tileWidth = 32;
    this.tileHeight = 32;
  }

  void Init(vect2 playerPosition, ref int[] tileSet, int mapWidth, int mapHeight )
  {
    playerLocation = playerPosition;
    this.mapWidth = mapWidth;
    this.mapHeight = mapHeight;

    CalculateCurrentCameraPosition( tileSet, playerPosition );

    //writeln( "Tile Set Copy: ", tileSetCopy );
    //writeln( "Orginal Tile Set: ", tileSet );
  }

  void CalculateCurrentCameraPosition( ref int[] tileSet, vect2 playerPosition )
  {
    playerLocation = playerPosition;

    playerTileCol = cast(int)((playerLocation.x / tileWidth) + 1);
    playerTileRow = cast(int)((playerLocation.y / tileHeight) + 1);

    //writeln( "Player Tile (Column, Row): ","(", playerTileCol, ", ", playerTileRow, ")");

    cameraTileCol = playerTileCol - (viewAreaWidth / 2);
    cameraTileRow = playerTileRow - (viewAreaHeight / 2);

    CameraMapBoundsCheck();

    //writeln( "Camera Tile Start (Column, Row): ","(", cameraTileCol, ", ", cameraTileRow, ")");

    cameraStartTile = ( (cameraTileRow - 1) * mapWidth ) + cameraTileCol - 1;

    //writeln( "Camera Start Tile: ", cameraStartTile );

    cameraEndTile = cameraStartTile + ( viewAreaWidth * viewAreaHeight ) * 2;

    //writeln( "Camera End Tile: ", cameraEndTile );

    tileSetCopy =  tileSet[cameraStartTile..cameraEndTile];
  }

  vect2 CalculatePlayerScreenLocation()
  {
    cameraCoordinates.x = cast(float)(cameraTileCol * tileWidth);
    cameraCoordinates.y = cast(float)(cameraTileRow * tileHeight);

    playerScreenLoc = playerLocation - cameraCoordinates + vect2(32, 32);;

    //writeln( "Camera Coordinates: ", cameraCoordinates );
    //writeln( "Player Location (Map Space): ", playerLocation );
    //writeln( "Player Location (Screen Space): ", playerScreenLoc );

    return playerScreenLoc;
  }

  void CameraMapBoundsCheck()
  {
    if( cameraTileCol < 1 )
      cameraTileCol = 1;

    if( cameraTileRow < 1 )
      cameraTileRow = 1;

    if( cameraTileCol + 24 > mapWidth )
      cameraTileCol = mapWidth - 24;

    if( cameraTileRow + 19 > mapHeight )
      cameraTileRow = mapHeight - 19;
  }

  ref int[] GetTileSet()
  {
    return tileSetCopy;
  }

  int GetViewWidth()
  {
    return viewAreaWidth;
  }
}

```

---

Along with the Palindromes helpful response, I found that my bug was because I was calculating the camera coordinates in terms of tiles instead of pixels which caused the irregular motion.

# Answer
lazyfoo has some really great tutorials, and this is what I found:

If dot is whatever you are drawing:

```
apply_surface( x - camera.x, y - camera.y, dot, screen );

```

where apply\_surface blits to the SDL apply\_surface thingy...

Really, the camera is just an SDL\_Rect with height being the screen height, width being screen width, and x and y just being the offsets...

This is the code from the scrolling tutorial, I didn't make this!

```
//Center the camera over the dot
camera.x = ( x + DOT_WIDTH / 2 ) - SCREEN_WIDTH / 2;
camera.y = ( y + DOT_HEIGHT / 2 ) - SCREEN_HEIGHT / 2;

//Keep the camera in bounds.
if( camera.x < 0 )
{
    camera.x = 0;
}
if( camera.y < 0 )
{
    camera.y = 0;
}
if( camera.x > LEVEL_WIDTH - camera.w )
{
    camera.x = LEVEL_WIDTH - camera.w;
}
if( camera.y > LEVEL_HEIGHT - camera.h )
{
    camera.y = LEVEL_HEIGHT - camera.h;
}

```

simple stuff, isn't it?

If you ask me, the SDL\_Rect idea is much better than having a class, and it is incredibly smooth.

if you want something that 'doesn't move with the camera' i.e. a **house**, just do this:

```
apply_surface(x,y,sprite,screen, &camera);

```

where the extra function is calls this:

```
SDL_BlitSurface( source, clip, destination, &offset );

```

and the function definition is this:

```
apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect *clip)

```
> 1 votes

---
Tags: 2d, camera, sdl
---


# Question
Title: How to make a gaussian blur effect in UDK
I want to make a plane shape (surface) that have a gaussian blur applied to it and this plane is transperant, so all objects behind it looks like they are having a gaussian blur effect.

# Answer
> 1 votes
The pros at Polycount have a good discussion of this topic, as well as how to achieve related effects such as frosted or textured transparent materials.

The long and short of it is, take a look at the material's distortion input.

---
Tags: udk, unreal, blur, shaders
---


title: glColor3f Setting colour

text:
# Question
Title: glColor3f Setting colour
This draws a white vertical line from 640 to 768 at x512:

```
glDisable(GL_TEXTURE_2D);
glBegin(GL_LINES);
      glColor3f((double)R/255,(double)G/255,(double)B/255);
      glVertex3f(SX, -SPosY, 0); // origin of the line
      glVertex3f(SX, -EPosY, 0); // ending point of the line
glEnd();
glEnable(GL_TEXTURE_2D);

```

This works, but after having a problem where it wouldn't draw it white (Or to any colour passed) I discovered that disabling GL\_TEXTURE\_2D Before drawing the line, and the re-enabling it afterwards for other things, fixed it. I want to know, is this a normal step a programmer might take? Or is it highly inefficient? I don't want to be causing any slow downs due to a mistake =)

Thanks

# Answer
> 2 votes
Yes, this is extremely common. A major problem a lot of people face is an unbound texture being applied to a line accidentally, or having GL\_TEXTURE\_2D enabled, but without a texture, in which case the line is always drawn black (no texture = black = 0, (black(0) * given color = black(0))

There is nothing inefficient as such with your code, though it is usually a wise choice to try to avoid switching unnecessarily. (eg. if you were to have to draw another line as well, don't constantly enable/disable, instead do it all in between one disable and enable).

Hope this helped.

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


# Question
Title: Creating natural environments that can run on lower end computers in Unity3D/C#
So, I'm starting work on a project soon that will require me to create realistic environments that can preferably run on PC's besides high quality ones. The goal is to get as real an environment as possible while still being easy(ish) to run.

The only problem is I've NEVER done anything with 3D environments, making trees sway, grass move, lighting, etc. Can anyone give me any help? Perhaps describe how it's done? Link me to articles? I'm just looking to be pointed in the right direction, not for you to write the code for me.

Any help at all would be greatly appreciated, I'm using Unity3D and C# as my language.

Thanks,

Tim.

# Answer
> 0 votes
> 3D environments

You can sculpt the basic ground terrain with Unity's Terrain tool, but beyond that you need to model complex objects in a 3D modelling program, then import them into Unity and place them within a scene. How to do 3D modelling is beyond the scope of a question like this. Alternatively you can sometimes buy the models pre-made from the Unity Asset Store.

> making trees sway, grass move

Unity can do this for you, if you place trees and grass with the Unity terrain editor. There are various parameters to let you specify how much you want things to sway. This requires you to place 'wind zones' in the level.

> lighting

Lighting is as complex or as difficult as you want. To get started you can make sure all objects have shadows turned on, then add one directional light for the sun (make it yellowy-white) and then add an ambient light to lighten the shadows. It won't win any prizes but it's a reasonable starting point. More realistic lighting can use a variety of different tricks, such as multiple directional lights, lightmaps, ambient occlusion, more complex shaders, etc etc - which to use and how would be a question in itself.

# Answer
> 0 votes
One of the easiest performance balance tricks is to limit the visible distance of older machines with fog and use of billboards. If you have a high end PC you can have all the trees be actual 3d objects, but by having a check in your software, such as which shader level is available, on an older machine that is using an older shader API, you can set your engine to that the trees closest to the player(of the older PC) are 3D, the trees in a mid-range area are billboards (two images of the same tree configured in a perpendicular pattern "a cross", to give the illusion of a 3D tree using 2 static images), and the trees in the background could be incorporated into your sky-box texture. Then start using the fog effect on your mid-range billboard trees. It will give the appearance of the engine the high end PC will see but reduce the shadow and light calculation processing that would bog down an older machine. As for movement in trees and grass, remember that those conditions should only occur within the player's line of sight (if the player can't see it - your not required to display or calculate it.)

---
Tags: c#, unity
---


# Question
Title: What is the best way to code the XNA gameserver for an FPS game?
I'm writing an FPS XNA game. It is going to be multiplayer, so I came up with the following:

1. I'm making two different assemblies — one for the game logic, and one for drawing it and the game irrelevant stuff (like rocket trails).
2. The type of the connection is client-server (not peer-to-peer), so every client connects to the server, and then the game begins.
3. I have decided to use the `XNA.Framework.Game` class, for the clients to run their game in window (or fullscreen), and the `GameComponent`/`DrawableGameComponent` classes, to store the game objects, update, and draw them on each frame.

---

What should I do on the server side? I got few options:

1. Create my own `Game` class on the server, which will process all the game logic, without graphics. I am not using the standard `Game` class because, when I call `Game.Run()`, the white window appears and I cant figure out how to get rid of it.
2. Somehow, use the original XNA `Game` class, which already has the `GameComponent` collection and Update event (60 times per second, just what I need).

---

I have additional questions:

First, what socket mode should I use? TCP or UDP? How do I actually let the client know the order in which packets are meant to be processed?

Second, if I am going to use the exact `GameComponent` class for the game objects, which are stored and processed on the server, how do I get them to draw on the client side? Should I inherit them, while they are combined in an assembly), or something else?

# Answer
> 2 votes
I'm not qualified to answer your XNA-network specific questions. However, I can recommend you this great article about TCP/UPD for games which is not XNA specific.

I'll summarize below as best as I could in the context of your question.

In short:

Timing is crucial in an FPS game, you want **packets** to be sent across as fast as possible. **Use UDP**, it gives you more control over individual packets and is much faster than TCP on average which exposes networking interface as **streams** rather than packets.

Long explanation:

TCP guarantees order/arrival of packets, but abstracts away the logic to break up your data into packets. However, this introduces latency if you attempt to send small amounts of data, it may get clumped up by TCP into 1 packet of "reasonable" size and then sent. Also for packet loss, TCP simply wait/re-send the data, this will block execution of the game and cause lag. Therefore, you need control over individual packets and should use UDP which is more low level; it gives you control over processing each packet and lets you handle what size of packet/packet loss/ordering yourself (more work for you of course).

One way to deal with ordering of course is to time-stamped the packets you send and do appropriate checking on both sides. For more info, you can refer to the rest of his series at bottom above comments of this article about Networked Phyiscs. He wrote a series on how to handle networked games with UDP including how to implement virtual connections which you'll be interested in.

Now, his articles are not framework specific and talk about fundamental concepts which you probably should be familiar with. However, I'm sure that there exist some game specific networking frameworks to aid you (do some googling perhaps?). Perhaps someone else will give you some recommendations.

---
Tags: xna, client-server
---


title: Using virtual functions

text:
# Question
Title: Using virtual functions
I am starting to use virtual functions, and i am programming a simple text game, my question is this, if i have a virtual function called spec\_abil with in a Super class called rpg\_class. If you allow the player to class what class they want to play, say a mage class, a archer class, and a warrior class, which all have their own spec\_abil function. How do you write it so that the program knows which one to use depending on the chosen class.

# Answer
> 4 votes
It's automatic as long as you're calling the virtual method through a *pointer* or *reference* to your base class - that's the beauty of polymorphism! So to give a typical example using pointers, imagine you had these three classes:

```
class rpg_class
{
public:
    virtual void special_ability() { cout << "Generic ability"; }
}

class mage : public rpg_class
{
public:
    void special_ability() { std::cout << "Mage ability"; }
}

class warrior : public rpg_class
{
public:
    void special_ability() { std::cout << "Warrior ability"; }
}

```

The following example would automatically work:

```
std::vector<rpg_class*> characters;
characters.push_back(new mage());
characters.push_back(new warrior());
characters[0]->special_ability();   // Prints "Mage ability"
characters[1]->special_ability();   // Prints "Warrior ability"

```

And it works because the vector is storing *pointers* to the base class (i.e. `rpg_class*` instead of simply `rpg_class`).

*PS: You might also want to consider using a smart pointer such as `std::unique_ptr` if your compiler supports it instead of a regular pointer, as this will free you from having to delete your objects explicitally. All smart pointers are also made to work under polymorphism afaik.*

# Answer
> 2 votes
Declaring a method as virtual in a base class causes the compiler to introduce a hidden pointer into objects of this class (and its derived classes). This is the `vfptr`, the pointer to the `vtable`. This pointer and table can be absent in classes that do not declare any virtual methods. The vtable holds the addresses of the correct methods to call. There is one vtable per class. When an object is constructed, its vfptr is set to point to the appropriate vtable in order to make this all work. All virtual method calls are indirectly looked up in this vtable to provide the polymorphism. Therefore, determining which method to call takes place at *run time*, not compile time or link time.

You must be aware of how virtual methods work in order to use them safely. I recommend further reading, inclusing virtual destructors (very important).

Polymorphism can be exploited with or without pointers, using dynamically allocated objects or automatically cleaned up objects. References can be used instead of pointers:

```
class BaseClass {
public:
   virtual void fn() {
      printf("Base::fn()\n");
   }
};

class Derived1 : public BaseClass {
public:
   virtual void fn() {
      printf("Derived1::fn()\n");
   }
};

class Derived2 : public BaseClass {
public:
   virtual void fn() {
      printf("Derived2::fn()\n");
   }
};

void useRef(BaseClass& b) {
   b.fn();
}
void usePtr(BaseClass* pb) {
   pb->fn();
}
void testVirtuals() {
   Derived1 d1;
   Derived2 d2;
   useRef(d1);
   useRef(d2);
   usePtr(&d1);
   usePtr(&d2);
   Derived2* pd2Dynamic = new Derived2();
   usePtr(pd2Dynamic);
   delete pd2Dynamic;
}

```

Produces this output:

```
Derived1::fn()
Derived2::fn()
Derived1::fn()
Derived2::fn()
Derived2::fn()

```

Caveat for beginners: beware the subtle differences in the use of pointers and references. Best to learn pointers exclusively first I would think.

---
Tags: c++
---


# Question
Title: Can't use the hardware scissor any more, should I use the stencil buffer or manually clip sprites?
I wrote a simple UI system for my game. There is a clip flag on my widgets that you can use to tell a widget to clip any children that try to draw outside their parent's box (for scrollboxes for example). The clip flag uses glScissor, which is fed an axis aligned rectangle. I just added arbitrary rotation and transformations to my widgets, so I can rotate or scale them however I want. Unfortunately, this breaks the scissor that I was using as now my clip rectangle might not be axis aligned.

There are two ways I can think of to fix this: either by using the stencil buffer to define the drawable area, or by having a wrapper function around my sprite drawing function that will adjust the vertices and texture coords of the sprites being drawn based on the clipper on the top of a clipper stack. Of course, there may also be other options I can't think of (something fancy with shaders possibly?). I'm not sure which way to go at the moment.

Changing the implementation of my scissor functions to use the stencil buffer probably requires the smallest change, but I'm not sure how much overhead that has compared to the coordinate adjusting or if the performance difference is even worth considering.

# Answer
> 1 votes
Since your sprites can rotate, clipping them manually won't be as easy as just moving your vertices and texture coordinates around. There are many cases where you'd actually need to replace a single vertex with two new vertices. But by doing so your primitive would stop being a triangle so you'd also need to triangulate the result, which is not simple. Check the following image for a clearer view:

So in the end, that entire processing might even be more expensive than using the stencil buffer (haven't tested though). So my advice for now would be to try using the stencil buffer first, and if it turns out to work well enough, don't give it a second thought.

# Answer
> 1 votes
> Of course, there may also be other options I can't think of (something fancy with shaders possibly?). I'm not sure which way to go at the moment.

I hope I can help here, however Disclaimer: I don't know much about OpenGL, if anything. In DirectX I'd do this as a a user clip plane (dx9) or a ClipDistance (dx10+). They're both identical concepts and I *know* that OpenGL has identical concepts, however I'm not sure what they are so I'm just gooling randomly to fill this answer out. Hopefully this answer helps you start looking for them :)

If the version of OpenGL/GLSL you're targeting supports gl\_ClipDistance, you could use those. You need to use 4 planes to define the box that you previously used a scissor for. The clip planes don't even have to be axis aligned, which is a plus point. Hopefully you can just define them to be the same as your previous scissor-rect and then just use the same rotations you did to the gui element to orientat the rects to be exactly the same?

Once you have 4 clips planes describing your clip-box you need to pass them into the vertex shader as 4 vec4 uniforms. You then find the distance between your vec4 position value and the 4 planes. (The clip plane coordinates will obviously need to be in world or clip space depending upon where you do the calculation in regards to your matrix transforms, if you even have any for gui elements. Infact if you do the gui-element's rotation in the vertex shader, you could even do the clip-plane's rotation here using the same rotation matrix?)

IIRC the distance between a point and a plane is just a dot product? Assuming it is, the 4 dot products will give you 4 scalar values, and these are the distances from the 4 planes, aka the 'clip distance'. The HW clips any edge that has an interpolated value \<0. So if you have 2 verts, A and B, with a single per-Vertex clipDistance element whose value is -1.0f at A and 1.0f at B, then the HW automagically clips it for you at new position C, which will be halfway between the two :) David Gouveia's diagram above has a nice diagram reflecting this.

Hopefully you can output 4 clipplanes (the documentation refers to gl\_MaxClipDistances, but I don't know how to look up a standard value for this. I hope you do :)). If not you can just accumulate the previous values, remembering that any value \<0 would result in clipping.

There's also glClipPlane. That might be fixed function -- again, I know nothing about OpenGL. But it basically does the dotproduct for you and outputs the clipDistance itself, I hope. At least that's how the analgous DX functions work. SetClipPlane ClipDistance

# Answer
> 0 votes
I have done a stencil approach to that problem and runs fine...

Is done with Xna but it should be done in a similar way with opengl...

Clipping polygons in XNA with stencil (not using spritebatch)

http://www.youtube.com/watch?v=-xUMC7sPAx0

---
Tags: opengl, gui
---


# Question
Title: Per-vertex position/normal and per-index texture coordinate
In my game, I have a mesh with a vertex buffer and index buffer up and running. The vertex buffer stores a Vector3 for the position and a Vector2 for the UV coordinate for each vertex. The index buffer is a list of ushorts. It works well, but I want to be able to use 3 discrete texture coordinates per triangle.

I assume I have to create another vertex buffer, but how do I even use it?

Here is my vertex/index buffer creation code:

```
// vertices is a Vertex[]
// indices is a ushort[]
// VertexDefs stores the vertex size (sizeof(float) * 5)

// vertex data
numVertices = vertices.Length;
DataStream data = new DataStream(VertexDefs.size * numVertices, true, true);
data.WriteRange<Vertex>(vertices);
data.Position = 0;

// vertex buffer parameters
BufferDescription vbDesc = new BufferDescription()
{
    BindFlags = BindFlags.VertexBuffer,
    CpuAccessFlags = CpuAccessFlags.None,
    OptionFlags = ResourceOptionFlags.None,
    SizeInBytes = VertexDefs.size * numVertices,
    StructureByteStride = VertexDefs.size,
    Usage = ResourceUsage.Default
};

// create vertex buffer
vertexBuffer = new Buffer(Graphics.device, data, vbDesc);
vertexBufferBinding = new VertexBufferBinding(vertexBuffer, VertexDefs.size, 0);
data.Dispose();

// index data
numIndices = indices.Length;
data = new DataStream(sizeof(ushort) * numIndices, true, true);
data.WriteRange<ushort>(indices);
data.Position = 0;

// index buffer parameters
BufferDescription ibDesc = new BufferDescription()
{
    BindFlags = BindFlags.IndexBuffer,
    CpuAccessFlags = CpuAccessFlags.None,
    OptionFlags = ResourceOptionFlags.None,
    SizeInBytes = sizeof(ushort) * numIndices,
    StructureByteStride = sizeof(ushort),
    Usage = ResourceUsage.Default
};

// create index buffer
indexBuffer = new Buffer(Graphics.device, data, ibDesc);
data.Dispose();

Engine.Log(MessageType.Success, string.Format("Mesh created with {0} vertices and {1} indices", numVertices, numIndices));

```

And my drawing code:

```
// ShaderEffect, ShaderTechnique, and ShaderPass all store effect data
// e is of type ShaderEffect

// get the technique
ShaderTechnique t;
if(!e.techniques.TryGetValue(techniqueName, out t))
    return;

// effect variables
e.SetMatrix("worldView", worldView);
e.SetMatrix("projection", projection);
e.SetResource("diffuseMap", texture);
e.SetSampler("textureSampler", sampler);

// set per-mesh/technique settings
Graphics.context.InputAssembler.SetVertexBuffers(0, vertexBufferBinding);
Graphics.context.InputAssembler.SetIndexBuffer(indexBuffer, SlimDX.DXGI.Format.R16_UInt, 0);
Graphics.context.PixelShader.SetSampler(sampler, 0);

// render for each pass
foreach(ShaderPass p in t.passes)
{
    Graphics.context.InputAssembler.InputLayout = p.layout;
    p.pass.Apply(Graphics.context);
    Graphics.context.DrawIndexed(numIndices, 0, 0);
}

```

How can I do this?

# Answer
> 3 votes
You don't need a separate vertex buffer, you can just put additional vertices in the same buffer. Rather than re-using vertices where faces meet, create a duplicate and set it's normal and texture coords to match the face that it belongs to.

---
Tags: c#, directx11, slimdx, vertex, index-buffer
---


# Question
Title: When should I be implementing XML documents
I often struggle with the question of when to use XML docs. Does anyone have a good rule of thumb when it comes to deciding to use them or deciding not to use them.

At the moment I am working on a project that has a lot of name, attributes, textures and even maps that are randomly selected when an object is created. Should I be harnessing XML here?

Thanks for your time!

# Answer
Short answer: when the benefit outgrows the effort.

Long answer: there's no long answer. You have to decide this yourself. You'll spend some time implementing, debugging and tweaking the XML system. Is it going to save you more time than you'll expend? Then do it.

Summing up: do I **really** need this part of the game to be data-driven?
> 5 votes

# Answer
To be up-front and fair: I'm not a big fan of XML for most purposes in games so take my advice with a grain of salt, please.

Regardless, there are some situations where you probably wouldn't want to use XML for your data:

* When document creation has to be carried out by humans. Stuff like attributes and balancing constants come to mind. It's a very wordy format and it takes quite a lot discipline on the part of the author to keep XML documents easily understandable and terse, if that is at all possible.
* When data storage does not need to be platform independent or backwards compatible, a binary format makes for simpler load/save code and shorter loading/saving times.
> 0 votes

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


title: box2d and constant movement

text:
# Question
Title: box2d and constant movement
i'm developing a game with a top down view, the players body is a circle. To move the character you need to tap on the screen and it moves to the spot.

To achieve this i'm saving the coordinate of the touch and call a method every frame which applies linear velocity to the body with a vector of the direction the body should go

```
_body->SetLinearVelocity(b2Vec2((a.x - currPos.x)/SPEED_RATIO,(size.height - a.y - currPos.y)/SPEED_RATIO));
//click position - current position, screen height - click position (since the y axis is flipped, (0,0) is in the bottom left ) - current position = vector of the direction we want to go

```

now the problem with this is that the body slows down until it finally stops when getting closer to the point we want it to go, since the closer we are to that point the lenght of the vector gets smaller. Besides that i've read that it's bad practice to set linear velocity in box2d and i should use apply force instead, but that way the forces would add up and overshoot the target where it's supposed to stop.

So what i'm asking is how to move a box2d body to a coordinate in constant speed.

# Answer
> 1 votes
> Besides that i've read that it's bad practice to set linear velocity in box2d and i should use apply force instead, but that way the forces would add up and overshoot the target where it's supposed to stop.

Setting the linear velocity isn't necessarily a bad thing. You just don't want it to jump around so doing things like clamping the velocity is perfectly fine.

Anyways to answer you question I would apply a force of a fixed magnitude pointing to the last contact point. I would also create a finger sized sensor and use the BeginContact and EndContact events.

In the BeginContact event I would set the dampening of the circle to a very large amount (large enough to prevent the circle from moving out from under the finger) and block the application of forces to the circle.

For the EndContact event reset the dampening and unset the flag that prevents the circle from accepting forces.

Also its perfectly fine to teleport sensors around. So feel free to set the position directly to wherever the finger presses the screen.

# Answer
> 1 votes
You DO want to use applyForce() or applyLinearImpulse instead of setLinearVelocity().

I would recommend using applyLinearImpulse() to apply an impulse proportional to the distance between your object and it's destination divided by it's speed each update. I used Java, so excuse my C++ errors(not sure if I use a dot operator or whatever -\> is), but it would be something like this:

```
applyLinearImpulse(b2Vec2((a.x-_body.getPosition().x)/SPEED_RATIO, (a.y-_body.getPosition().y)/SPEED_RATIO), _body.getWorldCenter());

```

# Answer
> 0 votes
I'm no expert on Box2D, but I think what you're looking for is dynamic friction or damping. Both of these will apply a counter-fource to the movement, so that, for a certain constant force, an equilibrium velocity is reached after an initial acceleration. I'm not sure if this is how Box2D models it, but in real physics dynamic damping is frequently modelled as proportional to current velolcity, so:

```
    acceleration = force - velocity * damping
 => 0 = force - maxVelocity * damping
<=> force = maxVelocity * damping
<=> damping = force / maxVelocity

```

You must then calculate a point from the target where you stop applying the force, so that the damping will decelerate it until it reaches the target.

# Answer
> 0 votes
If you're doing this on every frame and want no negative acceleration then why don't you just no take into concideration the length of the vector between origin and target?

sudo:

```
1. onTouchEvent(): capture coords
2. onRender():
     - Check if coordinates of body are on target yet
         - True: Remove all forces from body.
         - False: Apply force again(?)

```

Another method would be to remove all friction and damping on the body depending on if there's contact with any other bodies, and what the gravity of the world might be.

Straight from box2d manual:

> Damping
>
> Damping is used to reduce the world velocity of bodies. Damping is different than friction because friction only occurs with contact. Damping is not a replacement for friction and the two effects should be used together.Damping parameters should be between 0 and infinity, with 0 meaning no damping, and infinity meaning full damping. Normally you will use a damping value between 0 and 0.1. I generally do not use linear damping because it makes bodies look float

---
Tags: physics, box2d, movement
---


# Question
Title: Do unused vertices in a 3D object affect performance?
For my game I need to generate a mesh dynamically. Now I'm wondering does it have a noticeable affect in FPS if I allocate more vertices than what I'm actually using or not? and does it matter if I'm using DirectX or OpenGL?

**Edit**

Final output will be a `w*h` cell grid, but for technical issues it's much easier for me to allocate `(w+1)*(h+1)` vertices. Sure I'll only use `w*h` vertices in indexing, and I know there is some memory wasting there, but I want to know if it also affect FPS or not? (Note that mesh is only generated once in each time you play the game)

# Answer
You'll obviously be wasting memory resources, but the question about FPS is a good one actually.

Your framerate might drop not because you need more processing power or for cache-swapping reasons but for wasted memory accesses.

This is all about where are those extra vertices located. If the vertices are interleaved in the array you'll need more memory accesses since you'll waste a lot of bandwith fetching irrelevant data. If your extra vertices are contiguous then you'll get no FPS drop at all, since they're probably not going to be fetched (or will be fetched few times while fetching your last vertices.)

The more relevant data you can bring from memory at the same time, the better. Of course cache is also relevant, but for the same reasons stated in the last paragraph. Data doesn't matter for cache if you're not fetching it!

The actual FPS drop might not be noticeable. Unfortunately like almost anything GPU-related, you'll have to try it.
> 6 votes

# Answer
It could, in theory. More vertices means more memory used on the GPU. If your game uses enough GPU memory to trigger swapping, then you could lose a bit of time to memory transfer. However, if `w` and `h` are low, then the buffer will use a negligible amount of memory, and if `w` and `h` are high then the wasted memory is fairly small. (As an example, the overhead on a 64x64 grid is about 3%.) The chance that a useful buffer could fit in that additional space is pretty small. The chance that you'd notice the FPS difference there is pretty tiny.

It could also somewhat penalize a smarter GPU. Although a vertex that is never listed in the index buffer should never get transformed by your vertex shader, it still might be fetched and take up cache space, depending on how the GPU works. This assumes your wasted vertices are littered all over your vertex buffer, not concentrated at the end (where they'd presumably be easy to get rid of).
> 3 votes

---
Tags: opengl, directx, dynamic-mesh
---


title: Making a startscreen for an HTML5 game?

text:
# Question
Title: Making a startscreen for an HTML5 game?
How would I make a start screen for a game using HTML5 canvas?

I'm not looking for something advanced, just the new game button and highscore link etc. The question might be stupid, but I've never done anything similar, and the tutorials out there don't cover the subject.

Is it enough to just make a fillText with an `onclick` function? Is there a way to find out the size of the text?

Help appreciated.

# Answer
There are many approaches to this. But, basically, you want to **draw** these buttons in, say, GIMP, and then put them on screen using a canvas. Then, register an onclick event to the canvas, and when it fires you want to iterate through an array of buttons (I suggest you make a constructor function for that; that would be a class in other languages), and when you see that a button has been clicked, you execute it's onclick function. The button's onclick function can be something like `new Game();`, given that you wrapped your game inside a function like I always do.

For that, you need to know the position of the canvas in the web page, because onclick tells you the mouse's absolute position, and you need a position relative to the canvas. That is simple to solve. First, you calculate the offset of your canvas with this:

```
function findPos(obj)
{
    var curleft = curtop = 0;

    if (obj.offsetParent)
    {
        do
        {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        }
        while (obj = obj.offsetParent);
    }
    return [curleft,curtop];
}

CO = findPos(canvas); //CO stands for canvas offset

```

Once you have that, this should be how you calculate the actual click position:

```
var mouse = [0, 0];

function onclick(e)
{
    mouse[0] = e.pageX - self.CO[0];
    mouse[1] = e.pageY - self.CO[1];
    /*Rest of the code*/
}

canvas.addEventListener("click", onclick);

```

This is all if you actually want to create your start menu using a canvas. You might not want to do that, because it would be easier with just HTML. This has several advantages though, like animation and so forth...

Also, there is a way to find out the text size. The height of the text is simply the font size, but to get the width of the text to be drawn use this:

`context.measureText("some random text").width`
> 4 votes

# Answer
It might work to just use anchors. then hide them with css and show the game canvas `onclick`. If you don't want that, you could make a picture which you know the width of and then `onclick` see if the mouse is on it.
> 1 votes

# Answer
Most compelling games seem to use their game engine in the start-screen.

So it will be a specially set-up version of the rendering / gameplay engine playing a demo or autonomous activity (Examples: Any console racing game, Transport Tycoon, etc).

So I expect it's a case of running some kind of state-machine over the top of your normal game-loop doing its normal "thing".

PS: Thanks for the comment on my previous answer.
> 1 votes

# Answer
Depending on the kind of start screen you want to do, you might not need a canvas at all.

Your "html5" game is a web page, after all, so if your start screen is pretty "static", you might want to do it in simple HTML+CSS, with images, fonts, and links (as in ' \< a \> ' tags) to pages that would contain the *actual* game (most likely a page with a large canvas that you draw something on).

And if you want to embed the highscore list, you can use 'standard' web techniques (generating the list on the server side and using a template engine to embed it the page, load it with ajax, whatever works.)

Hoping this helps.
> 0 votes

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


title: Questions about XNA

text:
# Question
Title: Questions about XNA
I've read tons of different threads about XNA, but I still have some questions.

First of all: I have 2 years of experience programming and C# is my main language, so XNA would fit perfectly for me, but I have some concerns.

1. People mentioned that C# has a performance loss compared to C++. Is this true?
2. XNA only supports DirectX 9. I found the ANX framework which is pretty similar to XNA but it is capable of DirectX 11. Would this be a good alternative ?
3. Because I'm worried about the performance loss of C#, I searched for a C++ framework and found SFML. It's based on C++ but can be integrated into C#.

I already have some experience with UDK, but I am really interested in creating more by myself ( lighting physics etc ).

**I didn't start yet, what would you recommend me to use / learn ?**

*I am going to create a **first person shooter** (3D) and I have plenty of time for this. My aim is realtime lighting, realtime global illumination, image-based reflections etc. I want to develop for **Windows**.*

Edit: I found something interesting: OpenTK. It supports the latest version of OpenGL which is on the same level as DX11 (if my knowledge is correct). It makes use of mono.

# Answer
> People mentioned that C# has a performance loss compared to C++. Is this true?

I'll comment on this from a game developers perspective. The author of SharpDX ran a benchmark last year in which he compared the relative performance between using a native D3D11 application written in C++ and several managed alternatives written in C# such as SharpDX, SlimDX and XNA. I'm not sure how accurate these tests really are but the results were:

* SharpDX performed 1.52x slower than native code
* SlimDX performed 2.45x slower than native code
* XNA performed 9.72x slower than native code

So obviously it's true that there's a performance loss. But whether that affects you or not depends a lot the needs of your game. Several commercial games have been created and shipped successfully with XNA (e.g. Bastion, Terraria, Magicka). For the sort of game and the requirements that you listed, it might not be the best choice though.

> XNA only supports DirectX 9. I found the ANX framework which is pretty similar to XNA but it is capable of DirectX 11. Would this be a good alternative ?

Last time I checked ANX was still under development. So I'd recommend maybe looking into either SharpDX or SlimDX for now. In fact, ANX is being built *on top* of SharpDX anyway. And from the benchmark above you can see that SharpDX seems to be the fastest implementation, and not that much slower than native code. But I think SlimDX is more mature and popular though, although I've never used either of them.

> I am going to create a first person shooter (3D) and I have plenty time for this. My aim is realtime lighting, realtime global illumination, image-based reflections etc. I want to develop for Windows.

But seriously, from these requirements, I really think that the best choice would be for you to keep working with the UDK or the CryEngine.
> 11 votes

---
Tags: xna
---


# Question
Title: Box2D Difference Between WorldCenter and Position
So this problem has been brothering for a couple of days now. First off, what is the difference between say Body.getWorldCenter() and Body.getPosition(). I heard that WorldCenter might have to do with the center of gravity or something.

Second, When I create a Box2D Body for a sprite the Body is always at the lower left corner. I check it by printing a Rectangle of 1 pixel around the box.getWorldCenter(). From what I understand the Body should be in the center of the Sprite and its bounding box should wrap around the Sprite, correct?

Here's an image of what I mean (The Sprite is Red, Body Blue):

Here's some code:

**Body Creator:**

```
    public static Body createBoxBody( final World pPhysicsWorld, final BodyType pBodyType,
            final FixtureDef pFixtureDef, Sprite pSprite ) {

        float pRotation = 0;
        float pCenterX = pSprite.getX() + pSprite.getWidth() / 2;
        float pCenterY = pSprite.getY() + pSprite.getHeight() / 2;
        float pWidth = pSprite.getWidth();
        float pHeight = pSprite.getHeight();

        final BodyDef boxBodyDef = new BodyDef();
        boxBodyDef.type = pBodyType;

        //boxBodyDef.position.x = pCenterX / Constants.PIXEL_METER_RATIO;
        //boxBodyDef.position.y = pCenterY / Constants.PIXEL_METER_RATIO;

        boxBodyDef.position.x = pSprite.getX() / Constants.PIXEL_METER_RATIO;
        boxBodyDef.position.y = pSprite.getY() / Constants.PIXEL_METER_RATIO;

        Vector2 v = new Vector2( boxBodyDef.position.x * Constants.PIXEL_METER_RATIO, boxBodyDef.position.y * Constants.PIXEL_METER_RATIO );
        Gdx.app.log("@Physics", "createBoxBody():: Box Position: " + v);

        // Temporary Box shape of the Body
        final PolygonShape boxPoly = new PolygonShape();
        final float halfWidth = pWidth * 0.5f / Constants.PIXEL_METER_RATIO;
        final float halfHeight = pHeight * 0.5f / Constants.PIXEL_METER_RATIO;
        boxPoly.setAsBox( halfWidth, halfHeight );  // set the anchor point to be the center of the sprite

        pFixtureDef.shape = boxPoly;

        final Body boxBody = pPhysicsWorld.createBody(boxBodyDef);
        Gdx.app.log("@Physics", "createBoxBody():: Box Center: " + boxBody.getPosition().mul(Constants.PIXEL_METER_RATIO));
        boxBody.createFixture(pFixtureDef);

        boxBody.setTransform( boxBody.getWorldCenter(), MathUtils.degreesToRadians * pRotation );

        boxPoly.dispose();

        return boxBody;
}

```

**Making the Sprite:**

```
    public Car( Texture texture, float pX, float pY, World world ) {

        super( "Car" );

        mSprite = new Sprite( texture );
        mSprite.setSize( mSprite.getWidth() / 6, mSprite.getHeight() / 6 );
        mSprite.setPosition( pX, pY );
        mSprite.setOrigin( mSprite.getWidth()/2, mSprite.getHeight()/2);

        FixtureDef carFixtureDef = new FixtureDef();

        // Set the Fixture's properties, like friction, using the car's shape
        carFixtureDef.restitution = 1f;
        carFixtureDef.friction = 1f;
        carFixtureDef.density = 1f; // needed to rotate body using applyTorque

        mBody = Physics.createBoxBody( world, BodyDef.BodyType.DynamicBody, carFixtureDef, mSprite );
}

```

# Answer
> 10 votes
> First off, what is the difference between say Body.getWorldCenter() and Body.getPosition().

`Body.getWorldCenter()` is the center of gravity. `Body.getPosition()` is the center of the AABB. For a simple box or circle they will be the same however if your body is unbalanced (ex. multiple fixtures /w different densities) they will differ. Also try setting your origin before the location.

So

```
mSprite.setOrigin( mSprite.getWidth()/2, mSprite.getHeight()/2);
mSprite.setPosition( pX, pY );

```

instead of

```
mSprite.setPosition( pX, pY );
mSprite.setOrigin( mSprite.getWidth()/2, mSprite.getHeight()/2);

```

---
Tags: java, android, physics, box2d, libgdx
---


# Question
Title: How do I load a texture in OpenGL where the origin of the texture(0, 0) isn't in the bottom left?
When loading a texture in OpenGL, how do I specify the origin of the data I am loading?

For example, how would I load a Targa that has it's origin at the top left instead of the bottom left of the image?

# Answer
You can't, at least not directly. The origin of textures in OpenGL is the lower-left corner. You need to vertically flip your image if it doesn't match this coordinate system. So it's really an image processing problem, not an OpenGL problem.

(Alternatively, you can flip all your texture coordinates that refer to the image.)
> 4 votes

# Answer
As a first solution, you could just change the coordinates accordingly yourself when calling `glTexCoord` (or when setting the texture coordinates in your vertex array.)

To flip your texture origin you could easily flip your coordinate system. A naive solution would be `glScalef(1.0f, -1.0f, 1.0f);` (or alternative methods in modern matrix-less OpenGL), effectively flipping your Y coordinates and putting the origin at the top-left corner. **Beware**: you're not actually flipping the texture, but flipping your geometry, although it's a very easy solution if you're just drawing a simple scene like a full-screen quad.

That's rather hacky and will not work for complex situations (without *hacking even more*.) The correct way to go in old OpenGL is the `GL_TEXTURE` matrix (which doesn't seem to be very popular, even when matrices were available.) It behaves exactly like any other matrix (see this link about transforms @ Songho.)

Another approach to this problem (the correct one IMHO, fully-compatible with modern OGL) is processing the image in shaders. It's very simple: your new `texCoord` would be `1.0 - texCoord` (for normalized textures.) This is fully compatible with matrix-less OpenGL (which you should be aiming for, btw) and will let you do all kind of further image processing.
> 6 votes

# Answer
You should flip the image data before uploading it to the GPU. Depending on the image library you are using it might be possible to flip the images already when loading without extra effort.

Don't try to workaround this by flipping texture coordinates or altering texture matrices. Those are not general solutions and only pollutes your code here and there. They are also incompatible with Framebuffer objects, since those expect the texture coordinates to be without any flipping.

Note that cube maps should not be flipped before uploading them. Those can be used directly as they are.
> 1 votes

---
Tags: opengl, textures
---


title: Trouble with speed and vectors

text:
# Question
Title: Trouble with speed and vectors
I'm working on adding bullets to my game. Right now I can shoot bullets in the direction that I would like from a ship by getting the ship's angle:

```
int speed = 5;
int dx = -(cos(degreesToRadians(ship.angle)) * speed); // rate of change in the x direction
int dy = -(sin(degreesToRadians(ship.angle)) * speed); // rate of change in the y direction

bulletPosition.addX(dx); // addX(dx) is simply bulletPosition.x += dx
bulletPosition.addY(dy);

```

The ship is pretty much the exact same thing, except I use the += operator:

```
int dx += -(cos(degreesToRadians(angle)) * 0.15)
int dy += -(sin(degreesToRadians(angle)) * 0.15);

shipPosition.addX(dx);
shipPosition.addY(dy);

```

I would like to be able to add the ship's velocity to the bullet's velocity, but I'm a little confused as to how should get the speed from the ship's vector. I thought that adding the ship's `dx` to the bullet's `dx` like `int dx = -(cos(degreesToRadians(ship.angle)) * speed * dx)` would work because I'm adding the rate of change of the ship to the rate of change of the bullet, but that doesn't work. So here's the final question: How can I get the speed of my ship and apply it to my bullet's speed?

Thanks in advance for all help :)

# Answer
You do want to add the ship's `dx`/`dy` to the bullet's `dx`/`dy`, but you want addition, not multiplication.

```
bulletDx = -(cos(degreesToRadians(bulletHeading)) * speed) + shipDx;

```
> 5 votes

---
Tags: c++, vector
---


# Question
Title: How to highlight non-rectangular hotspots?
So my question is highly related to Creating non-rectangular hotspots and detecting clicks.

Yet again, I've irregular hot-spots (think the game Risk). So basically, we can detect clicks on these hot-spots easily using color key mapping as discussed in above question which I don't have any problems implementing (which is also covered here in details).

The problem is about highlighting these irreguar hotspots. So let me explain the question a bit more - the above color key mapping guide uses this as a world map:

Then the author color-maps the imaginary countries:

Now we can now detect the country the pointer is over. In the same article author mentions outlining countries on mouse-over. Though to get the effect, he creates unique border assets for each country - like:

For the game I'm working on I'm using the same color-key mapping idea to detect hot-spots, but I didn't like the way of highlighting hot-spots. Coloring all the hot-spots is already a time-consuming job for me - as I have 25+ hot-spots for each map. Further, the need to have 25 unique border/highlight asset per hot-spot doesn't sound right.

Anyone have a better idea/suggestion on highlighting these hot-spots?

# Answer
Instead of creating all border/highlight assets manually, you could also create them at runtime, preferably during startup/loading of the game?

To do so, I suggest you look into the marching squares algorithm. By focusing on a single color (eg. treating all other colors as "background") you should be able to trace the outline of a single hotspot. Then just move on to the next color and repeat.
> 3 votes

---
Tags: algorithm, gui
---


# Question
Title: Dropping multiple objects using an array in Actionscript?
I'm trying to get these `fireBalls` to drop more often, I'm not sure if I'm using `Math.random` correctly.

Also, for some reason I'm getting a `null reference` because I think the fireBalls array waits for one to leave the stage before dropping another one?

This is the relevant code:

```
var sun:Sun=new Sun
var fireBalls:Array=new Array()
var left:Boolean;

function onEnterFrame(event:Event){
    if (left) {
        sun.x = sun.x - 15;
    }else{
        sun.x = sun.x + 15;
    }
    if (fireBalls.length>0&&fireBalls[0].y>stage.stageHeight){ // Fireballs exit stage
        removeChild(fireBalls[0]);
        fireBalls.shift();
    }
    for (var j:int=0; j<fireBalls.length; j++){
        fireBalls[j].y=fireBalls[j].y+15;
        if (fireBalls[j].y>stage.stageHeight-fireBall.width/2){
        }
    }
    if (Math.random()<.2){ // Fireballs shooting from Sun
        var fireBall:FireBall=new FireBall;
        fireBall.x=sun.x;
        addChild(fireBall);
        fireBalls.push(fireBall);
    }
}

```

# Answer
> 1 votes
They might not be dropping as often as you want to because you're only removing one per enter frame event using this code:

```
if (fireBalls.length>0&&fireBalls[0].y>stage.stageHeight){ // Fireballs exit stage
    removeChild(fireBalls[0]);
    fireBalls.shift();
}

```

You might want to use a for loop instead to go through all of the fireballs on every enter frame event like so:

```
for (var i:int = 0; i < fireBalls.length; ++i)
{
    if (fireBalls.length > 0 && fireBalls[i].y > stage.stageHeight)
    {
        removeChild(fireballs[i]);
    }
}

```

As far as I can tell, your usage of Math.random() is correct, if you want a new fireball about 1/5th of the time.

# Answer
> -3 votes
figured it out

```
import flash.events.TimerEvent;
import flash.utils.Timer;
var bucket:Bucket=new Bucket
var sun:Sun=new Sun
var fireBalls:Array=new Array()
var livesLeft:Array = new Array()
var left:Boolean;
var timer:Timer = new Timer(1000); // test change direction every second

addChild(bucket)
addChild(sun)
sun.x=sun.width/2
sun.y=50
bucket.x=bucket.width/2
bucket.y=stage.stageHeight-50
bucket.speed=15

stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown)

function onTimer(e:TimerEvent) {
    left = (Math.random() > 0.75);// 50/50 chance of changing direction
}
timer.addEventListener(TimerEvent.TIMER, onTimer);
timer.start();

function onKeyDown(event:KeyboardEvent){
    if (event.keyCode==37&&bucket.x>bucket.width/2){ // left arrow key
        bucket.x=bucket.x-bucket.speed;
    }
    if (event.keyCode==39&&bucket.x<stage.stageWidth-bucket.width/2){ // right arrow key
        bucket.x=bucket.x+bucket.speed;
    }
}

stage.addEventListener(MouseEvent.MOUSE_MOVE,followBucket);

function followBucket(event:MouseEvent):void {
bucket.x=mouseX;
}

addEventListener(Event.ENTER_FRAME,onEnterFrame)

function checkForCollisions (){

}

function onEnterFrame(event:Event){
    checkForCollisions.call();
    if (left) {
        sun.x = sun.x - 15;
    }else{
        sun.x = sun.x + 15;
    }
    if (fireBalls.length>0&&fireBalls[0].y>stage.stageHeight){ // Fireballs exit stage
        removeChild(fireBalls[0]);
        fireBalls.shift();
    }
    for (var j:int=0; j<fireBalls.length; j++){
        fireBalls[j].y=fireBalls[j].y+15;
    }
    if (Math.random()<.2){ // Fireballs shooting from Sun
        var fireBall:FireBall=new FireBall;
        fireBall.x=sun.x;
        fireBall.y=sun.y+sun.width/2;
        addChild(fireBall);
        fireBall.gotoAndStop(1);
        fireBalls.push(fireBall);
    }
    if (sun.x>stage.stageWidth){ // Sun hits right side of stage
        sun.x=0;
    }
    if (sun.x<0){ // Sun hits left side of stage
        sun.x=stage.stageWidth;
    }
}

```

---
Tags: flash, animation, actionscript-3
---


# Question
Title: Want to develop my own primitive physics engine, don't know how to start with its high-level architecture. Suggestions?
Few years ago I tried to make a simple 3D game - billiards. Completed like 50%, stuck with physics. Basically, I only need to calculate balls rolling over flat surface, but it would be nice to make something more flexible. I know all the formulas and laws (most of them, anyway). the problem is I have no idea of how to make good physics engine architecture-wise. I tried google and other forums but didn't find what I was looking for. The only suggestion was to look at open-source engine, but I'm not that good a programmer to make heads or tails out of it...

# Answer
> 10 votes
**How to start an Architecture/Design Task:** With pen and paper.

Get yourself a large sheet of paper and start drawing out the components and items that will exist within your engine. What properties each entity will need so that you can model the physical interaction.

You'll need to figure out what entities your code will have to deal with, which entity has the responsibility of running the physics simulation (and which bit of the simulation).

Then you'll have to figure out how the entities are interacting. Use colours.

Now go to sleep. leave the design for a few days and do other stuff. If you have some friends you can talk to, this is a good time to ask them about what they think.

Return to you design. You'll see some obvious problems and will feel the urge to make it more elegant. Do it.

Start coding from your second design. Rinse and repeat until you feel proud of your design and implementation. Then ask for criticism from people whose technical skills you respect, and realise that you've barely scratched the surface and that your engine is held together with duct tape. Rinse and repeat.

Some points:

* There is no perfect formula for architectural systems like this. It's a matter of experience and a taste for elegance. Books may help you by exposing you to interesting ideas, but if you're comfortable with the physics, you're no more or less qualified than anyone else to design an engine.
* Don't worry about a *good* engine worry about about getting an engine that *runs*, and move towards good from there. (even if it means you're hitting polynomial complexity )
* Worry more about being able to communicate the way your engine works to someone else. Until you can explain your code to your mum, you don't understand what you're doing.

That last point is most important. When you get stuck, try to explain what your engine should do to a friend, on IRC, or in an email to someone whose work you respect. The act of trying to explain it to someone else will often reveal what your problem was in the first place. (You don't actually have to hit the "send" button, if you feel shy...)

If you want a good book on architecture, try The Architecture of Open Source Applications which you can read for free online. You could also watch Rich Hickey talk about how he designed Clojure: Hammock Driven Development for inspiration.

---
Tags: architecture, physics-engine
---


# Question
Title: Skeletal Animation - Automatically apply skeleton to model
Looking at websites such as mixamo.com or some game's development systems such as the animation editor for Overgrowth (http://www.youtube.com/watch?v=-RpqbC5-Z0E), i see that the skeleton in these situations is automatically being applied to the models.

I really don't expect (though wouldn't mind) code that does this, but i really am looking for some sort of pointer in the direction, or how they go about this. If any of you have done this, or know how to, please do reply, i don't want to spend the next week trying to crack it, then another to actually code it :P

Thanks all :)

Just for a bit more information, i am in C# working with OpenTK with my own custom model loader, etc. but i can easily adjust any given code / concept to fit with mine :)

# Answer
So to start, I'll just give brief overview of how skeletal animation works, which will lead in nicely to how a skeleton is applied to a mesh.

Character animation can be defined as the deformation of the 'skin,' or geometry that makes up the character, over time. The extremely naive way of accomplishing this is to individually move and keyframe each vertex in the model. This would results in the most control and perhaps visually appealing results, but it would also take forever for an animator to do his job. So the skeleton method was established (note that there are also other ways to animate such as implicit functions, but the skeleton method is most convenient for games).

Each joint of a skeleton exerts a certain amount of influence over the vertices of a mesh, and is represented as a matrix which will perform a linear transformation. In a rigid bind, a vertex can only be influenced by one joint. This is good for a robotic character, but for a humanoid character, we need smooth skinning, where a vertex can be influenced by multiple joints. And to calculate new positions of vertices as the joints move, we linearly interpolate between the new positions of the vertices calculated by multiplying by the matrix of each joint that influences them, and weighted by the amount of influence of those joints.

For more information, a good starting point is the Wikipedia article on the subject.

Now, given all that, your goal is to calculate what joints influence each vertex, and with what weights. The reason I suggested using modeling software which already does this for you (Maya, 3DS Max, etc.), is because this is quite a hard problem to do properly in one go, but all the same it's probably fun to try to implement.

What you need to do is for each vertex, figure out, perhaps, which joints are closest to it, and depending on their distance, assign a weight to that joint for that particular vertex. There are problems that come up though. For example, what if when you skin the model, the wrist joints are close to the hips (the characters arms are hanging)? The result will be that the vertices of the hip are now influenced by the wrist joint, and when you move the model's arm outwards, the hip will deform awkwardly. A naive way to remedy this might be to raycast between each vertex and potential influencing joint, and if there is an obstruction (i.e, the ray does not travel entirely inside of the model), then that joint cannot influence that vertex. Again, this is not true in all cases, and finding a general solution is difficult.

Furthermore, there are difficulties in assigning weights to joints appropriately. Even professional grade modeling and rigging software, such as Maya, cannot do this perfectly, and this is why the job of weight painting exists. Other skinning algorithms, such as Dual Quaternion Skinning, alleviate the need for this, but do not eliminate it entirely.

A couple of additional implementation notes: the sum of the weights on joints for a particular vertex must be 1. Also, the typical number of joints that influence a single vertex in the industry these days is 4.

In sum, the concept of applying a skeleton to a model is quite easy to grasp and implement at its most basic level, but the details and corner cases of doing it properly are what makes it such a hard problem.

Hope this helps, and good luck :)
> 9 votes

---
Tags: c#, skeletal-animation
---


# Question
Title: Problem with Update(GameTime) Methods and Pause implementation
I have the pause function implemented and it works correctly in that it dims the player screen and stops updating the gameplay.

The problem is that GameTime continues to increase while it is paused, so my method that checks gameTime versus previousSpawnTime before spawning another enemy gets messed up and if the game is paused too long it is noticeable that the next enemy draws far too early.

Here is my code for the enemy update.

```
private void UpdateEnemies(GameTime gameTime)
    {
        // Spawn a new enemy every 1.5 seconds
        if (gameTime.TotalGameTime - previousSpawnTime > enemySpawnTime)
        {
            previousSpawnTime = gameTime.TotalGameTime;

            // Add an Enemy
            AddEnemy();
        }
...

```

I also have other methods that depend on gameTime. I've tried getting the total pause time and subtracting that from the total game time, but I can't seem to get it to work correctly if that is the way I should go about solving this.

If you need to see any other code let me know. Thank you.

# Answer
> 8 votes
Instead of using `TotalGameTime` use `ElapsedGameTime` and accumulate the running total yourself in some variable. Then when you pause the game all you have to do is to stop adding the elapsed time to the variable. Here's an example:

```
float spawnTimer = 0.0f;
float timeBetweenSpawns = 1.5f;

private void Update(GameTime gameTime)
{
    // Perform actions that should only happen when the game is not paused
    if(!isPaused)
    {
        // Add time elapsed since previous frame to running timer
        spawnTimer += (float) gameTime.ElapsedGameTime.TotalSeconds;

        // Check if enough time has passed to spawn a new enemy
        if(spawnTimer >= timeBetweenSpawns)
        {
            AddEnemy();

            // Decrement the timer to prepare it for the next spawn
            spawnTimer -= timeBetweenSpawns;
        }
    }

    // Perform any actions that should happen all the time
}

```

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


title: Where are all the tutorials for libGDX?

text:
# Question
Title: Where are all the tutorials for libGDX?
I've searched online for help and tutorials on LibGDX but I couldn't really find any, except and the wiki for asking questions on stackexchange. Besides the source (demos) and wiki, is there any other tutorials online that's hidden or indirect?

From what I read, there isn't much documentation for LibGDX, so there's only two options I see

* Give up move to a different framework.
* Ask people a lot of questions.

# Answer
> 31 votes
Welcome to open source! As most developers will tell you: "What documentation?". Documenting code is probably the least fun developers have when creating a project. So what do you think is often severely lacking when the developer isn't even getting paid for their creation? Documentation of course! (Even fully paid programmers will often leave out the documentation).

I mentioned to you before that open source isn't "supposed" to be easy. This is one of the reasons. However, the nice thing about open source is that it's open, so you can find out what the code is doing on your own. However this is often *a lot of work*.

That being said, I took a look at the demos provided in the libgdx source, and the wiki. **Libgdx is pretty well documented**, considering it's open source. I don't think your issue is with documentation. I think you may be trying to bite off more than you can chew. From your previous questions, I understand that you're pretty new to programming in general and brand new to the Android platform. Programming on the Android platform isn't the easiest place to start, and programming games on the Android is even further from the mark.

I really think you should try some 2D game programming for the PC, there are plenty of tutorials for getting started in 2D Java game programming on the PC. Once you're more comfortable with programming in general, I think you'll find that the resources available to you for libgdx are more than sufficient.

# Answer
> 14 votes
I agree with @Byte56 that you may be better off with something a bit simpler than Android game development, however for completeness (if other people would like to know where to look):

http://steigert.blogspot.com.au/2012/02/1-libgdx-tutorial-introduction.html

Steps through several different aspects of development with libgdx, from setting up your project, to drawing, to GUI's, file handling, etc.

http://www.badlogicgames.com/wordpress/

This is the blog from the developers, and each time a new feature is introduced, there is always a very well written, comprehensive discussion of how it works and why it is there in the first place.

http://code.google.com/p/libgdx/source/browse/#svn%2Ftrunk%2Fdemos

As has been mentioned, there are several demo's you can study to see how different things are achieved (e.g. how do you integrate Box2D physics engine into your game? or how do you animate sprites?)

http://code.google.com/p/libgdx/source/browse/#svn%2Ftrunk%2Ftests%2Fgdx-tests%2Fsrc%2Fcom%2Fbadlogic%2Fgdx%2Ftests

In addition to the game demo's which are shown above, I find it easier to look at the tests if there is a specific feature of libgdx I want to investigate. There is good coverage of most of the different features (e.g. sprite handling, physics, file handling, etc).

And finally, the usuals: http://www.google.com, http://gamedev.stackexchange.com if you have very specific things you want to find out.

I'm sure there are several other good tutorials out there, but these are the ones I stumbled across and found helpful for my recent foray into libgdx.

---
Tags: android, libgdx
---


title: How to make an isometric background?

text:
# Question
Title: How to make an isometric background?
I'm trying to create an isometric background for a game but I'm not sure how to do it. I'm using Javascript and jQuery. I've already **tried it before** using CSS3 but I think I'm using the wrong method.

# Answer
> 7 votes
I don't know about jQuery but in general terms I can think of a few alternatives.

1. Use **isometric tiles** to create the background. It's very similar to creating a top-down tile based map but with tiles being offset a little. You can find more information *here*. Also check this answer for a side-by-side comparison between isometric and top-down.
2. Turn a top-down background into isometric by **rotating 45º and compressing it vertically**, either in code or in some image manipulation software.
3. Probably not applicable here but in a 3D API you can also get an isometric view of the world by setting an **orthographic projection** and positioning the camera at the correct angle.

---
Tags: javascript, isometric
---


# Question
Title: Memory allocation strategy for the vertex buffers (DirectX 10/11)
I'm writing a CAD system. I have a 3D scene and there are many different objects (walls, doors, windows and so on). The user can add or delete objects. The question is: **How do I keep track of all the vertices for all my objects?**

I can create vertex buffer for every object. But I think drawing/switching from one buffer to another would have performance penalty.

Another way - I can create several big buffers for every object type. But I don't understand how to update such buffers. It is too big to update whole buffer (for example buffer for all walls). What would I do if I wanted to delete an object that's in the middle of the buffer?

I have the similar question here on Stack Overflow.

Most examples I've found work with static models. Therefore, they tend to create a single vertex buffer with their list of points, and then are just manipulated by matrix transformations. I, on the other hand, will be updating the scene very often. So what's the best way to keep track of and store this information?

# Answer
This is a fairly clear case of premature optimization. You have no performance data saying that there will be any need for optimization.

Simply make one vertex buffer per separate object that the user wants to edit, by the time your seeing performance problems you can start profiling your code for the bottlenecks. In particular, swapping vertice buffers is not a very time consuming task, draw calls is the bottleneck there.

Your likely bottle neck will either not exist (for smaller parts style CADing) or be a matter of too many triangles (for town CADing), in this latter case you would be using efficient culling to reduce the problem, this is easier to do with several objects instead of a singular huge one.

Im hoping this makes sense, was written a bit hastily I'm afraid.
> 3 votes

---
Tags: directx11, directx10, vertex, index-buffer
---