# Question
Title: How to play a sound only one time in XNA?
I'm using a sound when a key is pressed, like a fire. But despite that I'm pressing the key for just a short moment, the sound is playing so many times. I guess it's because of the Update method that updates it all 60 times per second.

Is there a way to play the sound only one time, until I press the next time? I also have the same problems with sprites when they hit the border a short "bang" sound is played, but it dosen't sounds like it should do! I guess it playes to many times!?

Help id preciated to solve this! Thanks!

```
if (keyboardState.IsKeyDown(Keys.Space))
{
code play sound and activate a sprite
}

```

# Answer
> 4 votes
What you need to do is check if this is the FIRST time the key has been pressed. Remember that the game updates 60 times per second (that's about once every 16.6ms!), so when you press the button, it's unlikely you're going to have it held down only for 1 frame. The way you get around this is to keep the *previous* keyboard state as well as the current keyboard state. You then compare them to see if this is the first frame the key has been pressed and execute your code only if that is true.

So, at the top of the class, add these two field variables:

```
KeyboardState _currentKeyboardState;
KeyboardState _previousKeyboardState;

```

Then, your `Update` will look like this:

```
public void Update(GameTime gameTime) {
    //Update the current keyboard state at the beginning of Update
    _currentKeyboardState = Keyboard.GetState();

    //Do all your update stuff here

    //Last line in the update statement:
    //Set the previous keyboard state to the current one.
    // On the next frame, this will be equal to the keyboard state on THIS frame.
    _previousKeyboardState = _currentKeyboardState;
}

```

So, now that you have those two things, you can check if the keyboard has been newly pressed by checking both states like so:

```
if (_currentKeyboardState.IsKeyDown(Keys.Space) && //Currently pressed
    _previousKeyboardState.IsKeyUp(Keys.Space)) { //Was Up on the last frame
    //If the Space key is currently pressed and was not pressed on the
    // last frame, play a sound
}

```

That's the basics of how it works. Let me know if you have any questions.

On a side note, I have a more in-depth explanation on my blog relating specifically to checking the different states (Up, Click, Hold, Release) using the mouse if you're interested.

---
Tags: xna
---


# Question
Title: Find the nearest control points either side of a Catmull Rom spline segment
There is a formula for evaluating a Catmull Rom spline segment at time 't' found here.

The problem with this is that it requires finding the two control points either side of the segment to evaluate.

Is there a formula for finding those two control points?

As a alternative I considered utilising some kind of algrorithm for finding the nearest values either side of a given value:

```
float lowerNearest = float.MaxValue;
float upperNearest = float.MinValue;

int numElements = array.Length;

for (int i = 0; i < numElements; ++i)
{
    float dif = index - array[i].Index

    if (dif > 0)
    {
                     lowerNearest = Math.Min(lowerNearest, dif)
    }
    else
    {
         upperNearest = Math.Max(upperNearest, dif);
    }
}

```

However I'm not sure what values I should be comparing as the control points are only vectors and felt that it was probably the incorrect way to approach this problem.

# Answer
Are you using this as a motion path? Assuming the points are ordered in the array you can just go in this order and keep track of which point is next/previous.

If you want to start at an arbitrary point then the question is a bit confusing - how do you define this point? I guess it is not just 'a point in space.' Is it defined like t? (0\<=t\<=1)

If so, you can try guessing with some sort of interpolation. Check out http://en.wikipedia.org/wiki/Nearest\_neighbor\_search for some hints.

Depending on the shape of the spline you could try nearest neighbour distance ratio - for example if t=0.5 then you take the middle points:

```
int index = Math.round(array.Length*0.5);

```

and take three other points around this one. Then you can try checking if one of these points is not closer to your point. If it is, use its neighbours for comparison, and so on.

If you know the approximate distance between points and it is roughly even, then you can use fixed radius nearest neighbour - query points until you find those within a tolerance and take the closest from these.

If the space is very big (lots of points) then you might be best off building a tree structure for faster search.

Hope this helps
> 2 votes

# Answer
How you choose the two outside control points depends entirely on what you *want* the spline to do and what you're trying to do with it. Those points affect how it curves, so you select them based on the curving behavior you want.

What Catmull-Rom splines are designed to do is create a smooth curve defined by an array of points. It passes through each point in the array in order and has no visual discontinuities as it does so. In this case the four control points are just four contiguous points in the array. E.g. one segment would use points 0, 1, 2, 3, the next segment would use 1, 2, 3, 4, etc.

If this is not your use case, it's possible a different kind of spline would be better suited for you, e.g. Hermite or Bézier.
> 1 votes

---
Tags: mathematics, splines
---


# Question
Title: How should I position and move objects in my 3D world in relation to terrain
I'm drawing a heightfield as a piece of 3D terrain using the fairly 'dumb' method of drawing triangles, like everyone does when learning this sort of thing. There's no fancy LOD, scenegraphs or other things, it's deliberately simple and low poly because that's the look of the game. A section of X,Y height data is turned into a mesh of triangles and drawn on the screen.

I now want to scroll the heightfield in the Z axis (not the X or Y, I just want to move 'forwards' through it).

I have a player object with a 'camera' attached to it. When the player wants to go 'forwards' should I

* keep the player at the same Z position and scroll the terrain towards the viewer to simulate movement
* actually move the player in the Z axis and draw the relevant bit of terrain under them (because the camera is 'attached' to the player it looks like they stay in the middle of the screen, and the gameworld and gameplay will limit how far the player can go forwards)

I'm doing the first one at the moment and it works well... until I want to interact with the terrain or place stationary objects on it at specific points. It seems a bit backwards since all the 'moving' objects stay still, and all the stationary objects need to be moved towards the viewer at the same rate as the terrain is. Also the maths to translate the terrain's scrolled amount and the player's pretend location is somewhat complex.

# Answer
I would recommend the 2nd option. With it, you are only updating one item (the position of the player). Whereas in the 1st option, you must update the position of every other object in the world.
> 3 votes

---
Tags: 3d, graphics, coordinates, terrain-rendering
---


# Question
Title: Does the standard lighting equation ever allow objects to be brighter than their textures?
It occurred to me that the standard lighting setup you see in all the tutorials doesn't allow lights to actually make an object appear brighter than its texture. The light value is always clamped between 0 and 1. Which means at maximum brightness, the resulting color will be exactly the same as the value from the texture. Even if you didn't clamp it manually, in a deferred renderer, the graphics card/driver will end up clamping it for you.

This seems very unusual to me. Do AAA games actually use lighting like this? Or is there a solution? My thought was maybe this is what HDR "fixes" but the only thing I've noticed HDR doing is that rather annoying light-transition effect.

# Answer
Specular light is not modulated by the diffuse texture, so specularity can easily make a surface appear brighter than its texture at times, even in an LDR renderer.

But more generally, ordinary materials can't reflect more light than they receive, so (considering only diffuse for a moment) the reflected light will be no brighter than the incoming light, and if the incoming light is clamped to 1 then the reflected light will be no brighter than the texture.

In an HDR renderer the lights can have an arbitrary brightness, but that's not the whole story. Two keys to doing HDR properly are: setting the exposure properly based on the brightness of the scene and your aesthetic goals, and using a good tonemapping filter. If you want the image to look brighter you have to adjust the exposure to do so. Even if the lights are still in the \[0, 1\] range, you can adjust the exposure to make the image brighter. This is an artistic choice and it's perfectly permissible to set the exposure in such a way that well-lit objects end up brighter than their textures. The tonemapping filter allows you to alter the exposure without losing too much detail either in the bright or dark areas. It also makes bright colors ramp to white in a natural way as they get brighter, rather than simply being clamped, which can produce unwanted color shifts and loss of detail.

There's a good tonemapping equation on slide 140 of this talk (which is also *highly* worth reading, at least the first two sections on gamma correction and HDR, if you want to understand how to do physically based rendering correctly).
> 4 votes

---
Tags: hlsl, lighting
---


# Question
Title: How do I put a game on miniclip or addinctinggames?
I finished making a java game recently, and I would like to put it on a website such as Miniclip.com or AddictingGames. How would I do this?

I have one more question. I know these sites could run Flash games, but what about Java games? If they can't, is there any other website analogous to those that would?

My reason for this is that I am planning on launching this game on Android, and I would like to get some feedback for this game and have some people be familiar with the game before it launches.

# Answer
> 2 votes
Addicting games has an upload page here, looks like the mobile submission process is via email.

Same with Mini clip, they have a developers page, and you'll need to email them for a mobile submission.

Neither looks like they do Java for PC, but both appear to do Android games.

Desura can offer what you want with a Java PC game. As a bonus they also have a beta service for your game, and that's what it looks like you want first.

---
Tags: java, android, distribution
---


title: Help with Meshes, and Shading

text:
# Question
Title: Help with Meshes, and Shading
In a game I'm making in LibGdx, I wish to incorporate a ripple effect. I'm confused as to how I get access to the individual pixels on the screen, or any way to influence them (apart from what I can do with sprite batch).

I have my suspicions that I have to do it through openGL, and it has something to do with apply a mesh? This brings me to my question, what exactly is a mesh?

I've been working on my game for about half a year, and am doing great with the other aspects of the game, but I find this more advance stuff isn't as well documented.

Thanks!

# Answer
You seem to be REALLY confused about things, so i'll try to break it down for you.

A mesh is just a collection of points/triangles in space. It's used interchangably with the term model and usualy means the same thing.

You don't get access to individual pixels on the screen itself, what you can do is access them before they're put on the screen, if that makes sense. OpenGL allows rendering to a, so called, frame buffer, it's like rendering to an image in memory, this allows you to apply post processing effects. I don't know how libgdx does it though.

Now there are plenty of ways to do ripples and it depends on what kind of an effect you're looking for, though you haven't specified anything. You could just do a ripple animation and blend it with whatever picture you have, you don't need OpenGL for that. Other than that you could put your finished image through OpenGL and let it apply ripples as some sort of a displacement based on a normal map. There's plenty of articles that cover this subject. The issue is that if you don't understand how OpenGL works, then none of this is going to help you, really.
> 1 votes

# Answer
If you're using libGDX SpriteBatch, instead of rendering to the screen you should be able to render to a FrameBuffer, then you can get the resulting texture out of that and render it to the screen. You can apply effects to the texture before rendering to get screen-wide effects.

This isn't the most efficient way, but it should be sufficient.

This question over on stackoverflow covers a similar request (for a different reason), but the code example should help you get started: https://stackoverflow.com/questions/7551669/libgdx-spritebatch-render-to-texture
> 0 votes

---
Tags: opengl, java, android, opengl-es, libgdx
---


# Question
Title: Voxel terrain rendering with marching cubes
I was working on making procedurally generated terrain using normal cubish voxels (like minecraft) But then I read about marching cubes and decided to convert to using those. I managed to create a working marching cubes class and cycle through the densities and everything in it seemed to be working so I went on to work on actual terrain generation. I'm using XNA (C#) and a ported libnoise library to generate noise for the terrain generator. But instead of rendering smooth terrain I get a 64x64 chunk (I specified 64 but can change it) of seemingly random marching cubes using different triangles.

This is the code I'm using to generate a "chunk":

```
public MarchingCube[, ,] getTerrainChunk(int size, float dMultiplyer, int stepsize)
    {
        MarchingCube[, ,] temp = new MarchingCube[size / stepsize, size / stepsize, size / stepsize];
        for (int x = 0; x < size; x += stepsize)
        {
            for (int y = 0; y <size; y += stepsize)
            {
                for (int z = 0; z < size; z += stepsize)
                {
                    float[] densities = {(float)terrain.GetValue(x, y, z)*dMultiplyer, (float)terrain.GetValue(x, y+stepsize, z)*dMultiplyer, (float)terrain.GetValue(x+stepsize, y+stepsize, z)*dMultiplyer, (float)terrain.GetValue(x+stepsize, y, z)*dMultiplyer,
                    (float)terrain.GetValue(x,y,z+stepsize)*dMultiplyer,(float)terrain.GetValue(x,y+stepsize,z+stepsize)*dMultiplyer,(float)terrain.GetValue(x+stepsize,y+stepsize,z+stepsize)*dMultiplyer,(float)terrain.GetValue(x+stepsize,y,z+stepsize)*dMultiplyer };
                    Vector3[] corners = { new Vector3(x,y,z), new Vector3(x,y+stepsize,z),new Vector3(x+stepsize,y+stepsize,z),new Vector3(x+stepsize,y,z), new Vector3(x,y,z+stepsize), new Vector3(x,y+stepsize,z+stepsize),
                       new Vector3(x+stepsize,y+stepsize,z+stepsize), new Vector3(x+stepsize,y,z+stepsize)};
                    if (x == 0 && y == 0 && z == 0)
                    {
                        temp[x / stepsize, y / stepsize, z / stepsize] = new MarchingCube(densities, corners, device);
                    }
                    temp[x / stepsize, y / stepsize, z / stepsize] = new MarchingCube(densities, corners);
                }
            }
        }

```

(terrain is a Perlin Noise generated using libnoise)

I'm sure there's probably an easy solution to this but I've been drawing a blank for the past hour.

I'm just wondering if the problem is how I'm reading in the data from the noise or if I may be generating the noise wrong? Or maybe the noise is just not good for this kind of generation? If I'm reading it wrong does anyone know the right way?

the answers on google were somewhat ambiguous but I'm going to keep searching.

Thanks in advance!

# Answer
> 1 votes
I would try to decouple the problem into two distinct chunks: firstly, have a Marching Cubes algorithm that gets its data from an arbitrary 3d array; and second, have a function that will fill an array with values from noise.

Essentially, you're building an ad hoc 'unit testing' approach: on one side, you can fill in your array with 'easy' values by using specific functions of two variables (for instance, a constantly-sloping plane like f(x,y)=8x+10y+15z, or a smooth surface like f(x,y)=(x-100)^2+(y-100)^2+(z-100)^2 ) and confirm that Marching Cubes applied to level sets of these functions gives the results that you expect in those cases.

Meanwhile, on the other side you can write simpler rendering algorithms — for instance, just rendering a cube or even a particle for each value in the array that's within a certain range — and use those to visualize your noise function. Once you can confirm that both pieces of the puzzle are working well in 'toy' circumstances then you can make the optimizations of putting them together and eliminating the intermediate 3d array, but until you're certain that both are independently functional I would decouple them as much as possible.

---
Tags: xna, voxels, terrain-rendering
---


# Question
Title: Collision Detection/Map Management in RPG
I'm making an rpg game. I have a Grid class which takes a char\[\]\[\] to create tiles. The way I'm currently doing collision detection is by creating a Player and assigning it the grid it should be created in.

However, (because it seems to be the easiest way to do things) I want to be able to have a class that has an array of Grids that only load the map information when neccessary (i.e. when the player is close enough to the next grid).

My past implementation was when i had a Grid\[\]\[\]. However, this causes problems when I want to walk off my current grid and the game gives me a ArrayIndexOutOfBoundsException. My main concern is this: I want to be able to design a system that loads information as I need it.

My questions are: How should I go about doing this? Is this the most efficient way to design things? If I have to redesign something things, I'm willing to, as I'm in the early stages of game design.

# Answer
> 1 votes
If I'm not mistaken, the player's position in your implementation is represented by 4 numbers: GridX, GridY, TileX and TileY. That's a way to do it, and it's completely fine, as long as you don't screw something up with the indexes (which will give you ArrayIndexOutOfBoundsException).

**1 . First, whatever happens (the player moves, etc.) just make sure that:**

0 \<= GridX \< Grid.Length

0 \<= GridY \< Grid\[GridX\].Length

0 \<= TileX \< Grid\[GridX\]\[GridY\].Tiles.Length

0 \<= TileY \< Grid\[GridX\]\[GridY\].Tiles\[TileX\].Length

**2 . Only load a Grid, if any of its Tiles are about to become visible.**

```
  (Player.TileX < ScreenWidth/2
   || Player.TileY < ScreenHeight/2
   || Player.TileX >= (GridWidth-ScreenWidth/2)
   || Player.TileY >= (GridHeight-ScreenHeight/2))

```

Where (ScreenWidth * ScreenHeight) is the number of tiles shown on your main screen at any time, and GridWidth * GridHeight is the number of tiles your grid holds. For example, if your window shows 30x20 tiles, and your Grids hold 100x100 tiles each, then

```
  ScreenWidth = 30;
  ScreenHeight = 20;
  GridWidth = GridHeight = 100;

```

**3 . Make transitions smooth (if necessary).** If your grids are really large, and it takes 1 second to load one into the memory, then you might want to start loading it sooner. For example, when the Player is at a (ScreenHeight/2 + 5) distance from the edge of the Grid. However, it's only necessary if you experience lag while loading a Grid. This might happen if you're reading the Grid data from a huge file on the HDD, or from a distant server.

# Answer
> 1 votes
If you want dynamic map loading you need a special data structure to store the level. Easiest way is to split the level into even sized chunks.

For example you could make a chunk an area of 32x32 grid cells. Then you need another class, that takes care of loading and unloading chunks. Make sure that you have the visible chunks and the surrounding ones loaded, as it may take some time to load a chunk.

You need some logic that manages the chunks, means checks if they are enough far away to be unloaded or if they are near enough to be loaded.

Maybe it would be best to start with a fixed sized system to get the arrangement and rendering of the chunks right. If you've done that, you can extend the class so chunks can be dynamically loaded or unloaded.

btw, minecraft uses a similar system of chunks (i think its something like a 16x16x256 cube). You find some information on the internet, how the chunk system in minecraft works. You could use it as inspiration, as you want to do basically the same thing, but in 2d space.

=\> http://www.minecraftwiki.net/wiki/Chunks

---
Tags: java, rpg, memory-efficiency
---


# Question
Title: Binding BoundingSpheres to a world matrix in XNA
I made a program that loads the locations of items on the scene from a file like this:

```
using (StreamReader sr = new StreamReader(OpenFileDialog1.FileName))
                    {
                        String line;
                        while ((line = sr.ReadLine()) != null)
                        {
                            red = line.Split(',');
                            model = row[0];
                            x = row[1];
                            y = row[2];
                            z = row[3];
                            elements.Add(Convert.ToInt32(model));
                            data.Add(new Vector3(Convert.ToSingle(x), Convert.ToSingle(y), Convert.ToSingle(z)));
                            sfepheres.Add(new BoundingSphere(new Vector3(Convert.ToSingle(x), Convert.ToSingle(y), Convert.ToSingle(z)), 1f));
                        }

```

I also have a list of BoundingSpheres (called spheres) that adds a new bounding sphere for each line from the file. In this program I have one item (a simple box) that moves (it has its world matrix called matrixBox), and other items are static entire time (there is a world matrix that holds those elements called simply world). The problem i that when I move the box, bounding spheres move with it. So how can I bind all BoundingSpheres (except the one corresponding to the box) to the static world matrix so that they stay in their place when the box moves?

# Answer
> 1 votes
Comment as answer:

In that case, how does your ray picker check against the bounding spheres? My thought is that, if worldBox is the only thing you're changing, it must co-incide somewhere with the picker algorithm. Two possible problems: 1) does the ray picker use the worldBox matrix? 2) If not, are world and worldBox created at the same time? Have you inadvertently got two references to the same matrix?

---
Tags: collision-detection, xna-4.0
---


# Question
Title: What mathematics would I need to know in order to build a 2.5D raycasting engine
I realize this is a fairly common-type question, but I've been studying Maths in my spare time, fairly slowly at that, and I really want to develop a raycasting engine like the original DOOM.

I know more-or-less the subjects / categories of Maths needed for modern 3D games, such as Linear Algebra, but I don't they all would be applicable for a raycasting engine.

Assume I am starting from the ground-up in Maths, what would I need to know? I assume Algebra, Trigonometry and Geometry would be the most important. I'm wondering if I could pull it off just with that?

# Answer
A Wolfenstein-style raycaster is really simple. You basically shoot beams horizontally in an arc from one side of the player view to the other edge. When a beam encounters a wall, you get the wall slices height on screen from the distance (e.g. scale\_factor / distance). E.g. for this height calculation you don't need to understand anything about matrices etc, just think that you want a smaller height on screen when the distance from viewer is greater.

The "trickiest" part is "shooting" the beam (i.e. determining direction and traversing it in small steps), but that's trivial for any 2d game programmer - just use sin and cos as you would have done for the player movement.

It gets slightly more complicated when adding stuff like textured walls (still easy) and sprite enemies, and you can always explain the thing with difficult mathematics using projection planes and whatnot, but the basic idea is just traversing 2d beams on a 2d grid - if you're language/programming environment has an easy way to output graphics, you can get a basic raycaster running in less than 50 lines of code without any matrices or even vector classes.
> 4 votes

# Answer
Well, if you stick to something very simple then you can do it using only basic linear algebra. I would list the absolute necessities as understanding a) orthogonal coordinate systems; b) matrix multiplication and c) how and why the two are related.

And if you want to actually construct some arbitrary rotation matrices then you'll at least need to understand the basic trigonometric functions and their relation to the circle.

The wikipedia page for Transformation matrix summarizes pretty much everything, and the links from that page has even more information (see 3D projection in particular).

There's also some amount of non-mathematical understanding required of course. If you want to put something together on your own then figuring out how and why to do something might require quite a lot of logical thinking, even when the math in question would turn out to be trivial (which might turn out to be most of the time).

However, I'd say that the most important skill isn't math but the ability to search for information. There is *a lot* of material in books and on the internet. If there is something you don't understand when reading then you can be quite certain that there are articles and books (or Stack Exchange for that matter) available to explain.

\[Edit\] Right... It seems I've misunderstood the question, and overshot terribly. See above for a better aimed answer :)
> 1 votes

---
Tags: raycasting, 2.5d
---


# Question
Title: How can I read .TGA and .BLP image files in C++?
Is there a C++ library that enables reading of .tga and .blp image formats on Windows?

# Answer
> 1 votes
For BLPs, you may check this source code example.

For TGAs, honestly I would just convert them to *eg.* PNGs offline, and then use plain GDI+ to load the PNGs. Is there a specific reason for using TGA? Anyway, you can use this full, annotated source code.

# Answer
> 0 votes
For Targa (.tga) files, the FreeImage library may be useful.

# Answer
> 0 votes
I recommend using SOIL. I found it to be by far the easiest way of loading and saving texture to and from OpenGL. The last update was in 2008, though. It still works fine, but some people like to steer away from "old" software.

---
Tags: c++
---


title: Z axis in isometric tilemap

text:
# Question
Title: Z axis in isometric tilemap
I'm experimenting with isometric tile maps in JavaScript and HTML5 Canvas. I'm storing tile map data in JavaScript 2D array.

```
// 0 - Grass
// 1 - Dirt
// ...
var mapData = [
    [0, 0, 0, 0, 0],
    [0, 0, 1, 0, 0,
    ...
]

```

and draw

```
for(var i = 0; i < mapData.length; i++) {
    for(var j = 0; j < mapData[i].length; j++) {
        var p = iso2screen(i, j, 0); // X, Y, Z
        context.drawImage(tileArray[mapData[i][j]], p.x, p.y);
    }
}

```

but this function mean's all tile Z axis is equal to zero.

```
var p = iso2screen(i, j, 0);

```

Maybe anyone have idea and how to do something like `mapData[0][0]` Z axis equal to `3` `mapData[5][5]` Z axis equal to `5`?

I have idea: Write function for grass, dirt and store this function to 2D array and draw and later `mapData[0][0].setZ(3);` But it is good idea to write functions for each tiles?

# Answer
I'm assuming by Z axis we're kind of talking about the 'height' of the tile here.

If you're sure that there would only ever be one tile on each of the X and Y axes (like a heightmap) then you can just modify your map array to store two values rather than a number:

```
// mapData[i][j][0] is the tile Id, mapData[i][j][1] is the Z axis
var mapData = [
    [[0,0], [0,1], [0,0], [0,2], [0,3]],
    [[0,1], [0,0], [1,0, [0,1], [0,2],
    ...
]

```

If you're not sure of this (i.e, you might have caves or overhangs or similar features) then the way to do it is **slices**.

Slices are all the same size (the whole of your map) and you would have one for each and every Z level possible. You would also require a new tile type of 'Nothing', which means you just don't draw anything.

This way is more expensive, but if you need the flexibility it's the way to do it.
> 1 votes

---
Tags: html5, isometric, html-canvas
---


# Question
Title: Enabling and Disabling children in Unity
I'm trying to create an enable/ disable game objects in Unity. I used GameObject.SetActiveRecursively but it only works one-way.

I used a collider in which when an object enters the collider. The game objects become enabled. When they leave or get to a certain point, they disable.

How would I make this a two way system, making it able to be enabled while inside the collider and disabled when outside the collider?

-- The collider is in the game object who is being disabled and enabled.

According to this information from Unity Answers, the object becomes disabled. So how would I make the object enabled?

```
function OnTriggerEnter(other : Collider){
    if(other.tag == "Player"){
        gameObject.SetActiveRecursively(true);

    }
}

function OnTriggerExit(other : Collider){
    if(other.tag == "Player"){
        gameObject.SetActiveRecursively(false);
    }
}

```

# Answer
Let's say you have the following hierarchy:

* ColliderAndScript
    + SetOfMeshes
    + AnotherSetOfMeshes

Attach your script and collider to ColliderAndScript. Add your things you want enabled/disabled as children. Then make your script like this:

```
function OnTriggerEnter (other : Collider) {
    if(other.tag == "Player"){
        for (var child : Transform in transform) {
            child.gameObject.SetActiveRecursively(false);
        }
    }
}

function OnTriggerExit(other : Collider){
    if(other.tag == "Player"){
        for (var child : Transform in transform) {
            child.gameObject.SetActiveRecursively(true);
        }
    }
}

```

This should enable all children when you enter the collider, and disable them when you exit.
> 3 votes

# Answer
If the collider is on an inactive game object, then of course it will never trigger, because it's not even in the game any more.

For something like this, the collider needs to be on a different object to the one you are switching on and off. Have the script on the collider object look up that other object to call SetActiveRecursively on it in both cases.
> 2 votes

---
Tags: unity
---


# Question
Title: Why are my exported illustrator graphics blurry and messy in-game?
Currently I use illustrator to create artwork for my Android games. My art size is pretty small, just 32x32. It looks OK in illustrator, but when exporting, my art is blurry and looks messy! Could you give some advice? How can you get vector-like art? And which is better for small images, pixel art or vector?

My large-size export image:

This is my exported result (The pixel is so bad when zooming):

# Answer
First of all, your exported image should match the size of the sprite in android. So if you're creating 32x32 sized images, your sprites should ideally be rendered as 32x32 on your device screen. Don't expect a 32x32 image to look good when your sprite takes 100x100 pixels on the device!

Exporting vector art from Illustrator to an image (eg. PNG) to use in Android should not be accompanied with any quality loss. Sure, you're losing the scalability of the vector artwork, but when bitmap and vector artwork are both shown at 100% scaling, then they should look identical (if they do not, there's probably a flaw in your workflow).

But it's more likely, that you're experiencing a texture-filturing/mip-mapping issue. Depending on your camera distance, you might see a mip-mapped version of your artwork which would explain the blurred images.

To get an output close to what you see in illustrator, you should disable mip-mapping and probably also set texture-filtering to `GL_NEAREST`. Here's an excellent tutorial about texture-filtering on android.
> 2 votes

---
Tags: graphics, art
---


# Question
Title: Are my programming methods for java games sufficient
so I'm making a 2d Java game with the slick2d and MarteEngine libraries. This is the biggest project since I made checkers for my Java class. I am still pretty new to programming concepts and using optimal ways to get stuff done.

The basic structure of my game is you are a player/hero in a zombie apocalypse and you can gather survivors to help you. There are a many areas that I'm concerned about in my programming. I'm not sure if my methods are a good choice for what I want. This game also does not currently have a grid/tile system.

I've looked at some open source java games and they don't really answer my questions to my methods. So I'm going to make a list here of what I'm uncertain about and I hope you guys can confirm/deny if my methods are appropriate. Sorry if this list gets too long, I'm thinking of the questions as I type.

1. **Targeting/Attacking** \- Survivors will automatically attack zombies once they get within the gun's target range. To do this, I have every survivor get the distance (using distance formula) to every zombie and find the closest one to attack. I check for this constantly so if a faster zombie gets closer, the survivor will change targets. For zombies, they acquire a target and stick to it (for now). The zombies constantly check if they are within the attack range (around 50 pixels) using the distance formula. If they are within range, stop and attack, otherwise, move towards the target.
2. **2D Camera** \- So a camera in a 2D environment moves the world around instead of you. My current method is have my zombies/survivors/any entities on the map stored in array lists. First the background is adjusted, then all the lists are cycled through and every entity's x and y values are modified. This seems to work alright but some stuff you can really notice sliding around on the background. Not really sure how to avoid this.
3. **User Interface** \- I really have no clue how to work with UI. What I've been doing so far is simply using a background and then generating button objects and manually lining them up. Then, I check if the mouse is over any of the button's areas and if there is a click while moused over the button. I have three different backgrounds and buttons that I switch out with booleans. I'm going to recode that area though, using objects with the background and buttons. Is this the correct way to do UI?
4. **Path Finding** \- I have no path finding system yet. Do I have to stick to a grid system? I really rather my entities move freely along the terrain and not in a weird square to square motion.
5. **Selecting** \- I have it so you can select survivors, upgrade them, and other random stuff. My current method for selecting is constantly check where the mouse X and Y is. I get the distance from the mouse to every survivor and check if it is within 30 pixels. Then, I check if there is a click, if so, select the survivor and unselect all others. I'm still trying to figure out how to unselect all survivors if I click on open space. Is there a better way to go about doing this?
6. **Picking stuff up** \- Same way as said before. I check the distance from the player to every item that can be picked up. If the item is within 30 pixels of the player, it picks it up. It seems to work fine for the moment I suppose. Maybe there really is no other way to do this.
7. **Animations** \- I understand the how to animate with sprites, but I just want to make sure. So if I have 7 different guns to be shot, do I need to manually make functions that have precise timing on each sprite. Say if I have a shotgun, it needs a recoil, pump forward, brief pause, pump back, and ready again. For a pistol I need just the recoil really. So I'd have to make unique functions for each of these animations?

Sorry to type this long list of questions. I try to gather information on this stuff as much as possible and I haven't been able to find many examples on this stuff. I greatly appreciated any answers, even just a yes or no answer. Thanks in advance!

# Answer
> 7 votes
* Targeting/Attacking - That's fine. There are optimizations here, but don't worry about those yet.
* 2D Camera - No, that's not the way you do a camera. I'm sure your engine must have a camera class built in. If not, Slick2D has the option to translate. So before drawing your scene, you translate the scene by the 2D camera offset. Then draw your entities at their absolute positions. Don't modify your entity positions!
* Interface - That works OK, but it's hard to maintain. You can checkout some GUI libraries that utilize Slick2D. Many of them use XML files to define the layout of your UI and are easily modifiable. But only switch methods if this is causing problems for you.
* Path Finding - You seem to be confusing path finding with motion. They're not the same thing. You find the path, which will likely be "square to square", then you have your entities follow the path. If you want free motion, you can implement steering and have them steer between the nodes of the path you found. Check out A\*, as that's a popular path finding algorithm.
* Selecting - It would probably be best to have an event system for this (and your other GUI commands). But basically you can do what you're doing now, poll the mouse, find out what's under it. You can either do this constantly, or just when a mouse click happens. Either way, you only want to change the selection when the mouse is clicked. If there's nothing under the mouse, deselect all the survivors.
* Picking stuff up - There are other ways to do this, but this is good enough for a first pass.
* Animations - No, you make one function that has inputs for fire speed, reload rate, etc. That one function calculates the time required to fire a gun. Don't make multiple "unique" functions.

I can tell already that this answer will likely be followed up by even more questions. This question is already border line a discussion, so don't follow up with more questions. Keep doing research. It sounds like you're new enough that looking at open source projects will be far less useful to you than reading through questions and answers on a site like this. So do more research here. Use the "related" links on the right to browse through related questions and just soak in some information. You have a lot to learn, so take your time. When you have more questions, really think about the problem you're facing, *try* to solve it yourself first and if you don't solve it post one question at a time here. Good luck!

# Answer
> 2 votes
1. **Targeting/Attacking** \- Is ok for prototype, but later there could be a room for optimization as when you will have lots of units, performance could drop if you check everyone vs everyone. It may or may be not a problem. You will need to check and see :)
2. **2D Camera ** \- Don't modify entity's position coords.. modify your camera position and while drawing the view, calculate entity space to screen space coords and don't draw if they are outside of your viewport.
3. **Animations** \- make an object that keeps info about current animation frame, start and end frames, and which can draw frames from a to b (for example 30 to 40) with given speed in milliseconds.

---
Tags: 2d, java, slick
---


# Question
Title: Simplified trajectory equation to identify Time Taken(t) by a protectile to travel Distance(d), under gravity?
I am building a game, where I have to plot a trajectory of a ball in 3D space, launched with an inital velocity **Sx, Sy, Sz**. \[*I am using OpenGL and Android-NDK*\]

> Lets assume **Sz** is always **0**. And **Sx** and **Sy** values are known.

Now, I am able to plot a dotted trajectory properly along the path taken by the ball, under uniform gravity. But, the problem is that the distance between the points are NOT EQUIDISTANT, since I am plotting them at regular time intervals.

So, the next step for me is to plot the trajectory at intervals (**tn**) such that my distance traveled (**d**) is always fixed.

> Now, assume I want to plot the **"nth"** trajectory point for every **"d"** units of distance. So, I need **'tn'** to plot it.

I have tried solving this on white board, but the resulting equation for **'tn'** is too complex. And I could get this far :

> **d^2 = dx^2 + dy^2;**
>
> **dx = Sx * t; | t = dx/Sx;**
>
> **dy = Sy * t + 1/2 (g) (t^2); | dy = Sy * (dx/Sx) + 1/2 (g) ((dx/Sx)^2);**
>
> So **t = 'gives me an equation that has a highest order of 4'**;

I am hoping there must be a better way. Can anyone please help me derive a better equation for **'t'**.

> Time **(tn)** = ?; Assume **tn = Tn - T(n-1)**; Where **'Tn'** is total time to cover **'n'** times **'d'** units of distance.
>
> In terms of : **'d'** : is distance interval. (fixed); **'sx'**: initial velocity along x axis (horizotal ground); **'sy'**: initial velocity along y axis (against gravity **'g'**);

Hope, I made thing clear enough. Please let me know if you need more information.

I tried this question in 'physics.stackexchange.com', but I was thinking this might be a more appropriate place to discuss, since I want a perspective of a game developers too.

# Answer
Or, if you don't mind a slightly less pure, but much simpler and good-enough-for-visualisation approach:

Use an approximation to the arc, by connecting points on it with straight lines. Calculating points on this path that are equidistantly spaced should be relatively trivial.
> 2 votes

# Answer
Well, let's try it in 3D:

Assume the dynamics equation: **r(t) = r0 + v0 * t + 0.5\*g\* t^2** where *r* is the position vector, *v0* is the initial launch velocity and *g* is the gravitational constant acceleration vector *(0,0,-9.8)* .

Now let's analyze the length functional: **L(t) = Integral(0,t, ||r'(t)|| dt)** . This means that the total curve length from its beginning (t=0) till this *t* time instance is *L(t)*. In this formula, **||r'(t)||** is the norm of the time derivative of the position function **r(t)**. We know that the norm is actually the square root of the dot product of its argument vector:

**||r'(t)|| = sqrt(dot(r'(t),r'(t))** hence you can analyze this amount:

**r'(t) = v0 + g * t** and therefore **dot(r'(t),r'(t))** = **v0ov0 + 2\*v0og\*t + gog\*t^2** where `o` is the dot product operator (some write it as an angular bracket \< a , b \>, others use a dot which I tried to imitate here with this `o`). This dot product, in your case, is a quadratic function of `t` with nothing more than scalar coefficients in the name of those dot products. Hence, if you can compute a primitive for this **sqrt(dot(r'(t),r'(t))=sqrt(at^2 + bt + c)** where **a=gog**, **b=2v0og**, **c=v0ov0** you're on the right path.

Call this primitive **F(t)**, then **L(t) = F(t) - F(0)**. If you want to know what *t0* instance corresponds to a length on your path of *d0* units, then just compute the inverse of *L(t)* by, what else, computing the inverse function of **F(t)**.

as I am in a hurry, I can't compute the primitive, nor its inverse for you, but if you can't either, do it numerically (numerical integration and then numerical equation solving via Newton's method).

*Later edit:* Use the Wolfram Alpha to find the integral, then perhaps solve numerically for its inverse.. or again Wolfra Alpha
> 1 votes

---
Tags: opengl, android, game-mechanics, projectile-physics, trajectory
---


# Question
Title: My rhythm game runs choppy even with high frame rate
EDIT: \[SOLUTION\] I posted a possibly explanation for my issue below to anyone who has a similar problem. Hope it helps.

I'm coding a rhythm game and the game runs smoothly with uncapped fps. But when I try to cap it around 60 the game updates in little chunks, like hiccups, as if it was skipping frames or at a very low frame rate. The reason I need to cap frame rate is because in some computers I tested, the fps varies a lot (from ~80 - ~250 fps) and those drops are noticeable and degrade response time. Since this is a rhythm game this is very important.

This issue is driving me crazy. I've spent a few weeks already on it and still can't figure out the problem. I hope someone more experienced than me could shed some light on it. I'll try to put here all the hints I've tried along with two pseudo codes for game loops I tried, so I apologize if this post gets too lengthy.

1st GameLoop:

```
const uint UPDATE_SKIP = 1000 / 60;
uint nextGameTick = SDL_GetTicks();

while(isNotDone)
{

    // only false when a QUIT event is generated!
    if (processEvents())
    {
        if (SDL_GetTicks() > nextGameTick)
        {
            update(UPDATE_SKIP);
            render();
            nextGameTick += UPDATE_SKIP;
        }
    }
}

```

2nd Game Loop:

```
    const uint UPDATE_SKIP = 1000 / 60;
    while (isNotDone)
    {
    LARGE_INTEGER startTime;
    QueryPerformanceCounter(&startTime);

    // process events will return false in case of a QUIT event processed
    if (processEvents())
    {
        update(frameTime);
        render();
    }

    LARGE_INTEGER endTime;
    do {
        QueryPerformanceCounter(&endTime);
        frameTime = static_cast<uint>((endTime.QuadPart - startTime.QuadPart) * 1000.0 / frequency.QuadPart);
    } while (frameTime < UPDATE_SKIP);
    }

```

\[1\] At first I thought it was a timer resolution problem. I was using SDL\_GetTicks, but even when I switched to QueryPerformanceCounter, supposedly less granular, I saw no difference.

\[2\] Then I thought it could be due to a rounding error in my position computation and since game updates are smaller in high FPS that would be less noticeable. Indeed there is an small error, but from my tests I realized that it is not enough to produce the position jumps I'm getting. Also, another intriguing factor is that if I enable vsync I'll get smooth updates @60fps regardless frame cap code. So why not rely on vsync? Because some computers can force a disable on gfx card config.

\[3\] I started printing the maximum and minimum frame time measured in 1sec span, in the hope that every a few frames one would take a long time but still not enough to drop my fps computation. It turns out that, with frame cap code I always get frame times in the range of \[16, 18\]ms, and still, the game "does not moves like jagger".

\[4\] My process' priority is set to HIGH (Windows doesn't allow me to set REALTIME for some reason). As far as I know there is only one thread running along with the game (a sound callback, which I really don't have access to it). I'm using AudiereLib. I then disabled Audiere by removing it from the project and still got the issue. Maybe there are some others threads running and one of them is taking too long to come back right in between when I measured frame times, I don't know. Is there a way to know which threads are attached to my process?

\[5\] There are some dynamic data being created during game run. But It is a little bit hard to remove it to test. Maybe I'll have to try harder this one.

Well, as I told you I really don't know what to try next. Anything, I mean, anything would be of great help. What bugs me more is why at 60fps & vsync enabled I get an smooth update and at 60fps & no vsync I don't. Is there a way to implement software vsync? I mean, query display sync info?

Thanks in advance. I appreciate the ones that got this far and yet again I apologize for the long post.

Best Regards from a fellow coder.

# Answer
Well, after a lot of more tests I realized that the problem was either in the way I was measuring time, which I find really unlikely due to the fact that I've tested many timers, or something in the graphics card that was preventing it from rendering to screen, like it was skipping frames.

I found the exact term for that and it made a lot easier to search for the solution after. It's called (macro/micro) stuttering. It can be caused by a whole variety of this, not related to your game (yay! the art of PC game programming).

It could be due to an anti-virus running, instant message programs interference, multi-GPU sincronization (micro stuttering), laptop clock variety due to power consumption settings, intel processors can give errors due to "intel speed stepping" that changes cpu clock based on cpu usage (that would probably mess up with my QFC timer) http://www.intel.com/cd/channel/reseller/ASMO-NA/ENG/203838.htm, it could be a driver problem (nvidia as of today 07/12/12 has a driver bug that causes micro-stuttering in single GPU for GTX 6 card family): http://videocardz.com/33159/nvidia-v-sync-stuttering-caused-by-drivers-bug-fix-coming

Well in my case I realized another particularity, as stated before that enabling vsync fixes the issue. What is probably happening is a tearing effect that gives the illusion of a frame skip, since the camera is fixed I don't see the "tear line", only notes scrolling weirdly. I can't really tell if a tearing is happening because it scrolls so fast, but I'm accepting it for now as vsync fixes the issue.

I hope it helps someone out there struggling with this problem.
> 1 votes

# Answer
My strong suspicion is that your problem is in your usage of UPDATE\_SKIP. When you define:

```
const uint UPDATE_SKIP = 1000 / 60;

```

what you're actually saying is

```
const uint UPDATE_SKIP = 16;

```

—but the problem is that there's no number n that has 16\*n=1000! Essentially, while you may be clamping yourself to 60Hz elsewhere, here in these game loops you're actually running one frame (one call to update()) per 16ms—and those aren't the same thing. That disconnect (which would also occur with UPDATE\_SKIP = 1000/30, since that also isn't an even division) is probably the source of your issue, but without the rest of your code it's hard to say precisely what the correct fix would be - hopefully this will give you more to look at, though...
> 3 votes

# Answer
You should enable VSync. If you are worried with computers forcing it off, add a cap just to make sure. Without VSync, a buffer can be flip (assuming you are using double buffer, if you are not, you really should) while being rendered (I mean, the monitor is reading and displaying it), resulting in an image which part of it is from the previous frame.

Note that for most games, since 99.9% of time one frame is not very different from the next frame, this event is not very visible, but in one game I worked on, when VSync was off, I got an interesting artifact (it was the PC port of an iPhone game, so I was getting like 3000 fps), were a camera shaking algorithm was being applied for different values (since it changed every frame) for different parts of the screen.
> 0 votes

---
Tags: game-loop, frame-rate
---


# Question
Title: How could I expose the engine API for text-adventure games?
While developing an engine for text-adventures I'm still unsure how to expose the API it provides to the developers/writers. My two concepts for now are:

1. Running a small JS engine which executes JS script files (in comparison to a full DSL) where devs/writers can access a well-defined subset of functions and classes.
2. Parsing XML files which define levels, objects, entities, ... so that no real programming knowledge is necessary if the devs/writers stick to the conventions concerning the structure of these files.

Which of these approaches (or even other ones I haven't thought about yet) is more likely to be recommended?

# Answer
> 1 votes
I would recommend XML, XML with XSLT support or YAML.

1) XML is good because of two main reasons: it's human readable format, which anyone can understand and use with minimal training and knowledge, and it's very easy to parse, support and extend, you probably already know that.

2) YAML just like XML is again human readable format, but also offers concise code, I guess they are alike in this matter.

http://www.yaml.org/

3) XML+XSLT is an ideal for me, because XSLT is actually touring complete language, so people can not only define leves and structures, but also implement some logic, for example randomly generating village with loops. But this option will require additional work on a client, and might create some head-ache if you haven't worked with XSLT before.

http://c2.com/cgi/wiki?XsltLanguage

# Answer
> 0 votes
I would go for parsing XML or YAML files with a clear and easily accessible documentation. This way the people who work with them never have to touch real code they might completely screw up.

---
Tags: architecture, text-based, interactive-fiction
---


# Question
Title: High Resolution Timer Options in Windows
I'd like to know what are my options for high resolution timer in Window. I want a timer with at least 1ms precision since I need it for a rhythm game. I'm using QueryPerformanceCounter now, but I read there are many problems I can have with it (variable clock due to laptop power consuption, intel speed stepping, multi-core sync gives negative times, etc).

I tried SDL\_GetTicks() but I realized it is implemented using QPC in Windows. What other options do I have?

Thanks.

# Answer
> 2 votes
QueryPerformanceCounter is a LOT more reliable these days than it was in the earlier days when multicore first appeared. Worst case is that you may have to run a timer on a separate thread, and snoop at it's current time as-required.

You may of course still come across the occasional older machine that still exhibits buggy behaviour though.

The only other real option is timeGetTime. Couple that with a timeBeginPeriod (1) call and you'll get 1ms resolution, but this is a global system-wide change that will affect the performance of Windows' thread scheduler and other apps, so be certain to call timeEndPeriod (1) when done.

Note that it's *possible* that a timeBeginPeriod call is only effective for the duration of the program that makes the call, but I've never had any joy finding confirmation of this behaviour either way so I'd just play safe and use timeEndPeriod.

If you need better than 1ms resolution, one thing I've tried in the past is a main timer that runs off timeGetTime but using QueryPerformanceCounter calls to "fill in the gaps". I've never been fully confident with this approach though and I've long-since junked it.

---
Tags: windows, timer
---


# Question
Title: How to draw lines between user draggable points?
I want to create a triangle using three different points on the SurfaceView using OpenGL. Line indications between the points with one color and fill the triangle with different color. I want to pull those points from existing place to the user desired positions (where ever he wants) on the surface.

How can I do this?

# Answer
I recommend you to start with this tutorial and it's next parts.

Steps for your apps:

1. update positions of points
2. render triangle between these points - set fill color
3. render lines between these points - set line color and width
4. render touch points or circles - set point size and color

Tutorials that might help you with OpenGL ES 2:

That's all to **your question**: How to draw lines between user draggable points?

If you want to know how to drag points ask another question like `How to drag points? [tags: android, input]`.
> 1 votes

# Answer
Without any previous research done, I can only provide a basic guideline:

1. Verify if the mouse click is on a point.
2. Verify mouse position while mouse button is pressed.
3. Draw line at every rendering based on mouse position while mouse button is pressed.
4. When mouse is released, stop listening to mouse position and store new point position.

Hope this helps!
> 0 votes

---
Tags: opengl, 2d, android
---


title: glLoadIdentity or Not?

text:
# Question
Title: glLoadIdentity or Not?
Should I call `glLoadIdentity` each time I render or cumulatively add translations? Does the latter option provide any performance advantage?

**With glLoadIdentity (pseudo-code)**

```
// in game loop
glLoadIdentity();
glTranslatef(position.x, position.y, position.z);
glDrawArrays(...);

// in input handling code
if (KeyDown(LEFT))
  position.x = position.x - 0.01;

```

**Without glLoadIdentity (pseudo-code)**

```
// in game loop
glTranslatef(change_position.x, ...);
glDrawArrays(...);

// in input handling code
if (KeyDown(LEFT))
  change_position.x = -0.01;

```

# Answer
In the old days of OpenGL with the builtin matrix stacks, `glLoadIdentity` served as a simple way of setting the topmost matrix on the stack to the identity matrix.

If you were doing a transform like `T1*R1*S1*T2*R2*S2`, it has the benefit of letting you use the same cumulative form for each of the operations instead of having to overload the first one to be able to replace the existing state instead of multiply with it.

That is, you have:

```
glLoadIdentity();
glTranslatef(..); glRotatef(); glScalef();
glTranslatef(..); glRotatef(); glScalef();

```

instead of a hypothetical:

```
glClearAndTranslatef(..); glRotatef(); glScalef();
glTranslatef(..);         glRotatef(); glScalef();

```

You can compare this to addition or multiplication of scalars - you can always add in the *identity* element for the operation: `1 * a * b` and `0 + c + d`.

Modern matrix libraries tend to eschew the stack model in lieu of matrix objects. As such, there's no real need to have a focus on the *current* object, as all matrices are fairly equal in importance.

You then only really need an identity matrix for when you really need identity, not to clear out the state for a long multiplication.
> 4 votes

---
Tags: opengl
---


title: How do I structure a 2D platform level?

text:
# Question
Title: How do I structure a 2D platform level?
I'm doing a 2D platformer but I don't know how they are usually built.

The approach I'm looking at is making it tilebased, with ground tiles on bottom row, then platforms on some places in "mid-air" within the array.

Then some physics to add gravity to pull the player down if airborn, and just scroll the map horizontally and check for collisions.

Am I on the right track? Thank you.

# Answer
I'm going to share a link with you that someone else had shared with me:

http://higherorderfun.com/blog/2012/05/20/the-guide-to-implementing-2d-platformers/

This page covers several approaches as to how one might implement 2d platformers with both basic and some more advanced mechanics. It doesn't give you straight up code but it does a fantastic job at explaining the techniques so that you should be able to code it without too much trouble.
> 6 votes

# Answer
Try using Tiled, which is a great free map editor. You can build your own level with it, and then load the output file (a XML) into your application (generally Tiled compacts everything with gzip and then converts to base64, but there are libraries to load that).

As for the code, yes. You could see it as a big array.
> 2 votes

# Answer
I would buy the Level UP book: http://www.amazon.com/Level-Up-Guide-Great-Design/dp/047068867X/ref=cm\_cr\_pr\_product\_top This is the only one with a broken spine & dog eared pages currently on my shelf.

Also read the author's blog for awesome ideas, particularly his Platformer Primer: http://mrbossdesign.blogspot.ca/2008/10/platformer-primer.html
> 2 votes

---
Tags: game-design, javascript, html5, platformer
---


title: 3rd party terrain editor

text:
# Question
Title: 3rd party terrain editor
I am looking for a good application for generating 3d terrains (really allowing generation and then some user-editing) . After a google search, I found many, but I need one that can export the entire terrain as a mesh. This, I was unable to find. (I need either a .obj .fbx or .3ds output) The size of the file that is written and the price of the program are not major factors in my decision.

# Answer
> 0 votes
Using Assimp you can convert from a lot of formats to .obj I think that the usability of the tool should be your first priority as the formats can then be converted by your application.

---
Tags: terrain
---


# Question
Title: Code Problem Involving Vertical Movement of Platforms
I am trying to create vertical moving tiles with the Microsoft Platformer Starter Kit. My platforms can move in one direction; however, they fail to switch direction.

If my platform starts at the top, it scrolls down. Once the platform reaches the bottom, however, it fails to move up. I have an issue with

```
if (Level.GetCollision(tileX + (int)direction, tileY) ==

```

in the code below this sentence. It always returns Impassable. Here is my modified code:

```
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Diagnostics;

namespace Platformer
{
//http://robotfootgames.com/xna-tutorials/78-xna-platformer-starter-kit-movable-platforms
public class MovableTile
{
    private Texture2D texture;
    private Vector2 origin;

    public Level Level
    {
        get { return level; }
    }
    Level level;

    public Vector2 Position
    {
        get { return position; }
    }
    Vector2 position;

    public Vector2 Velocity
    {
        get { return velocity; }
    }
    Vector2 velocity;

    /// <summary>
    /// Gets whether or not the player's feet are on the MovableTile.
    /// </summary>
    public bool PlayerIsOn { get; set; }

    public Rectangle BoundingRectangle
    {
        get
        {
            int left = (int)Math.Round(Position.X - ScaleManager.GetNewNumber(origin.X)) + localBounds.X;
            int top = (int)Math.Round(Position.Y - ScaleManager.GetNewNumber(origin.Y)) + localBounds.Y;
            return new Rectangle(left, top, localBounds.Width,
                                localBounds.Height);
        }
    }

    public FaceDirection Direction
    {
        get { return direction; }
        set { direction = value; }
    }

    FaceDirection direction;

    public TileCollision Collision
    {
        get { return collision; }
        set { collision = value; }
    }

    public float WaitTime {
        get {return waitTime;}
        set {WaitTime = value;}
    }

    private TileCollision collision;

    private Rectangle localBounds;
    private float waitTime;
    private const float MaxWaitTime = 2.0f;
    private float MoveSpeed = ScaleManager.GetNewNumber(120.0f);

    public MovableTile(Level level, Vector2 position, TileCollision collision, FaceDirection faceDirection)
    {
        this.level = level;
        this.position = position;
        this.collision = collision;
        this.direction = faceDirection;
        LoadContent();
    }

    public void LoadContent()
    {
        texture = collision == TileCollision.Platform ? Level.Content.Load<Texture2D>("Tiles/Platform") : Level.Content.Load<Texture2D>("Tiles/BlockB0");
        origin = new Vector2(texture.Width / 2.0f, texture.Height / 2.0f);
        localBounds = new Rectangle(0, 0, (int)ScaleManager.GetNewNumber(texture.Width), (int)ScaleManager.GetNewNumber(texture.Height));
    }

    public void Update(GameTime gameTime)
    {
        float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

        // Calculate tile position based on the side we are moving towards.
        float posX = Position.X + localBounds.Width / 2 * (int)direction;
        int tileX = (int)Math.Floor(posX / Tile.Width) - (int)direction;
        int tileY = (int)Math.Floor(Position.Y / Tile.Height);
        if (waitTime > 0)
        {
            // Wait for some amount of time.
            waitTime = Math.Max(0.0f, waitTime - (float)gameTime.ElapsedGameTime.TotalSeconds);
            if (waitTime <= 0.0f)
            {
                // Then turn around.
                direction = (FaceDirection)(-(int)GetVerticalDirection());
                Debug.WriteLine((int)direction);
            }
        }
        else
        {
            // If we are about to run into a wall that is not a MovableTile move in other direction.
            if (Level.GetCollision(tileX + (int)direction, tileY) == TileCollision.Impassable || Level.GetCollision(tileX + (int)direction, tileY) == TileCollision.Platform)
            {
                Debug.WriteLine("Collision: " + Level.GetCollision(tileX + (int)direction, tileY));
                velocity = new Vector2(0.0f, 0.0f);
                waitTime = MaxWaitTime;
            }
            else
            {
                // Move in the current direction.
                int newDirection = GetVerticalDirection();

                if(direction == FaceDirection.Left || direction == FaceDirection.Right)
                {
                    velocity = new Vector2((int)direction * MoveSpeed * elapsed, 0.0f);
                }
                else
                {
                    velocity = new Vector2(0.0f, (int)newDirection * MoveSpeed * elapsed);
                }

                //I need to make velocity.x an even number. otherwise, the tile and player move at different speeds.
                //this causes the player to fall off or glide on the tile, depending on the device
                position = position + new Vector2(Convert.ToInt32(velocity.X), Convert.ToInt32(velocity.Y));
            }
        }

        if (level.movableTiles.Count > 0)
        {
            // If we are about to run into a MovableTile move in other direction.
            foreach (var movableTile in level.movableTiles)
            {
                if (BoundingRectangle != movableTile.BoundingRectangle)
                {
                    if (BoundingRectangle.Intersects(movableTile.BoundingRectangle))
                    {
                        direction = (FaceDirection)(-(int)direction);
                        velocity = new Vector2((int)direction * MoveSpeed * elapsed, 0.0f);
                    }
                }
            }
        }
    }

    public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(texture, Position, null, Color.White, 0.0f, origin, ScaleManager.GetNewNumber(1f), SpriteEffects.None, 0.0f);
    }

    public int GetVerticalDirection()
    {
        int newDirection = 0;
                //get direction
        if(direction == FaceDirection.Up)
        {
            newDirection = 1;
        }
        else if(direction == FaceDirection.Down)
        {
            newDirection = -1;
        }
        else
        {
            newDirection = (int)direction;
        }

        return newDirection;
    }

}

```

}

# Answer
Here is GetCollision. It doesn't seem to get the high and low collisions:

```
public TileCollision GetCollision(int x, int y)
    {
        // Prevent escaping past the level ends.
        if (x < 0 || x >= Width)
            return TileCollision.Impassable;
        // Allow jumping past the level top and falling through the bottom.
        if (y < 0 || y >= Height)
            return TileCollision.Passable;

        return tiles[x, y].Collision;
    }

```

Level Class:

```
    private Tile LoadTile(char tileType, int x, int y)
    {
        switch (tileType)
        {
            // Blank space
            case '.':
                return new Tile(null, TileCollision.Passable);

            // Exit
            case 'X':
                return LoadExitTile(x, y);

            // Gem
            case 'G':
                return LoadGemTile(x, y, Color.YellowGreen, 30, PowerUpType.None);

            //add star
            case 'S':
                return LoadGemTile(x, y, Color.White, 100, PowerUpType.Invincible);

            //add red gem
            case 'L':
                return LoadGemTile(x, y, Color.Red, 1000, PowerUpType.Bonus);

            //add a one up
            case 'O':
                return LoadGemTile(x, y, Color.White, 100, PowerUpType.ExtraLife);

            //Ladder
            case 'H':
                return LoadTile("Ladder", TileCollision.Ladder);

            case '^':
                return LoadSpikeTile(x, y, TileCollision.Spikes);

            // Floating platform
            case '-':
                return LoadTile("Platform", TileCollision.Platform);

            case '2':
                return LoadTile("sand_block", TileCollision.Platform);

            case '3':
                return LoadTile("dirt_block", TileCollision.Platform);

            // Various enemies
            case 'A':
                return LoadEnemyTile(x, y, "MonsterA", 1);
            case 'B':
                return LoadEnemyTile(x, y, "MonsterB", 2);
            case 'C':
                return LoadEnemyTile(x, y, "MonsterC", 1);
            case 'D':
                return LoadEnemyTile(x, y, "MonsterD", 2);

            // Platform block
            case '~':
                return LoadVarietyTile("BlockB", 2, TileCollision.Platform);

            // Passable block
            case ':':
                return LoadVarietyTile("BlockB", 2, TileCollision.Passable);

            // Player 1 start point
            case '1':
                return LoadStartTile(x, y);

            // Impassable block
            case '#':
                return LoadVarietyTile("BlockA", 7, TileCollision.Impassable);

            case '$':
                return LoadTile("BlockC1", TileCollision.Platform);

            // Moving platform - Horizontal
            case 'M':
                return LoadMovableTile(x, y, TileCollision.Platform, FaceDirection.Left, VerticalFaceDirection.None);

            case 'U':
                return LoadMovableTile(x, y, TileCollision.Impassable, FaceDirection.Left, VerticalFaceDirection.Up);

            case 'I':
                return LoadMovableTile(x, y, TileCollision.Impassable, FaceDirection.Left, VerticalFaceDirection.Down);

            // Unknown tile type character
            default:
                throw new NotSupportedException(String.Format("Unsupported tile type character '{0}' at position {1}, {2}.", tileType, x, y));
        }
    }

```

Here is my altered code:

```
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Diagnostics;

namespace GemFinder
{
//http://robotfootgames.com/xna-tutorials/78-xna-platformer-starter-kit-movable-platforms
public enum VerticalFaceDirection
{
    None = 0,
    Up = -1,
    Down = 1
}

public class MovableTile
{

    private Texture2D texture;
    private Vector2 origin;

    public Level Level
    {
        get { return level; }
    }
    Level level;

    public Vector2 Position
    {
        get { return position; }
    }
    Vector2 position;

    public Vector2 Velocity
    {
        get { return velocity; }
    }
    Vector2 velocity;

    /// <summary>
    /// Gets whether or not the player's feet are on the MovableTile.
    /// </summary>
    public bool PlayerIsOn { get; set; }

    public Rectangle BoundingRectangle
    {
        get
        {
            int left = (int)Math.Round(Position.X - ScaleManager.GetNewNumber(origin.X)) + localBounds.X;
            int top = (int)Math.Round(Position.Y - ScaleManager.GetNewNumber(origin.Y)) + localBounds.Y;
            return new Rectangle(left, top, localBounds.Width,
                                localBounds.Height);
        }
    }

    public FaceDirection Direction
    {
        get { return direction; }
        set { direction = value; }
    }

    FaceDirection direction;

    VerticalFaceDirection verticalFaceDirection;
    public VerticalFaceDirection VerticalFaceDirection
    {
        get { return verticalFaceDirection; }
        set { verticalFaceDirection = value; }
    }

    public TileCollision Collision
    {
        get { return collision; }
        set { collision = value; }
    }

    public float WaitTime
    {
        get { return waitTime; }
        set { WaitTime = value; }
    }

    private TileCollision collision;

    private Rectangle localBounds;
    private float waitTime;
    private const float MaxWaitTime = 2.0f;
    private float MoveSpeed = ScaleManager.GetNewNumber(120.0f);

    public MovableTile(Level level, Vector2 position, TileCollision collision, FaceDirection faceDirection, VerticalFaceDirection verticalFaceDirection)
    {
        this.level = level;
        this.position = position;
        this.collision = collision;
        this.direction = faceDirection;
        this.verticalFaceDirection = verticalFaceDirection;
        LoadContent();
    }

    public void LoadContent()
    {
        texture = collision == TileCollision.Platform ? Level.Content.Load<Texture2D>("Tiles/Platform") : Level.Content.Load<Texture2D>("Tiles/BlockB0");
        origin = new Vector2(texture.Width / 2.0f, texture.Height / 2.0f);
        localBounds = new Rectangle(0, 0, (int)ScaleManager.GetNewNumber(texture.Width), (int)ScaleManager.GetNewNumber(texture.Height));
    }

    public void Update(GameTime gameTime)
    {
        float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

        // Calculate tile position based on the side we are moving towards.
        float posX = Position.X + localBounds.Width / 2 * (int)direction;
        float posY = Position.Y + localBounds.Height / 2 * (int)verticalFaceDirection;
        int tileX = (int)Math.Floor(posX / Tile.Width) - (int)direction;
        int tileY = (int)Math.Floor(posY / Tile.Height) - (int)verticalFaceDirection;

        if (waitTime > 0)
        {
            // Wait for some amount of time.
            waitTime = Math.Max(0.0f, waitTime - (float)gameTime.ElapsedGameTime.TotalSeconds);
            if (waitTime <= 0.0f)
            {
                // Then turn around.
                direction = (FaceDirection)(-(int)direction);
                verticalFaceDirection = (VerticalFaceDirection)(-(int)verticalFaceDirection);
            }
        }
        else
        {
            // If we are about to run into a wall that is not a MovableTile move in other direction.
            //check for a vertical collision

            if (verticalFaceDirection != GemFinder.VerticalFaceDirection.None &&

Level.GetCollision(tileX + (int)direction, tileY + (int)verticalFaceDirection) == TileCollision.Impassable || Level.GetCollision(tileX + (int)direction, tileY + (int)verticalFaceDirection) == TileCollision.Platform)
            {
                velocity = new Vector2(0.0f, 0.0f);
                waitTime = MaxWaitTime;
            }
            //check for top of screen
            else if (position.Y <= 0 + Tile.Height / 2 && verticalFaceDirection == GemFinder.VerticalFaceDirection.Up)
            {
                velocity = new Vector2(0.0f, 0.0f);
                waitTime = MaxWaitTime;
            }

            //check for a horizontal collision
            else if (verticalFaceDirection == GemFinder.VerticalFaceDirection.None && Level.GetCollision(tileX + (int)direction, tileY) == TileCollision.Impassable || verticalFaceDirection == GemFinder.VerticalFaceDirection.None && Level.GetCollision(tileX + (int)direction, tileY) == TileCollision.Platform)
            {
                velocity = new Vector2(0.0f, 0.0f);
                waitTime = MaxWaitTime;
            }
            else
            {

                if (verticalFaceDirection == GemFinder.VerticalFaceDirection.None)
                {
                    velocity = new Vector2((int)direction * MoveSpeed * elapsed, 0.0f);
                }
                else
                {
                    velocity = new Vector2(0.0f, (int)verticalFaceDirection * MoveSpeed * elapsed);
                }

                //I need to make velocity.x an even number. otherwise, the tile and player move at different speeds.
                //this causes the player to fall off or glide on the tile, depending on the device
                position = position + new Vector2(Convert.ToInt32(velocity.X), Convert.ToInt32(velocity.Y));
            }
        }

        if (level.movableTiles.Count > 0)
        {
            // If we are about to run into a MovableTile move in other direction.
            foreach (var movableTile in level.movableTiles)
            {
                if (BoundingRectangle != movableTile.BoundingRectangle)
                {
                    if (BoundingRectangle.Intersects(movableTile.BoundingRectangle))
                    {
                        direction = (FaceDirection)(-(int)direction);
                        velocity = new Vector2((int)direction * MoveSpeed * elapsed, 0.0f);
                    }
                }
            }
        }
    }

    public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(texture, Position, null, Color.White, 0.0f, origin, ScaleManager.GetNewNumber(1f), SpriteEffects.None, 0.0f);
    }
}

```

}
> 0 votes

# Answer
It sounds like it's colliding with itself. I have no idea what Level.GetCollision actually does, but I'm assuming that based on its name and call signature that you give it a coordinate and it checks to see if there is anything in the level that exists at that point, and I'm assuming that your tile is a perfectly valid candidate to collide with. The issue might be that you are adding the direction to the x component, not the y component. If you're moving vertically, it would make sense that 'what's coming up' would be a result of adding or subtracting a value from the y component.

```
tileX + (int)direction, tileY

```

should be

```
tileX, tileY + (int)direction

```

That should probably work, assuming that your tileX and tileY calculations are working correctly and producing a spot directly on the edge of your tile.
> 0 votes

# Answer
I would add this to your MovableTile code. Note, I only did the Y axis but the logic could easily be added for Horizontal movement the same way.

Class fields:

```
//Change to the rate of change the platform should move per Update
private const float MovementRate = 5f;

//wherever the platform should start from
private Vector2 _startPosition = new Vector2(50, 50);

//So we know if the direction should be positive or negative
private bool _isMovingDown = false;

//Where 1234 is the Y location to move to
Vector2 _moveTo = new Vector2(0, 1234);

```

Update method:

```
        if (_moveTo != Vector2.Zero)
        {
            //Y-Axis
            if (_isMovingDown)
            {
                if (Position.Y < _moveTo.Y)
                {
                    _isMovingDown = false;
                }
                else
                {
                    Position -= new Vector2(0f, MovementRate);
                }
            }
            else if (Position.Y > _startPosition.Y)
            {
                isMovingDown = true;
            }
            else
            {
                Position += new Vector2(0f, MovementRate);
            }

        }

```
> 0 votes

---
Tags: c#, platformer
---


title: Interval timing in XNA?

text:
# Question
Title: Interval timing in XNA?
I wonder if there is a simple way to use some kind om interval timing in XNA? For example call a method every 10 seconds?

I'm also wondering if there is a way to hide and unhide a sprite when it's on the screen?

Thanks!

# Answer
> 6 votes
### Question 1:

To expand on Jason's answer, I typically handle it by creating a couple variables:

```
float timer = 10;         //Initialize a 10 second timer
const float TIMER = 10;

```

Then in the Update() method, you can then do something like this:

```
public void Update(GameTime gameTime)
{
    float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
    timer -= elapsed;
    if (timer < 0)
    {
        //Timer expired, execute action
        timer = TIMER;   //Reset Timer
    }
}

```

### Question 2:

Create a variable:

```
bool drawSprite = true;

```

Set this variable in your code, depending on where you want to switch it on or off. You could set it inside of your timer action, so it would flip on/off every 10 seconds.

```
if (timer < 0)
{
    drawSprite = !drawSprite;
    timer = TIMER;   //Reset Timer
}

```

Then in your Draw() function:

```
public void Draw()
{
    if (drawSprite)
        //Drawcode
}

```

# Answer
> 1 votes
You could have a timer variable, and add gameTime.ElapsedGameTime to it on every update().

As for your second question: in your draw() function, use an if statement for drawing sprites.

---
Tags: xna
---


# Question
Title: update positition data: change vertex buffer or matrix?
I am writing a small 2D SHMUP for Android at the moment. Pure 2D rendering with Bitmaps turned out to be a bit too slow, especially with a lot of alpha blending going on. So I decided to switch my rendering backend to OpenGL. Last time I used OpenGL there was still immediate mode. I now want to build a modern architecture with OpenGL ES 2.0.

Here are the details: Most of the time I am going to display a lot of Sprites, that are essentially texure mapped quads consisting of 2 triangles each. I am probably going to want to render a lot of them :) I am going to use Vertex Buffers because of the faulty VBO implementation in Froyo.

Here's the question: How would I manage the position data of the independent sprites? Do I need to modify my vertex buffers each time a sprite changes its position? Or is it faster to use a single draw call and translation matrix for each sprite?

# Answer
For a large number of sprites, each of which is just a quad, I'd lean toward using dynamic vertex buffers and drawing them all in one draw call. The sprite bitmaps will all need to be in one atlased texture for this, since you can't switch textures in the middle of a vertex buffer.

Disclaimer, though: my experience is based on PC and console hardware and I'm unfamiliar with the performance tradeoffs on mobile hardware, which might be different.
> 1 votes

---
Tags: opengl, android
---


title: Need some help to move sprite in XNA

text:
# Question
Title: Need some help to move sprite in XNA
when a sprite, like a space ship, reach the window border I call a method to "turn off" the engine by setting the speed to 0. But then it's impossible to move the sprite back, because the speed is set to 0! I would preciate some help to solve this! Perhaps there is another way to do this? Thanks!

Some of the code

```
if (position.X > 800)
EngineOff();

direction = new Vector2((float)Math.Cos(rotation - 1.62), (float)Math.Sin(rotation - 1.62));
position += direction * speed;

```

And the method that controls the engine

```
 // Engine on
    public void EngineOn()
    {
        speed = 1;
    }

    // engine off
    public void EngineOff()
    {
        speed = 0;
    }

```

EDIT: Would it be possible to rotate the ship, so it's point inwards the game area? Would it be possible to rotate it 1/2 of a turn or 1/4 of a turn? My thought was that when the spaceship hit the border, it just turn around and continue moving inwards the game area.

# Answer
> 1 votes
You would need to re-position your ship back so that `if (position.X > 800)` would equal false.

```
if (position.X > 800)
{
   EngineOff();
   position.X = 800;
}

```

Similar to a collision, once the collision occurs you would typically reset your ship's position to the exact point of impact.

# Answer
> 1 votes
Considered that you are already storing the 2D position and the velocity in 2D vectors, what you could easily do is:

```
public void update(dt)
{
    // If needed, depending on user input
    Position.x += Direction.x * speed;
    Position.y += Direction.y * speed;

    checkCollisions();
}

private void checkCollisions()
{
    // if it collides with border
    if (Position.x + this.width >= 800)
    {
        Position.x = 800 - this.width - 2 // -2 to give some more separation
        Direction.x *= -1;
    }
    if (Position.y + this.height >= 800)  // 800 Y border
    {
        Position.y = 800 - this.height - 2 // -2 to give some more separation
        Direction.y *= -1;
    }
    // Similar for X left border, Similar for Y bottom border
}

```

This way, you will mirror the moving direction depending on the collision side pong-style, to speak. You don't really need to set your `speed` to 0 unless you don't want to turn on/off every time there is an user input. To block your sprite, you can add a `bool blocked` property to it and update/process user input only when the sprite is not blocked. If you want to simulate acceleration-style of moving, use the properties `Velocity` and `Acceleration` (2D vectors) as they need to be updated following the standard simple physics equations of accelerated motion. The additional `-2` is added to make sure that a collision is not detected two times consequently by mistake (can happen). Anyway, if the scenario becomes more complicated, consider adopting an easy 2D physics engine.

---
Tags: xna
---


# Question
Title: How to send an int array and struct via ENet?
I've been using the ENet library for networking and so far it's been working ok. I have established a connection between my client and server. On the client side all it does is send all user input to the server. On the server side I have an array `int map[24][24]` that stores all of the map tiles. I also have a struct for each player. After I get all of the user input, do all the calculations, and update the map, how would I send the map back to the client? Right now the function I've been using supports sending chars. Would I convert my int array and struct objects to char and send them? How should I accomplish this, also should I send the map and player structs in one packet, or send each in a separate packet? This is my first to experimenting with multiplayer so I apologize if this is a simple mistake or stupid question.

This is my function for sending packets:

```
void send_packet(int channel, char pack[11]) {
    ENetPacket *packet = enet_packet_create(pack, strlen (pack) + 1, ENET_PACKET_FLAG_RELIABLE);
    enet_peer_send(peer, channel, packet);
    enet_host_flush(host);
}

```

# Answer
> 1 votes
As a result of my comments to the question, i am pasting them here as an answer.

Just pack into the buffer the number of elements 24\*24 and the data itself, you can use memcpy for that. Then just do the reverse in the client to read it back to an array

I think the industry way to handle it is to have well defined packets. So no combining major packets. This also contributes to protocol clarity. A packet is usually a packet id, which translates to a well defined action, like ClientConnected, WorldInfo, SpawnNPC. Then there is usually a operation count, which just increments as packets are sent. A tick id, so you know WHEN it was sent by the other peer. Then, there is the actual data of your packet, like the id of the npc and coordinates of the spawn.

This of course excludes any compression and encryption you may want to implement, which are perfectly possible with these methods.

For a pretty good reference on how to pack and unpack data, check the SFML 2 source code, on the sf::Packet class. Its the best i can think of.

---
Tags: c++, multiplayer
---


title: Supporting Multiple Input Devices

text:
# Question
Title: Supporting Multiple Input Devices
I'm currently developing a PC game with the assistance of XNA and I'm integrating keyboard and gamepad control support. Up until now I've only supported gamepad control, and finding an elegant way to allow the player to choose one or the other is posing a complicated task to resolve.

I was thinking of creating a class that would sort of convert either input into a universal sort of data that the game could then use for the player's character and the rest of the game to interpret.

Then, I thought maybe it would be simpler to create a duplicate of my main character's class, except to accept keyboard input instead of the gamepad input.

Can anybody offer any insight?

# Answer
> I was thinking of creating a class that would sort of convert either input into a universal sort of data that the game could then use for the player's character and the rest of the game to interpret.

This is the right idea. Use a abstract action codes instead of actual Key Codes or Button Codes. Not only does this let you support keyboard + gamepad, it also lets you (or the player) remap controls.
> 4 votes

---
Tags: xna, xna-4.0, input, keyboard, gamepad
---


title: Implementing framerate independence

text:
# Question
Title: Implementing framerate independence
I know the following line of code has the effect of moving 3 units per milliseconds independent of framerate, but my sucky mathematical intuition is unable to understand WHY this works

```
translation *= 3 * (float)gameTime.ElapsedGameTime.TotalMilliSeconds

```

Could someone please explain why this works?

Are there any other common techniques / variations of framerate independent implementations operations like this?

# Answer
Let's say, for the sake of argument, that every frame takes the same amount of time: \\$\Delta t\\$. So if you say that \\$t\\$ milliseconds have elapsed since you started your game, you could also say that (\\$n \cdot \Delta t\\$) milliseconds have passed (\\$n\\$ frames that each took \\$\Delta t\\$ milliseconds).

You're applying the change to the `translation` variable every frame, which you can mathematically think of as multiplying by the number of frames that have passed so far. And using the fact that we already know the units of the number "3" (they are "units per millisecond"), we can put together an equation for the current translation, complete with units:

$$ \text{translation} = (\text{initial translation}) + n\text{ frames} \cdot \left( 3 \frac {\text{units}} {\text{millisecond}} \cdot \Delta t \frac {\text{milliseconds}} {\text{frame}} \right) $$

Let's cancel a few of the units: $$ \require{cancel} \text{translation} = (\text{initial translation}) + n\text{ } \cancel{\text{frames}} \cdot \left( 3 \frac {\text{units}} {\cancel{\text{millisecond}}} \cdot \Delta t \frac {\cancel{\text{milliseconds}}} {\cancel{\text{frame}}} \right) $$

What do we have now?

$$ \begin{align} \text{translation} &= (\text{initial translation}) + (3 \cdot n \cdot \Delta t)\text{ units} \\ &= (\text{initial translation}) + (3 \cdot t)\text{ units} \end{align} $$

Remember that \\$t\\$ is the number of milliseconds that have elapsed since you started your game. That's simple enough! Every time your *t* goes up by one, your translation increases by 3 units. That's the exactly what "3 units per millisecond" means. And that's why it works.

This works even when your velocity (the "3") changes frame-by-frame, as well as when the length of a frame changes. Explaining that properly requires calculus and an explanation of numerical integration. But it basically boils down to this same logic.

---

There are variations of this, yes, but this is by far the most common; it works pretty much anywhere you're adding some value to a variable every frame.
> 7 votes

---
Tags: xna, mathematics, xna-4.0
---


# Question
Title: How do you start modding a game without an editor?
I often come across very impressive mods for PC games that don't have an official editor, other development tools or its source code publicly available. (Take this amazing Multiplayer mod for Just Cause 2, for example.)
How do you go about creating mods for such games?
I'm not talking about replacing the odd texture or 3D model—that sort of thing seems fairly easy given tools to pry them out of game files and put them back in—but more along the lines of adding game behavior. (Tweaking settings files also doesn't count.)

Note that I'm not asking "how to create a mod", I just want to know where to start or where to go to learn.

# Answer
> 3 votes
My answer is kind of two parts.

The first is that generally, you're best off making mods for games that have a high level of support for mod making. Sometimes this stuff can be extremely involved and frankly you want all the help you can get.

Maybe there was a crack team out there that was able to decompile a game and insert their own assets. More likely they got help from the developers and access to their utilities.

Even if you do have those kind of abilities? It's a whole lot easier when someone has built tools for you.

That out of the way, I would suggest looking at the Unreal Development Kit.

Turns out someone really has made the tools for you.

I'm not really sure how to elaborate on this other than to say it's probably far beyond what you need. There's a LOT of material out there on the UDK. A lot of things you can read. And a lot of tutorials.

The development team I'm with is using it ourselves and while I can't speak for everyone I'm finding it to be *excellent*.

I've been working with it for about two weeks now, and not too long ago I was able to make a rocket launcher that fire rockets that when it exploded left a fire behind. A fire which both spread in a line, and dealt damage to anything close by.

Lasers that bounce off walls, cloaking devices? Pretty easy to make a mod for UT3 that includes things like that. Killer Robot Monkey that chases after enemies and breathes swarms of bees at your enemies shouldn't be too hard to program either.

It's kind of only really limited by imagination and performance issues. We're expecting to be able to make a pretty good burning down buildings system going.

I'm currently working on a stealth system. Enemies won't see you if you're in dark areas.

I only mention all of the above to give you an idea of what's feasible (which is a *lot*). There might be a better game and better tools for making mods, but the UDK is probably one of the best. And the fact of the matter is that again, there is a lot of documentation. It's a big part of why we chose it.

---
Tags: modding, pc
---