# Question
Title: Setting the values of a struct array from JS to GLSL
I've been trying to make a structure that will contain all the lights of my WebGL app, and I'm having troubles setting up it's values from JS. The structure is as follows:

```
struct Light {
    vec4 position;
    vec4 ambient;
    vec4 diffuse;
    vec4 specular;
    vec3 spotDirection;
    float spotCutOff;
    float constantAttenuation;
    float linearAttenuation;
    float quadraticAttenuation;
    float spotExponent;
    float spotLightCosCutOff;
};
uniform Light lights[numLights];

```

After testing LOTS of things I made it work but I'm not happy with the code I wrote:

```
program.uniform.lights = [];
    program.uniform.lights.push({
        position: "",
        diffuse: "",
        specular: "",
        ambient: "",
        spotDirection: "",
        spotCutOff: "",
        constantAttenuation: "",
        linearAttenuation: "",
        quadraticAttenuation: "",
        spotExponent: "",
        spotLightCosCutOff: ""
    });

        program.uniform.lights[0].position = gl.getUniformLocation(program, "lights[0].position");
        program.uniform.lights[0].diffuse = gl.getUniformLocation(program, "lights[0].diffuse");
        program.uniform.lights[0].specular = gl.getUniformLocation(program, "lights[0].specular");
        program.uniform.lights[0].ambient = gl.getUniformLocation(program, "lights[0].ambient");

    ... and so on

```

I'm sorry for making you look at this code, I know it's horrible but I can't find a better way.

Is there a standard or recommended way of doing this properly? Can anyone enlighten me?

# Answer
How about something like this?

```
var props = ['position', 'diffuse', 'specular', 'ambient']
for (var i = 0; i!=maxLights; ++i) {
  for (var j in props) {
    prop = props[j];
    eval('program.uniform.lights[' + i + '].' + prop + ' = gl.getUniformLocation(program, "lights[' + i + ']." + prop);
  }
}

```
> 1 votes

---
Tags: shaders, javascript, glsl
---


# Question
Title: Ray picking - get direction from pitch and yaw
I am attempting to cast a ray from the center of the screen and check for collisions with objects.

When rendering, I use these calls to set up the camera:

```
GL11.glRotated(mPitch, 1, 0, 0);
GL11.glRotated(mYaw, 0, 1, 0);
GL11.glTranslated(mPositionX, mPositionY, mPositionZ);

```

I am having trouble creating the ray, however. This is the code I have so far:

```
ray.origin = new Vector(mPositionX, mPositionY, mPositionZ);
ray.direction = new Vector(?, ?, ?);

```

My question is: what should I put in the question mark spots? I.e. how can I create the ray direction from the pitch and roll?

Any help would be much appreciated!

# Answer
You can treat this as a conversion from spherical coordinates to Cartesian coordinates.

Assuming the ray should have some length `r`, your `x`, `y`, and `z` components can be calculated like this:

```
x = r * sin(mPitch) * cos(mYaw)
y = r * sin(mPitch) * sin(mYaw)
z = r * cos(mPitch)

```
> 2 votes

---
Tags: opengl, java, lwjgl, picking
---


# Question
Title: MiniMax function throws null pointer exception
I'm working on a school project, I have to build a tic tac toe game with the AI based on the MiniMax algorithm. The two player mode works like it should.

I followed the code example on http://ethangunderson.com/blog/minimax-algorithm-in-c/. The only thing is that I get a NullPointer Exception when I run the code. And I can't wrap my finger around it.

I placed a comment in the code where the exception is thrown. The recursive call is returning a null pointer, what is very strange because it can't.. When I place a breakpoint on the null return with the help of a if statement, then I see that there ARE still 2 to 3 empty places.. I probably overlooking something.

Hope someone can tell me what I'm doing wrong.

Here is the MiniMax code (the tic tac toe code is not important):

```
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package MiniMax;

import Game.Block;
import Game.Board;
import java.util.ArrayList;

public class MiniMax {
public static Place getBestMove(Board gameBoard, Block.TYPE player) {
    Place bestPlace = null;
    ArrayList<Place> emptyPlaces = gameBoard.getEmptyPlaces();
    Board newBoard;

    //loop trough all the empty places
    for(Place emptyPlace : emptyPlaces) {
        newBoard = gameBoard.clone();
        newBoard.setBlock(emptyPlace.getRow(), emptyPlace.getCell(), player);

        //no game won and still room to move
        if(newBoard.getWinner() == Block.TYPE.NONE && newBoard.getEmptyPlaces().size() > 0) {
            //is an node (has children)
            Place tempPlace = getBestMove(newBoard, invertPlayer(player));

            //ERROR is thrown here! tempPlace is null.
            emptyPlace.setScore(tempPlace.getScore());
        } else {
            //is an leaf
            if(newBoard.getWinner() == Block.TYPE.NONE) {
                emptyPlace.setScore(0);
            } else if(newBoard.getWinner() == Block.TYPE.X) {
                emptyPlace.setScore(-1);
            } else if(newBoard.getWinner() == Block.TYPE.O) {
                emptyPlace.setScore(1);
            }

            //if this move is better then our prev move, take it!
            if((bestPlace == null)
                    || (player == Block.TYPE.X && emptyPlace.getScore() < bestPlace.getScore())
                    || (player == Block.TYPE.O && emptyPlace.getScore() > bestPlace.getScore())) {
                bestPlace = emptyPlace;
            }
        }
    }

    //This should never be null, but it does..
    return bestPlace;
}

private static Block.TYPE invertPlayer(Block.TYPE player) {
    if(player == Block.TYPE.X) {
        return Block.TYPE.O;
    }

    return Block.TYPE.X;
}
}

```

# Answer
> 2 votes
You are only updating `bestPlace` in the second branch of the outermost `if`. Simply put the `if((bestPlace == null)...` block outside that branch so that it gets executed at each iteration:

```
        /* ... */
        } else if(newBoard.getWinner() == Block.TYPE.O) {
            emptyPlace.setScore(1);
        }
    }

    //if this move is better then our prev move, take it!
    if((bestPlace == null)
            || (player == Block.TYPE.X && emptyPlace.getScore() < bestPlace.getScore())
            || (player == Block.TYPE.O && emptyPlace.getScore() > bestPlace.getScore())) {
        bestPlace = emptyPlace;
    }
}
/* ... */

```

---
Tags: java, algorithm, ai
---


# Question
Title: Good baseline size for an A* Search grid?
I'm working on a grid based game/prototype with a continuous open map, and are currently considering what size to make each segment. I've seen some articles mention different sizes, but most of them is really old, so I'm unsure how well they map to the various platforms and performance demands common today.

As for the project, it's a hybrid of 2D and 3D, but for path-finding purposes, the majority of searches would be approximately 2D. From a graphics perspective, the minimum segment size would be 64x64 in the XZ plane to minimize loaded segments while ensuring full screen coverage. I figure pathfinding would be an important indicator of maximum practical size.

Addendum:

I realize I was a bit unclear when talking about sizes and segments.

Each segment is a cubical map of blocks, e.g. 64x64x64 blocks. These represent both geometry, but also if an actor can move into that location and is thus a potential node in the graph.

Each of these segments again combine to a larger square or cubical world map. Neighboring segments are to be loaded dynamically to ensure a seamless local map.

Therefore how many blocks fit into the screen space when rendered, sets a practical minimum for the segments, but we would probably want to have larger segments than the absolute minimum. However, since a block also represents a potential node, the segment size also affects the size of the graph, which have to be considered when choosing a segment size.

# Answer
> 3 votes
Individual units are completely arbitrary and meaningless to the outside world. What matters is the topology of your search space. You need each segment to be small enough to ensure you can reach all the areas of the map that you want to be able to reach, but as big as possible in order to complete the searches more quickly.

---
Tags: path-finding, tilemap
---


title: Deforming surfaces

text:
# Question
Title: Deforming surfaces
I'm trying to accomplish a deforming physic behaviour for level surfaces, but don't have any idea how to start with the implemenation so far.

Regardless of the shape of the surface (planes, cubes, spheres…), I want to have small indentations at the positions from game-entities (players, enemies, objects…).

It's kind of complicated to explain, so I illustrated what I'm talking about, here is an example with a sphere:

So, the surfaces should be able to deform themselves a little bit (to appear like a really soft bed or sofa). My surfaces need probably a high vertices count to get a smooth deforming, but my big problem is the math for calculating this deformation.

I'm programming in C/C++ with OpenGL, but any advices in the right direction will be fine.

# Answer
> 5 votes
For a simple deformation, you can pick a point on the surface/object to manipulate, then apply a transformation (e.g. translation) to it. Then, transform all points within a certain distance from that point the same way, but have the transformation loose strength the further away from the chosen point you are.

So, to make stuff indent under a character, choose the point he/she is standing on and displace it downwards.

Depending on what effect you want to archive, you might want to apply the transform globally, locally or towards/away from the object center and/or use different functions to simulate different materials.

A simple example of indenting a plane using sin/cos falloff functions can be found among www.lighthouse3d.com/opengl/terrain/

---
Tags: opengl, collision-detection, mathematics, physics
---


# Question
Title: fmod getWaveData() export to WAVE file help (C++)
I am trying to export the current sound that is being played by the `FMOD::System` into a WAVE file by calling `getWaveData()`. I have the header of the wave file correct, and currently trying to write to the wave file each frame like so:

```
const unsigned int samplesPerSec = 48000;
const unsigned int fps = 60;
const int numSamples = samplesPerSec / fps;
float data[2][numSamples];
short conversion[numSamples*2];

m_fmodsys->getWaveData( &data[0][0], numSamples, 0 ); // left channel
m_fmodsys->getWaveData( &data[1][0], numSamples, 1 ); // right channel

int littleEndian = IsLittleEndian();

for ( int i = 0; i < numSamples; ++i )
{
    // left channel
    float coeff_left = data[0][i];
    short val_left =  (short)(coeff_left * 0x7FFF);

    // right channel
    float coeff_right = data[1][i];
    short val_right =  (short)(coeff_right * 0x7FFF);

    // handle endianness
    if ( !littleEndian )
    {
        val_left = ((val_left & 0xff) << 8) | (val_left >> 8);
        val_right = ((val_right & 0xff) << 8) | (val_right >> 8);
    }

    conversion[i*2+0] = val_left;
    conversion[i*2+1] = val_right;
}

fwrite((void*)&conversion[0], sizeof(conversion[0]), numSamples*2, m_fh);
m_dataLength += sizeof(conversion);

```

Currently, the timing of the sound is correct, but the sample seems clipped way harshly. More specifically, I am outputting four beats in time. When I playback the wave-file, the beats timing is correct but it just sounds way fuzzy and clipped. Am I doing something wrong with my calculation?

I am exporting in 16-bits, two channels.

Thanks in advance! :)

Reference (WAVE file format): http://www.sonicspot.com/guide/wavefiles.html

# Answer
Your code makes sense to me.

You should break this down into stages:

1. **Confirm the dynamic range of samples from getWaveData()**
Write each sample to a file as a string, then using somethign like Python or Octave (any tool that can read floats from a file, put them in some kind of vector, and then send that to the soundcard automatically) read your samples in and aurally confirm that FMOD itself is correct.
2. **Confirm your quantization step**
Having confirmed that sounds good, take the same data and read it into a C++ program that does the 16 bit quantization and again writes each sample out to a file as readable text.

Now you can read that file in with Python, convert each int you read to a short in raw string format, and write that out to a sound file using the wave module. Play it back in your media player to confirm that it sounds good.

Also maybe consider plotting the data so you can visually spot anomalies (like going outside of the -1 to 1.0 pre-quantization). If it sounds good at each of these stages, then maybe it's time to revisit how you wrote the WAVE header.

Also agreed with Ray Dey, a compare/contrast soundfile would be helpful.
> 1 votes

---
Tags: c++, fmod
---


title: camera movement along with model

text:
# Question
Title: camera movement along with model
I am making a game in which a cube travels along a maze with the motive of crossing the maze safely. I have two problems in this.

1. The cube needs to have a smooth movement like it is traveling on a frictionless surface. So could someone help me achieve this. I need to have this done in a event callback function
2. I need to move the camera along with the cube. So could someone advice me a good tutorial about camera positions along with an object?

# Answer
> 4 votes
Here are some simple steps you can take just to get something up & running quickly, and not to be too ambitious:

(1) For a frictionless effect, it sounds like your cube just needs to maintain a velocity vector (vx,vy,vz). Whenever the user presses a directional key, add or subtract some small fixed amount to this velocity vector.

This way, on each frame, whether or not the user is doing anything, you will move the cube by (velocity * timeElapsed), or even just by (velocity * someConstant). The cube will continue sliding along its current trajectory as though frictionless -- until it collides with a maze wall, that is... but that's collision detection, a whole other topic.

(2) I'm guessing you have the cube's position represented **somewhere** in your code. Well, on each frame take that position and add some fixed distance from it -- this will give you your camera's position for that frame. I suggest to you, initially, just to make your camera look down at the cube (and maze) from some fixed height. For example:

```
cameraPosition = cubePosition + VECTOR(0.0, CAMERA_HEIGHT, 0.0);

```

assuming the +y direction represents "up" in your world... otherwise, add CAMERA\_HEIGHT to the z-coordinate or subtract it from y, or whatever works for you.

Then if you're doing old-skool OpenGL and not shader language:

```
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(
        cameraPosition.x, cameraPosition.y, cameraPosition.z,
        cubePosition.x, cubePosition.y, cubePosition.z,
        0.0, 1.0, 0.0);  // <-- consult the gluLookAt() documentation

    // ... all your other glRotate()/glTranslate() and rendering
    // code for each frame follows here

```

Because the camera's position is cubePosition plus \[some fixed distance\], the camera will "follow" the cube around wherever it moves. In fact, you may find that it follows the cube **too** rigidly and will want to make the camera more loosely tethered -- but initially, keep it simple and just get something working.

In fact, all of this is very rigid and can be played with to get dynamic camera motion, dynamic angles, "tracks" and paths the camera could follow smoothly -- but all of that gets very complicated very quickly. Again, I implore you: initially, just to get things working, keep it simple and just have your camera perched a fixed distance above your cube, looking down onto the cube & maze. Once you get that much in place, feel free to play with it and design something more elaborate. (Just make sure you really sit down and **design** it, and not just cobble things together, otherwise you'll drown yourself in code clutter.)

# Answer
> 1 votes
1. For achieving this effect you only have to update the position of the cube every time you press one of the movement keys. Here is everything you need to know about it.
2. You have to understand that after setting the identity to the modelview, every vertex that is multiplied by that will be in the eye/camera position. Adding a -Z translate will allow you to see the object because the camera by default is looking towards -Z. All its left to do is updating the model position to the camera position and then do the -Z translate. This would be done pretty much like in 1. I'd recommend to understand some basic concepts before implementing anything, here's a good place to start.

---
Tags: opengl, camera, keyboard
---


# Question
Title: what is the best way to add avoidance behaviour to an AI framework?
I have a small AI framework for a shooting based game. Although this is rarely needed, as when agents are close to each other they are usually fighting, I would none the less like some way of implementing avoidance behaviour.

For example, if in the future I wanted to take away their weapons and have many of them wonder around in a crowd, how would I make them not hit / pass through each other, but instead avoid each other? while still following their calculated paths that is.

two ideas I had would be to add steering behaviour and allow that to deviate from their path, or to use a dynamic pathfinding technique. Are these valid solutions? If yes how, in theory, would I implement them? Are there better ways? What is the more respected practice?

# Answer
Make use of flocking.

Flocking combines three steering behaviours, separation, cohesion and alignment.

The idea is that through the combination of these behaviours, more complex, fairly realistic behaviour is created (this is called *emergent behaviour*).

Each agent has a neighbourhood data structure. The neighbourhood can be a simple bounding sphere test to check for the nearest neighbouring agents. Using this data, the 3 behaviours perform certain actions:

**Separation** (Ensure that agents don't get too close together)
*Steer the agent away from the neighbouring agents*

This behaviour iterates through the neighbouring agents, normalizes the vector to the neighbour and divides by the distance to the neighbour. This is then added to the steering force you apply to the agent.

**Alignment** (Used to make sure agents are facing the right direction)
*Steer the agent towards the average heading of neighbouring agents*

This behaviour iterates through the neighbouring agents, calculating the average heading of the neighbours and adds the vector to this average heading to the steering force of the agent.

**Cohesion** (Used to group agents together)
*Steer the agent towards the centre of mass of neighbouring agents*

This behaviour is similar to alignment, but instead of the calculating the average heading, we calculate the average position of the neighbours. Then we add the vector to the centre of mass to the agent's steering force.

***Or***... just make use of a library like OpenSteer.

I'd highly recommend you get Mat Buckland's Programming Game AI by Example. It will answer a lot of questions you have about steering behaviours and provides easy to understand source code.

EDIT:

If you look at OpenSteer and Buckland's book, you will notice that steering behaviours are atomic behaviours. Each behaviour is given some sort of weighting/priority value and the effects of all active behaviours are summed together.

So, to work with pathfinding, a *path-follow* behaviour is also a type of steering behaviour. This means that path-follow and flocking can be weighted, thus combining the effects of both.

Honestly, though, break it down into very small chunks, before you get caught up in integrating components with other components.
> 9 votes

---
Tags: ai
---


# Question
Title: Performing simple network call to retreive JSON in Unity?
I have looked at the network documentation for Unity and most examples seem to be related to networking your game for multiplayer. I am just looking to grab a JSON response from an API for dynamically generating a menu.

Are there some good examples for doing just simple network calls to get a response from a web server?

# Answer
> 2 votes
You go through the WWW class.

http://unity3d.com/support/documentation/ScriptReference/WWW.html

You can do a GET or POST through that, and get the .text from the result when it finishes downloading. There are several C# JSON decoders that you can use instead of parsing the result yourself.

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


# Question
Title: Coarse Collision Detection in highly dynamic environment
I'm currently working a 3D space game with A LOT of dynamic objects that are all moving (there is pretty much no static environment). I have the collision detection and resolution working just fine, but I am now trying to optimize the collision detection (which is currently O(N2) -- linear search). I thought about multiple options, a bounding volume hierarchy, a Binary Spatial Partitioning tree, an Octree or a Grid. I however need some help with deciding what's best for my situation. A grid seems unfeasible simply due to the space requirements and cache coherence problems.

Since everything is so dynamic however, it seems to be that trees aren't ideal either, since they would have to be completely rebuilt every frame. I must admit I never implemented a physics engine that required spatial partitioning, do I indeed need to rebuild the tree every frame (assuming that everything is constantly moving) or can I update the trees after integrating?

Advice is much appreciated - to give some more background: You're flying a space ship in an asteroid field, and there are lots and lots of asteroids and some enemy ships, all of which shoot bullets.

EDIT: I came across the "Sweep an Prune" algorithm, which seems like the right thing for my purposes. It appears like the right mixture of fast building of the data structures involved and detailed enough partitioning. This is the best resource I can find.

If anyone has any suggestions whether or not I'm going in the right direction, please let me know.

# Answer
> 0 votes
I unfortunatelly now don't have time to read about that SAP algorithm, but what I have read few months ago (but I don't know, if it's suitable for your problem, it's much more suitable for points - not objects):

You can use some special case of kd-Tree - for example octree - which uses half partitioning in each axis (in article I have read, they were using quarter partitioning - each axis is split to 4 peaces). You use dynamic version of it.

First you build your structure at the beginning. This means, you split space into kd-Tree. Leaf of tree should have some limited number of objects (for our example let's take 64). Each node knows of course how many objects is in it.

When you update positions of objects, you transfer them also in structures nodes. After that, you update whole structure according to these rules:

1) When inner node has less then limited number of points (sum of its leafs is less then 64), then you merge leafs and inner node becomes leaf.

2) When some leaf has more then 64 objects, you split this node.

If you want, I can try to find that article - when I will have some time.

# Answer
> 1 votes
I don't have enough experience with Sweep-and-Prune to know whether it's a good fit as the highest-level broad-phase algorithm, so I can't comment on that.

You may want to take a look at loose octrees, which are a variation of octrees that are designed for frequent alteration. I'm not sure what the best reference would be, however; I have often heard that loose octrees with k = 2 work pretty well, but I don't have an online source handy.

# Answer
> 1 votes
I'd take a look at dynamic icoseptrees.

1 ) Icoseptrees overall fares very well for large spaces due to its sparse nature. The memory requirements of the tree is directly proportional to the number of objects in the scene.

2 ) You can use it for rendering as well ( in fact, that is the primary application of Icoseptrees ).

3 ) Icoseptrees can deffer optimization of the tree while providing no false negatives.

4 ) Terrific worst case performance.

Icoseptrees loose vs pre processed octrees of static objects, but this is obviously no con for your use case.

---
Tags: c++, collision-detection, physics, optimization
---


# Question
Title: Best way to implement mouse-based movement in MMOG
I want to design an MMO where players click the destination they want to walk to with their mouse and the character moves there, similar to Runescape in this manner.

I think it should be easier than keyboard movement since the client can simply send the server the destination each time the player clicks on a destination.

The main thing I'm trying to decide is what to do when there are obstacles in the way. It's no problem to implement a simple path-finding solution on the client, the question is if the server will do path-finding as well, since it'll probably take too much Computation power from the server.

What I though is that when there is an obstacle the client will send only the first coordinate it plans to go to and then when he gets there he'll send the next coordinate automatically.

For example if there is a rock in the way the character will decide on a route that is made of two destinations so it goes around the rock and when it arrives at the first destination it sends the next coordinate.

That way if the player changes destination is the middle he won't send unnecessary information.

Is this a good way to implement it and is there a standard way MMOGs usually do it?

EDIT: I should also mention that the server will make sure all movements are legal and there aren't any walls in the way etc. In the way I wrote it should be quite easy since all movements will be sent in straight lines so the server will just check there aren't any obstacles along that line.

# Answer
If you don't want to do full path finding on the server, I'd do something like this...

1. Receive click from user
2. Client sends click location to server to see if it is legitimate
3. Client calculates path to click location (if legitimate)
4. Client begins walking along path
5. Server is checking for collisions on each movement
6. In the event of a server-detected collision with an item, the server sends a "cancel path follow" message back to client, and resets the player position back to the last known legal position

You can certainly skip step 2 as theoretically the client will also recognize the click location as not legitimate, assuming it has all the obstacle data to calculate paths.
> 1 votes

# Answer
It's a good idea to make pathfinding an async service that you can offload. Done this way you can have a dedicated server for nothing but pathfinding. Of note is that you will only be pathfinding across small areas with this click idea and therefore **the actual "computation power" required won't be as big as you think**. Measure, measure, measure when performance is concerned =)

It's never a good idea to let the client decide anything about movement. What smooth feeling MMOs do is let the client create a path based on the click and immediately start moving, then the server will return with move updates based on the path it created (like usual) and the client will abandon its own path and simply work from the server's input.

At least that's the way that I've seen it done. I'm looking forwards to following this and seeing other solutions!
> 4 votes

# Answer
If your client has all the information it needs to be able to do the pathfinding correctly, it can do it, and then move the player just by steering it around (as you would for a 1st person game, or a vehicle-based game, etc). The server just needs to validate the position and ensure the player doesn't pass through obstacles as usual.

Otherwise, the server should calculate the path, and then you can choose: either you send that to the client to allow the client to steer, or keep it on the server and move the character directly.

I can see the attraction of wanting to save bandwidth by only sending the destination from the client to the server, but remember that in MMOs you usually use between 5x and 50x as much bandwidth broadcasting your changing position to observers anyway. (Just sending destinations is rarely sufficient there, though I'm sure you can hack it with a few edge cases.)
> 2 votes

---
Tags: networking, mmo, path-finding, movement
---


title: Smooth animation in Cocos2d for iOS

text:
# Question
Title: Smooth animation in Cocos2d for iOS
I move a simple `CCSprite` around the screen of an iOS device using this code:

```
[self schedule:@selector(update:) interval:0.0167];

- (void) update:(ccTime) delta {
    CGPoint currPos = self.position;
    currPos.x += xVelocity;
    currPos.y += yVelocity;

    self.position = currPos;
}

```

This works however the animation is not smooth. **How can I improve the smoothness of my animation?**

My scene is exceedingly simple (just has one full-screen `CCSprite` with a background image and a relatively small `CCSprite` that moves slowly).

I've logged the ccTime delta and it's not consistent (it's almost always greater than my specified interval of 0.0167... sometimes up to a factor of 4x).

I've considered tailoring the motion in the update method to the delta time (larger delta =\> larger movement etc). However given the simplicity of my scene it's seems there's a better way (and something basic that I'm probably missing).

# Answer
> 2 votes
you can try this code:

```
[self schedule:@selector(update:) interval:0.0167];

- (void) update:(ccTime) delta {
    CGPoint currPos = self.position;
    currPos.x += xVelocity * delta;
    currPos.y += yVelocity * delta;

    self.position = currPos;
}

```

this way you are using the delta time provided to you, it means object will move with the same speed no matter how many times update function is called in one second. it also should help your animation look smoother.

---
Tags: animation, cocos2d-iphone, ccsprite
---


title: Movement and Collision with AABB

text:
# Question
Title: Movement and Collision with AABB
I'm having a little difficulty figuring out the following scenarios.

In scenario A, the moving entity has fallen to (and slightly into the floor). The current position represents the projected position that will occur if I apply the acceleration & velocity as usual without worrying about collision. The Next position, represents the corrected projection position after collision check. The resulting end position is the falling entity now rests ON the floor--that is, in a consistent state of collision by sharing it's bottom X axis with the floor's top X axis.

My current update loop looks like the following:

```
// figure out forces & accelerations and project an objects next position
// check collision occurrence from current position -> projected position
   // if a collision occurs, adjust projection position

```

Which seems to be working for the scenario of my object falling to the floor. However, the situation becomes sticky when trying to figure out scenario's B & C.

In scenario B, I'm attempt to move along the floor on the X axis (player is pressing right direction button) additionally, gravity is pulling the object into the floor. The problem is, when the object attempts to move the collision detection code is going to recognize that the object is already colliding with the floor to begin with, and auto correct any movement back to where it was before.

In scenario C, I'm attempting to jump off the floor. Again, because the object is already in a constant collision with the floor, when the collision routine checks to make sure moving from current position to projected position doesn't result in a collision, it will fail because at the beginning of the motion, the object is already colliding.

How do you allow movement along the edge of an object? How do you allow movement away from an object you are already colliding with.

**Extra Info** My collision routine is based on AABB sweeping test from an old gamasutra article, http://www.gamasutra.com/view/feature/3383/simple\_intersection\_tests\_for\_games.php?page=3

My bounding box implementation is based on top left/bottom right instead of midpoint/extents, so my min/max functions are adjusted. Otherwise, here is my bounding box class with collision routines:

```
public class BoundingBox {
    public XYZ topLeft;
    public XYZ bottomRight;

    public BoundingBox(float x, float y, float z, float w, float h, float d)
    {
        topLeft = new XYZ();
        bottomRight = new XYZ();
        topLeft.x = x;
        topLeft.y = y;
        topLeft.z = z;
        bottomRight.x = x+w;
        bottomRight.y = y+h;
        bottomRight.z = z+d;
    }

    public BoundingBox(XYZ position, XYZ dimensions, boolean centered)
    {
        topLeft = new XYZ();
        bottomRight = new XYZ();
        topLeft.x = position.x;
        topLeft.y = position.y;
        topLeft.z = position.z;
        bottomRight.x = position.x + (centered ? dimensions.x/2 : dimensions.x);
        bottomRight.y = position.y + (centered ? dimensions.y/2 : dimensions.y);
        bottomRight.z = position.z + (centered ? dimensions.z/2 : dimensions.z);
    }

    /**
     * Check if a point lies inside a bounding box
     * @param box
     * @param point
     * @return
     */
    public static boolean isPointInside(BoundingBox box, XYZ point)
    {
        if(box.topLeft.x <= point.x && point.x <= box.bottomRight.x
        && box.topLeft.y <= point.y && point.y <= box.bottomRight.y
        && box.topLeft.z <= point.z && point.z <= box.bottomRight.z)
            return true;
        return false;
    }

    /**
     * Check for overlap between two bounding boxes using separating axis theorem
     * if two boxes are separated on any axis, they cannot be overlapping
     * @param a
     * @param b
     * @return
     */
    public static boolean isOverlapping(BoundingBox a, BoundingBox b)
    {
        XYZ dxyz = new XYZ(b.topLeft.x - a.topLeft.x, b.topLeft.y - a.topLeft.y, b.topLeft.z - a.topLeft.z);

        // if b - a is positive, a is first on the axis and we should use its extent
        // if b -a is negative, b is first on the axis and we should use its extent
        // check for x axis separation
        if ((dxyz.x >= 0 && a.bottomRight.x-a.topLeft.x < dxyz.x)
        // negative scale, reverse extent sum, flip equality
          ||(dxyz.x < 0 && b.topLeft.x-b.bottomRight.x > dxyz.x))
            return false;
        // check for y axis separation
        if ((dxyz.y >= 0 && a.bottomRight.y-a.topLeft.y < dxyz.y)
        // negative scale, reverse extent sum, flip equality
          ||(dxyz.y < 0 && b.topLeft.y-b.bottomRight.y > dxyz.y))
            return false;
        // check for z axis separation
        if ((dxyz.z >= 0 && a.bottomRight.z-a.topLeft.z < dxyz.z)
        // negative scale, reverse extent sum, flip equality
          ||(dxyz.z < 0 && b.topLeft.z-b.bottomRight.z > dxyz.z))
            return false;
        // not separated on any axis, overlapping
        return true;
    }

    public static boolean isContactEdge(int xyzAxis, BoundingBox a, BoundingBox b)
    {
        switch(xyzAxis) {
            case XYZ.XCOORD:
                if(a.topLeft.x == b.bottomRight.x || a.bottomRight.x == b.topLeft.x)
                    return true;
                return false;
            case XYZ.YCOORD:
                if(a.topLeft.y == b.bottomRight.y || a.bottomRight.y == b.topLeft.y)
                    return true;
                return false;
            case XYZ.ZCOORD:
                if(a.topLeft.z == b.bottomRight.z || a.bottomRight.z == b.topLeft.z)
                    return true;
                return false;
        }
        return false;
    }

    /**
     * Sweep test min extent value
     * @param box
     * @param xyzCoord
     * @return
     */
    public static float min(BoundingBox box, int xyzCoord)
    {
        switch(xyzCoord) {
            case XYZ.XCOORD:
                return box.topLeft.x;
            case XYZ.YCOORD:
                return box.topLeft.y;
            case XYZ.ZCOORD:
                return box.topLeft.z;
            default: return 0f;
        }
    }

    /**
     * Sweep test max extent value
     * @param box
     * @param xyzCoord
     * @return
     */
    public static float max(BoundingBox box, int xyzCoord)
    {
        switch(xyzCoord) {
            case XYZ.XCOORD:
                return box.bottomRight.x;
            case XYZ.YCOORD:
                return box.bottomRight.y;
            case XYZ.ZCOORD:
                return box.bottomRight.z;
            default: return 0f;
        }
    }

    /**
     * Test if bounding box A will overlap bounding box B at any point
     * when box A moves from position 0 to position 1 and box B moves from position 0 to position 1
     * Note, sweep test assumes bounding boxes A and B's dimensions do not change
     *
     * @param a0 box a starting position
     * @param a1 box a ending position
     * @param b0 box b starting position
     * @param b1 box b ending position
     * @param aCollisionOut xyz of box a's position when/if a collision occurs
     * @param bCollisionOut xyz of box b's position when/if a collision occurs
     * @return
     */
    public static boolean sweepTest(BoundingBox a0, BoundingBox a1, BoundingBox b0, BoundingBox b1, XYZ aCollisionOut, XYZ bCollisionOut)
    {
        // solve in reference to A
        XYZ va = new XYZ(a1.topLeft.x-a0.topLeft.x, a1.topLeft.y-a0.topLeft.y, a1.topLeft.z-a0.topLeft.z);
        XYZ vb = new XYZ(b1.topLeft.x-b0.topLeft.x, b1.topLeft.y-b0.topLeft.y, b1.topLeft.z-b0.topLeft.z);
        XYZ v = new XYZ(vb.x-va.x, vb.y-va.y, vb.z-va.z);

        // check for initial overlap
        if(BoundingBox.isOverlapping(a0, b0))
        {
            // java pass by ref/value gotcha, have to modify value can't reassign it
            aCollisionOut.x = a0.topLeft.x;
            aCollisionOut.y = a0.topLeft.y;
            aCollisionOut.z = a0.topLeft.z;
            bCollisionOut.x = b0.topLeft.x;
            bCollisionOut.y = b0.topLeft.y;
            bCollisionOut.z = b0.topLeft.z;
            return true;
        }

        // overlap min/maxs
        XYZ u0 = new XYZ();
        XYZ u1 = new XYZ(1,1,1);
        float t0, t1;

        // iterate axis and find overlaps times (x=0, y=1, z=2)
        for(int i = 0; i < 3; i++)
        {
            float aMax = max(a0, i);
            float aMin = min(a0, i);
            float bMax = max(b0, i);
            float bMin = min(b0, i);
            float vi = XYZ.getCoord(v, i);

            if(aMax < bMax && vi < 0)
                XYZ.setCoord(u0, i, (aMax-bMin)/vi);
            else if(bMax < aMin && vi > 0)
                XYZ.setCoord(u0, i, (aMin-bMax)/vi);

            if(bMax > aMin && vi < 0)
                XYZ.setCoord(u1, i, (aMin-bMax)/vi);
            else if(aMax > bMin && vi > 0)
                XYZ.setCoord(u1, i, (aMax-bMin)/vi);

        }

        // get times of collision
        t0 = Math.max(u0.x, Math.max(u0.y, u0.z));
        t1 = Math.min(u1.x, Math.min(u1.y, u1.z));
        // collision only occurs if t0 < t1
        if(t0 <= t1 && t0 != 0) // not t0 because we already tested it!
        {
            // t0 is the normalized time of the collision
            // then the position of the bounding boxes would
            // be their original position + velocity*time
            aCollisionOut.x = a0.topLeft.x + va.x*t0;
            aCollisionOut.y = a0.topLeft.y + va.y*t0;
            aCollisionOut.z = a0.topLeft.z + va.z*t0;
            bCollisionOut.x = b0.topLeft.x + vb.x*t0;
            bCollisionOut.y = b0.topLeft.y + vb.y*t0;
            bCollisionOut.z = b0.topLeft.z + vb.z*t0;
            return true;
        }
        else
            return false;
    }
}

```

# Answer
> 2 votes
As always, there are multiple possibilities depending on your objectives (simplicity, speed, accuracy). One easy solution here is to treat each axis independently.

* figure out forces & accelerations and project an objects next position
* check collision occurrence from current position -\> projected position
    + if no collision occurs on x axis then set x to projected position
    + if no collision occurs on y axis then set y to projected position

It is not necessary to use a sweep test for this, a simple intersection test will suffice. The downside of using such a direct approach is that it can still give incorrect results if the destination point results in another collision. The trick to improving the accuracy is to either cap the velocity of the character, or use a small time span, possibly performing collision detection multiple times per frame.

The slightly harder solution which gives better results is to use the sweep test to return the time of collision (or depth vector), then move the character to this point. This is more general purpose and will be more accurate than the other method, it will add additional complexity to the force and acceleration components which need to be scaled according to the time of impact time. The stability of the integrator also becomes more relevant, and multiple simultaneous collision becomes more problematic.

**Edit:**

@Jeremy: You must not reset the position after the collision. Start with the current position and the predicted position. Consider each axis by itself - reducing the problem from n dimensions down to 1. For example: If the object collides at the predicted position on the x axis, you don't do anything, leave the x position unchanged, but if it does not collide on the x axis, the you set the new x position to the predicted x position. Repeat this for the other axes. The (rather crude) result will be that your character can move along an axis as long as there is no collision. Implemented as-is this may result in conditions where your character does not touch the walls or floors but appears to collide a short distance away. Solutions to avoid this are:

1. Use a low velocity so that the change between the current position and predicted position is never more than some acceptable value (say a pixel). Admittedly this is probably the worst and most limiting solution.
2. Use a small time step so that the velocity at any moment is never greater than a threshold (say a pixel). Slightly better than the previous solution, but not very practical as higher velocities will require a smaller time step.
3. Recursively sub-divide the time step to find the closest point to the wall/floor which does not result in a collision. This is a good trade off in terms of performance and complexity. Not the best performance but not overly complex to implement.
4. Update the sweep function to return the time of impact (instead of a true/false value) and use this to scale the projected position based on the time.

For perfect accuracy (for example, if bounce or friction is needed) it may be necessary to sub-divide the simulation step. For example, if you jump towards a wall and the impact occurs half-way through the time step you will need to recalculate the forces at the point of impact, and run the simulation step again with the remaining segment of time. Not that this can result in infinite recursion (for example if two objects are stacked) so some means are necessary to prevent this (i.e. limiting the number of recursions or amount of time spent in the calculation).

---
Tags: java, collision-detection, aabb
---


# Question
Title: Are there any preexisting maps for a Minecraft-like level I could use in my engine?
I am working on a tiny cube-based engine like Minecraft. I was wondering if there is a way for me to get large blocky terrain in a text format that I can use for rendering on my engine?

I don't want to start on procedural generation now, I just want a resource where I can get the coord list for a pretty looking terrain.

Alternatively, is it possible for me to parse the Minecraft world files and use that data to generate terrain/buildings in my code?

# Answer
You could just use plain text files and consider each character in the text file a small tower, with the character saying how tall the tower should be, and pick the material randomly or something..

That's the easiest route I can think of. Apart of procedural generation, which is probably easier.

If you want to use minecraft maps, the format is documented here on the minecraftwiki.net, and a bunch of editors and similar programs are also available, most with source code too, so if the level format is hard to decipher, you have plenty of code as a reference.
> 4 votes

---
Tags: terrain-rendering, minecraft-modding, voxels
---


# Question
Title: What game systems exist which uses camera input?
The group and I is in the middle of a semester project where we are currently researching on which game systems are using camera as input or as an interactive medium? We would like some help listing some of the game systems which uses camera input, as it seems hard to find other examples. Currently we know that webcam browser games uses camera input (Newgrounds webcam games), as well as the xbox kinect. I know this questions seems rather vague, though I still hope some people is capable of helping.

# Answer
> 1 votes
The PS3 (Playstation eye) and PS2 (Eyetoy) also use camera input. I believe the PS2 was the first console to do this.

Technically the Wii also uses camera input, as the wiimote has a camera in it to handle the pointer input style, but I don't think that's the sort of thing you're talking about.

---
Tags: camera, image
---


# Question
Title: 2D Topdown Shooter - Player Movement Relative to Mouse
I'm trying to make a topdown 2D space game for my school project. I'm almost done but I just want to add a few little things to make the game more fun to play.

```
if (keystate.IsKeyDown(Keys.W))
        {
            vPlayerPos += Vector2.Normalize(new Vector2(Mouse.GetState().X - vPlayerPos.X, Mouse.GetState().Y - vPlayerPos.Y)) * 3;

            rPlayer.X = (int)vPlayerPos.X;
            rPlayer.Y = (int)vPlayerPos.Y;
        }

        if (keystate.IsKeyDown(Keys.S))
        {
            vPlayerPos += Vector2.Normalize(new Vector2(Mouse.GetState().X - vPlayerPos.X, Mouse.GetState().Y - vPlayerPos.Y)) * -3;
            rPlayer.X = (int)vPlayerPos.X;
            rPlayer.Y = (int)vPlayerPos.Y;
        }

```

This is what i use to move towards and away from my mouse crossair. I tried to make a somewhat similar function to make it strafe with "A" and "D". But for some reason I just couldn't get it done.

Any thoughts?

# Answer
I assume you mean that forwards and backwards are working fine (from what I can tell they should). In order to move left and right you merely need to make the `Vector2` perpendicular and use almost the exact same logic:

```
public static class Vector2Extensions
{
  public static Vector2 Perpendicular(this Vector2 vector)
  {
    // Swap y and x, and negate y.
    return new Vector2(-vector.Y, vector.X);
  }
}

```

Now your logic would look something like (notice I have improved the layout and made it easier to understand):

```
var mouseState = Mouse.GetState();
var mouseOffset = new Vector2(mouseState.X - vPlayerPos.X, mouseState.Y - vPlayerPos.Y);
var movement = mouseOffset.Normalize()
  // Your game is currently frame-rate dependant, you should be doing this.
  // See: http://gamedev.stackexchange.com/q/19529/1494
  * 3000 * (float)gameTime.ElapsedGameTime.TotalSeconds;
var perpendicular = movement.Perpendicular();

if (keystate.IsKeyDown(Keys.W))
  vPlayerPos += movement;
if (keystate.IsKeyDown(Keys.S))
  vPlayerPos -= movement;

// You might need change the +/- here around.
if (keystate.IsKeyDown(Keys.A))
  vPlayerPos += perpendicular;
if (keystate.IsKeyDown(Keys.D))
  vPlayerPos -= perpendicular;

// You shouldn't do this. If you need them as int cast them when you need them as such.
// rPlayer.X = (int)vPlayerPos.X;
// rPlayer.Y = (int)vPlayerPos.Y;

```

*Side note:* **Good thinking** with using a normalized vector to determine movement, this is probably the 'best' way to do something like this.
> 4 votes

---
Tags: xna, movement, mouse
---


title: XNA advanced rotation 3D

text:
# Question
Title: XNA advanced rotation 3D
I'm able to rotate any model with any angle I want, where I can not rotate my model around a given point.

e.g: My model rotates from the origin assigned in its .fpx file. I want it to rotate related to a point of its bottom plane, so that it is animated as falling

# Answer
Here is a way to rotate a Matrix (model) around a specific point :

```
Vector3 pointToRotateAround = modelWorldTransform.Translation +
                              modelWorldTransform.Down * modelHalfHeight; // modelHalfHeight is meant to represent distance from fbx origin to feet plane

modelWorldTransform.Translation -= pointToRotateAbout;
modelWorldTransform *= Matrix.CreateFromAxisAngle(axis, angle);//angle is the angle to rotate just this frame only
modelWorldTransforms.Translation += pointToRotateAround;

```

pointToRotateAround can be any Vector3 representing a point in 3d space. Make certain that the axis in the Create Method is unit length or your matrix will distort.
> 8 votes

# Answer
You can use CreateFromAxisAngle method from Matrix class. This method will create a rotation matrix about a specific axis for a given angle.

http://msdn.microsoft.com/en-us/library/bb195606(v=XNAGameStudio.40).aspx
> 0 votes

---
Tags: xna, rotation
---


# Question
Title: What is causing these visual artifacts on my OpenGL sprites?
What could be the cause of the defects in my characters sprite? I am using OpenGL ES 2.0. I draw my sprites in a sprite batch that uses UV coordinates from one large texture atlas. If you look around the character' edges, you'll see two noticeable problems:

1. The invisible alpha background is not invisible, but shows a strange static-like background.
2. There are unwanted streaks where the character nears the edge of the frame (but only in some frames of the animation, this happened to be one of them).

Any idea what could be causing these? I will provide related code if asked for, but I'll try to avoid just dumping the entire project and expecting someone to look through it all.

EDIT: Here's a bit of code:

This is how I generate my UV coordinates:

```
private float[] createFrameUV(int frameWidth, int frameHeight, int x, int y){

    float[] uv = new float[4];

    if(numberOfFrames>1){
        float width = (float)frameWidth / (float)mBitmap.getWidth();
        float height = (float)frameHeight / (float)mBitmap.getHeight();
        float u = (float)x / (float)mBitmap.getWidth();
        float v = (float)y / (float)mBitmap.getHeight();

        uv[0] = u;
        uv[1] = v;
        uv[2] = u + width;
        uv[3] = v + height;
    }else{
        uv[0] = 0f;
        uv[1] = 0f;
        uv[2] = 1f;
        uv[3] = 1f;
    }

    return uv;
}

```

These are some OpenGL settings:

```
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
    GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
    GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
    GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);

```

# Answer
Here are a few thoughts :

for your "invisible" background, make sure that your texture has a power of two resolution, and lies in a "drawable-nodpi" resource folder

the strange artifact may be caused by dithering (you can use glDisable(GL\_DITHER) to prevent this)

for your character, it's most likely a problem in your large texture where the pixels around your character are read by the filtering (maybe due to floating point error when computing the uv). I'd suggest leaving some space between two unrelated sprites in your texture atlas.
> 4 votes

# Answer
Looks like two primary causes to me.

First of all, the black lines on the bottom and left of the character look like bilinear sampling artefacts. You can quickly confirm this by switching to nearest neighbour sampling and see if they occur there. One solution might be to add some padding around your sprite images so that bilinear sampling doesn't cause them to bleed into neighbours (or borders).

The background of the sprite looks like a compression aretfact. Are you uploading this image using a compressed format?
> 2 votes

---
Tags: android, java, opengl-es, sprites, opengl-es2
---


# Question
Title: Toon shader with Texture. Can this be optimized?
I am quite new to OpenGL, I have managed after long trial and error to integrate Nehe's Cel-Shading rendering with my Model loaders, and have them drawn using the Toon shade and outline AND their original texture at the same time. The result is actually a very nice Cel Shading effect of the model texture, but it is havling the speed of the program, it's quite very slow even with just 3 models on screen...

Since the result was kind of hacked together, I am thinking that maybe I am performing some extra steps or extra rendering tasks that maybe are not needed, and are slowing down the game? Something unnecessary that maybe you guys could spot?

Both MD2 and 3DS loader have an InitToon() function called upon creation to load the shader

```
initToon(){

    int i;                                                        // Looping Variable ( NEW )
    char Line[255];                                                // Storage For 255 Characters ( NEW )
    float shaderData[32][3];                                    // Storate For The 96 Shader Values ( NEW )
    FILE *In = fopen ("Shader.txt", "r");                        // Open The Shader File ( NEW )

    if (In)                                                        // Check To See If The File Opened ( NEW )
    {
        for (i = 0; i < 32; i++)                                // Loop Though The 32 Greyscale Values ( NEW )
        {
            if (feof (In))                                        // Check For The End Of The File ( NEW )
                break;

            fgets (Line, 255, In);                                // Get The Current Line ( NEW )

            shaderData[i][0] = shaderData[i][1] = shaderData[i][2] = float(atof (Line)); // Copy Over The Value ( NEW )
        }

        fclose (In);                                            // Close The File ( NEW )
    }

    else
        return false;                                            // It Went Horribly Horribly Wrong ( NEW )

    glGenTextures (1, &shaderTexture[0]);                        // Get A Free Texture ID ( NEW )

    glBindTexture (GL_TEXTURE_1D, shaderTexture[0]);            // Bind This Texture. From Now On It Will Be 1D ( NEW )

    // For Crying Out Loud Don't Let OpenGL Use Bi/Trilinear Filtering! ( NEW )
    glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri (GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

    glTexImage1D (GL_TEXTURE_1D, 0, GL_RGB, 32, 0, GL_RGB , GL_FLOAT, shaderData);    // Upload ( NEW )

}

```

This is the drawing for the animated MD2 model:

```
void MD2Model::drawToon() {
    float        outlineWidth    = 3.0f;                                // Width Of The Lines ( NEW )
    float        outlineColor[3]    = { 0.0f, 0.0f, 0.0f };                // Color Of The Lines ( NEW )

// ORIGINAL PART OF THE FUNCTION

    //Figure out the two frames between which we are interpolating
    int frameIndex1 = (int)(time * (endFrame - startFrame + 1)) + startFrame;
    if (frameIndex1 > endFrame) {
        frameIndex1 = startFrame;
    }

    int frameIndex2;
    if (frameIndex1 < endFrame) {
        frameIndex2 = frameIndex1 + 1;
    }
    else {
        frameIndex2 = startFrame;
    }

    MD2Frame* frame1 = frames + frameIndex1;
    MD2Frame* frame2 = frames + frameIndex2;

    //Figure out the fraction that we are between the two frames
    float frac =
        (time - (float)(frameIndex1 - startFrame) /
         (float)(endFrame - startFrame + 1)) * (endFrame - startFrame + 1);

// I ADDED THESE FROM NEHE'S TUTORIAL FOR FIRST PASS (TOON SHADE)

    glHint (GL_LINE_SMOOTH_HINT, GL_NICEST);                // Use The Good Calculations ( NEW )
    glEnable (GL_LINE_SMOOTH);
    // Cel-Shading Code //
    glEnable (GL_TEXTURE_1D);                                    // Enable 1D Texturing ( NEW )
    glBindTexture (GL_TEXTURE_1D, shaderTexture[0]);            // Bind Our Texture ( NEW )

    glColor3f (1.0f, 1.0f, 1.0f);                                // Set The Color Of The Model ( NEW )

// ORIGINAL DRAWING CODE

    //Draw the model as an interpolation between the two frames
    glBegin(GL_TRIANGLES);
    for(int i = 0; i < numTriangles; i++) {
        MD2Triangle* triangle = triangles + i;
        for(int j = 0; j < 3; j++) {
            MD2Vertex* v1 = frame1->vertices + triangle->vertices[j];
            MD2Vertex* v2 = frame2->vertices + triangle->vertices[j];
            Vec3f pos = v1->pos * (1 - frac) + v2->pos * frac;
            Vec3f normal = v1->normal * (1 - frac) + v2->normal * frac;
            if (normal[0] == 0 && normal[1] == 0 && normal[2] == 0) {
                normal = Vec3f(0, 0, 1);
            }
            glNormal3f(normal[0], normal[1], normal[2]);

            MD2TexCoord* texCoord = texCoords + triangle->texCoords[j];
            glTexCoord2f(texCoord->texCoordX, texCoord->texCoordY);
            glVertex3f(pos[0], pos[1], pos[2]);
        }
    }
    glEnd();

// ADDED THESE FROM NEHE'S FOR SECOND PASS (OUTLINE)

    glDisable (GL_TEXTURE_1D);                                    // Disable 1D Textures ( NEW )

    glEnable (GL_BLEND);                                    // Enable Blending ( NEW )
        glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);        // Set The Blend Mode ( NEW )

        glPolygonMode (GL_BACK, GL_LINE);                        // Draw Backfacing Polygons As Wireframes ( NEW )
        glLineWidth (outlineWidth);                                // Set The Line Width ( NEW )

        glCullFace (GL_FRONT);                                    // Don't Draw Any Front-Facing Polygons ( NEW )

        glDepthFunc (GL_LEQUAL);                                // Change The Depth Mode ( NEW )

        glColor3fv (&outlineColor[0]);                            // Set The Outline Color ( NEW )

// HERE I AM PARSING THE VERTICES AGAIN (NOT IN THE ORIGINAL FUNCTION) FOR THE OUTLINE AS PER NEHE'S TUT

        glBegin (GL_TRIANGLES);                                    // Tell OpenGL What We Want To Draw
        for(int i = 0; i < numTriangles; i++) {
        MD2Triangle* triangle = triangles + i;
        for(int j = 0; j < 3; j++) {
            MD2Vertex* v1 = frame1->vertices + triangle->vertices[j];
            MD2Vertex* v2 = frame2->vertices + triangle->vertices[j];
            Vec3f pos = v1->pos * (1 - frac) + v2->pos * frac;
            Vec3f normal = v1->normal * (1 - frac) + v2->normal * frac;
            if (normal[0] == 0 && normal[1] == 0 && normal[2] == 0) {
                normal = Vec3f(0, 0, 1);
            }
            glNormal3f(normal[0], normal[1], normal[2]);

            MD2TexCoord* texCoord = texCoords + triangle->texCoords[j];
            glTexCoord2f(texCoord->texCoordX, texCoord->texCoordY);
            glVertex3f(pos[0], pos[1], pos[2]);
        }
    }
        glEnd ();                                                // Tell OpenGL We've Finished

        glDepthFunc (GL_LESS);                                    // Reset The Depth-Testing Mode ( NEW )

        glCullFace (GL_BACK);                                    // Reset The Face To Be Culled ( NEW )

        glPolygonMode (GL_BACK, GL_FILL);                        // Reset Back-Facing Polygon Drawing Mode ( NEW )

        glDisable (GL_BLEND);
}

```

Whereas this is the drawToon function in the 3DS loader

```
void Model_3DS::drawToon()
{

    float        outlineWidth    = 3.0f;                                // Width Of The Lines ( NEW )
    float        outlineColor[3]    = { 0.0f, 0.0f, 0.0f };                // Color Of The Lines ( NEW )

//ORIGINAL CODE

    if (visible)
    {
    glPushMatrix();

        // Move the model
        glTranslatef(pos.x, pos.y, pos.z);

        // Rotate the model
        glRotatef(rot.x, 1.0f, 0.0f, 0.0f);
        glRotatef(rot.y, 0.0f, 1.0f, 0.0f);
        glRotatef(rot.z, 0.0f, 0.0f, 1.0f);

        glScalef(scale, scale, scale);

        // Loop through the objects
        for (int i = 0; i < numObjects; i++)
        {
            // Enable texture coordiantes, normals, and vertices arrays
            if (Objects[i].textured)
                glEnableClientState(GL_TEXTURE_COORD_ARRAY);
            if (lit)
                glEnableClientState(GL_NORMAL_ARRAY);
            glEnableClientState(GL_VERTEX_ARRAY);

            // Point them to the objects arrays
            if (Objects[i].textured)
                glTexCoordPointer(2, GL_FLOAT, 0, Objects[i].TexCoords);
            if (lit)
                glNormalPointer(GL_FLOAT, 0, Objects[i].Normals);
            glVertexPointer(3, GL_FLOAT, 0, Objects[i].Vertexes);

            // Loop through the faces as sorted by material and draw them
            for (int j = 0; j < Objects[i].numMatFaces; j ++)
            {
                // Use the material's texture
                Materials[Objects[i].MatFaces[j].MatIndex].tex.Use();

// AFTER THE TEXTURE IS APPLIED I INSERT THE TOON FUNCTIONS HERE (FIRST PASS)

                    glHint (GL_LINE_SMOOTH_HINT, GL_NICEST);                // Use The Good Calculations ( NEW )
                    glEnable (GL_LINE_SMOOTH);
                    // Cel-Shading Code //
                    glEnable (GL_TEXTURE_1D);                                    // Enable 1D Texturing ( NEW )
                    glBindTexture (GL_TEXTURE_1D, shaderTexture[0]);            // Bind Our Texture ( NEW )

                        glColor3f (1.0f, 1.0f, 1.0f);                                // Set The Color Of The Model ( NEW )

                glPushMatrix();

                    // Move the model
                    glTranslatef(Objects[i].pos.x, Objects[i].pos.y, Objects[i].pos.z);

                    // Rotate the model

                    glRotatef(Objects[i].rot.z, 0.0f, 0.0f, 1.0f);
                    glRotatef(Objects[i].rot.y, 0.0f, 1.0f, 0.0f);
                    glRotatef(Objects[i].rot.x, 1.0f, 0.0f, 0.0f);

                    // Draw the faces using an index to the vertex array
                    glDrawElements(GL_TRIANGLES, Objects[i].MatFaces[j].numSubFaces, GL_UNSIGNED_SHORT, Objects[i].MatFaces[j].subFaces);

                glPopMatrix();
            }

                glDisable (GL_TEXTURE_1D);                                    // Disable 1D Textures ( NEW )

// THIS IS AN ADDED SECOND PASS AT THE VERTICES FOR THE OUTLINE

    glEnable (GL_BLEND);                                    // Enable Blending ( NEW )
        glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);        // Set The Blend Mode ( NEW )

        glPolygonMode (GL_BACK, GL_LINE);                        // Draw Backfacing Polygons As Wireframes ( NEW )
        glLineWidth (outlineWidth);                                // Set The Line Width ( NEW )

        glCullFace (GL_FRONT);                                    // Don't Draw Any Front-Facing Polygons ( NEW )

        glDepthFunc (GL_LEQUAL);                                // Change The Depth Mode ( NEW )

        glColor3fv (&outlineColor[0]);                            // Set The Outline Color ( NEW )

        for (int j = 0; j < Objects[i].numMatFaces; j ++)
            {
        glPushMatrix();

                    // Move the model
                    glTranslatef(Objects[i].pos.x, Objects[i].pos.y, Objects[i].pos.z);

                    // Rotate the model
                                    glRotatef(Objects[i].rot.z, 0.0f, 0.0f, 1.0f);
                    glRotatef(Objects[i].rot.y, 0.0f, 1.0f, 0.0f);
                    glRotatef(Objects[i].rot.x, 1.0f, 0.0f, 0.0f);

                    // Draw the faces using an index to the vertex array
                    glDrawElements(GL_TRIANGLES, Objects[i].MatFaces[j].numSubFaces, GL_UNSIGNED_SHORT, Objects[i].MatFaces[j].subFaces);

                glPopMatrix();

        }

                glDepthFunc (GL_LESS);                                    // Reset The Depth-Testing Mode ( NEW )

        glCullFace (GL_BACK);                                    // Reset The Face To Be Culled ( NEW )

        glPolygonMode (GL_BACK, GL_FILL);                        // Reset Back-Facing Polygon Drawing Mode ( NEW )

        glDisable (GL_BLEND);

glPopMatrix();
}

```

Finally this is the tex.Use() function that loads a BMP texture and somehow gets blended perfectly with the Toon shading

```
void GLTexture::Use()
{
    glEnable(GL_TEXTURE_2D);                                // Enable texture mapping
    glBindTexture(GL_TEXTURE_2D, texture[0]);                // Bind the texture as the current one

}

```

# Answer
> 1 votes
You are using the old, deprecated immediate mode for drawing your polygons (`glBegin`/`glVertex`/`glEnd` calls). This causes a huge performance impact because you fill up the draw call budget pretty quickly, and multiple synchronous flush commands must be sent to the GPU to draw the triangles.

Just use vertex buffer objects for drawing your models and you will achieve a good overall performance.

---
Tags: c++, opengl, shaders, animation, post-processing
---


title: How to scroll hex tiles?

text:
# Question
Title: How to scroll hex tiles?
I don't seem to be able to find an answer to this one. I have a map of hex tiles. I wish to implement scrolling.

Code at present:

```
drawTilemap = function() {
    actualX = Math.floor(viewportX / hexWidth);
    actualY = Math.floor(viewportY / hexHeight);
    offsetX = -(viewportX - (actualX * hexWidth));
    offsetY = -(viewportY - (actualY * hexHeight));

    for(i = 0; i < (10); i++)
    {
        for(j = 0; j < 10; j++)
        {
            if(i % 2 == 0) {
                x = (hexOffsetX * i) + offsetX;
                y = j * sourceHeight;
            } else {
                x = (hexOffsetX * i) + offsetX;
                y = hexOffsetY + (j * sourceHeight);
            }

            var tileselected = mapone[actualX + i][j];

            drawTile(x, y, tileselected);
        }
    }
}

```

The code I've written so far only handles X movement. It doesn't yet work the way it should do. If you look at my example on jsfiddle.net below you will see that when moving to the right, when you get to the next hex tile along, there is a problem with the X position and calculations that have taken place.

It seems it is a simple bit of maths that is missing. Unfortunately I've been unable to find an example that includes scrolling yet.

http://jsfiddle.net/hd87E/1/

Make sure there is no horizontal scroll bar then trying moving right using the -\> right arrow on the keyboard. You will see the problem as you reach the end of the first tile.

Apologies for the horrid code, I'm learning!

Cheers

# Answer
> 1 votes
Whether hex or not, I'd suggest keeping your location variables (x, y) pointing to the game world, and converting to/from the screen coordinates only when needed. When you convert from screen to world you *add* (cameraX, cameraY) then *divide* by (tileStepX, tileStepY). When you convert from world to screen you *multiply* by (tileStepX, tileStepY) then *subtract* (cameraX, cameraY). Note that there's a minor complication with hexes, which you handle with columnOffset.

Here's a simpler version of your code, with x, y, firstX, firstY in world coordinates:

```
drawTilemap = function() {
    // Convert top left of the screen (0, 0) to world coordinates
    firstX = Math.floor(cameraX / 45);
    firstY = Math.floor(cameraY / 50);

    for( x = firstX; x < firstX + 10; x++ )  // world coordinates
    {
        var columnOffset = oddRowOffset * (x % 2);

        for( y = firstY; y < firstY + 10; y++ )  // world coordinates
        {
            // Make sure this world coordinate is part of the map
            if ( 0 <= y && y < mapone.length && 0 <= x && x < mapone[y].length )
            {
                // Convert world coordinates to screen coordinates
                drawTile((x * tileStepX) - cameraX,
                         (y * tileStepY + columnOffset) - cameraY,
                         mapone[y][x]);
            }
        }
    }
}

```

# Answer
> 0 votes
Found the answer! View here: http://jsfiddle.net/ck6Vq/1/embedded/result/

Not sure if anybody can come up with anything tidier than the code below?

```
drawTilemap = function() {
    firstX = Math.floor(cameraX / 45);
    offsetX = cameraX % 45;
    if(firstX > 0) {
        firstX = firstX - 1;
        offsetX = offsetX + 45;
    }

    console.log(offsetX);

    firstY = Math.floor(cameraY / 50);
    offsetY = cameraY % 50;

    for(x = 0; x < 10; x++)
    {
        var rowOffset = 0;
        var columnOffset = 0;

        if((firstX + x) % 2 == 1)
        {
            columnOffset = oddRowOffset;
        }

        for(y = 0; y < 10; y++)
        {
            drawTile((x * tileStepX) - offsetX,
                     (y * tileStepY) - offsetY + columnOffset,
                     mapone[y+firstY][x+firstX]);
        }
    }
}

```

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


# Question
Title: Direct2d off-screen rendering and hardware acceleration
I'm trying to use direct2d to render images off-screen using WindowsAPICodePack. This is easily achieved using WicBitmapRenderTarget but sadly it's not hardware accelerated.

So I'm trying this route:

1. Create direct3d device
2. Create texture2d
3. Use texture surface to create render target using CreateDxgiSurfaceRenderTarget
4. Draw some shapes

While this renders the image it appears GPU isn't being used at all while CPU is used heavily.

Am I doing something wrong? Is there a way to check whether hardware or software rendering is used?

Code sample:

```
var device = D3DDevice1.CreateDevice1(null,
                DriverType.Hardware,
                null,
                CreateDeviceOptions.SupportBgra,
                FeatureLevel.Ten
                );

var txd = new Texture2DDescription();
txd.Width = 256;
txd.Height = 256;
txd.MipLevels = 1;
txd.ArraySize = 1;
txd.Format = Format.B8G8R8A8UNorm; //DXGI_FORMAT_R32G32B32A32_FLOAT;
txd.SampleDescription = new SampleDescription(1,0);
txd.Usage = Usage.Default;
txd.BindingOptions = BindingOptions.RenderTarget | BindingOptions.ShaderResource;
txd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None;
txd.CpuAccessOptions = CpuAccessOptions.None;

var tx = device.CreateTexture2D(txd);

var srfc = tx.GraphicsSurface;

var d2dFactory = D2DFactory.CreateFactory();

var renderTargetProperties = new RenderTargetProperties
{
    PixelFormat = new PixelFormat(Format.Unknown, AlphaMode.Premultiplied),
    DpiX = 96,
    DpiY = 96,
    RenderTargetType = RenderTargetType.Default,
};

using(var renderTarget = d2dFactory.CreateGraphicsSurfaceRenderTarget(srfc, renderTargetProperties))
{
    renderTarget.BeginDraw();
    var clearColor = new ColorF(1f,1f,1f,1f);
    renderTarget.Clear(clearColor);
    using (var strokeBrush = renderTarget.CreateSolidColorBrush(new ColorF(0.2f,0.2f,0.2f,1f)))
    {
        for (var i = 0; i < 100000; i++)
        {
            renderTarget.DrawEllipse(new Ellipse(new Point2F(i, i), 10, 10), strokeBrush, 2);
        }
    }

    var hr = renderTarget.EndDraw();
}

```

# Answer
> 6 votes
Direct2D is using the GPU unless you specified not to use it... but unfortunately, Direct2D is in fact not as efficient as we would expect. There was a similar question on gamedev forum "Fastest way to draw connected lines?" I ran again the test on your test case and the results are again a bit scary...

When you are trying to draw 10000 ellipse on the screen (size 10,10), the GPU is effectively receiving:

* 1,500,000 vertices =\> 500,000 triangles to render, if you turn off anti-aliasing mode on the render target
* 4,411,734 vertices =\> 1,470,578 triangles to render, with antialias mode enabled (by default in your case)

Because the geometry is not know in advance, whenever you call DrawEllipse between renderTarget.BeginDraw and EndDraw, the part of Direct2D code that needs to run on the CPU is quite intensive, as It needs to generate all those vertices (It as to triangularize the whole surface and generate tiny triangles in order to cover the outer line of the ellipse) and send all commands to the GPU (several hundreds Direct3D10 commands). Each triangle is in fact covering almost a pixel region.

You can lower CPU usage by turning of AntiAliased mode, but then you would have to use AntiAliased post-effects shaders in order to reduce the aliasing.

In order to check this yourself, you can run your application with PIX debugger that is available from DirectX SDK.

On a side note, you should not use WindowsAPICodePack, as It is an API that is not really efficient and not actively maintained. I would suggest you to use SharpDX, which is supporting all Direct2D/DirectWrite features (including callbacks, for example for tessellation, which are not supported by any other managed API).

# Answer
> 1 votes
It does use hardware acceleration, but GPU is used much more less because there is no drawing into visible area. GPU usage depends on cards performance, so if you try this on highend, there will really little GPU usege. When you try that on low end (with enough CPU power), usage will magically raise.

So GPU usage will tell you if acc is on. If RenderTargetType is default, acceleration will be used if supported. If you set hardware, it will be used or error otherwise.

Anyway, if you arent using Direct3D, you should use BitmapRenderTarget, and d2dbitmap as a off-screen buffer. Its faster.

---
Tags: c#, .net, directx10
---


title: WiX installer for XNA 4.0 game?

text:
# Question
Title: WiX installer for XNA 4.0 game?
I'm trying to make a quick installer for my XNA 4.0 game which should be able to install silently. I did some research and figured out that WiX would probably be best for me. I don't like the setup projects inbuilt in Visual Studio 2010, and InstallShield LE doesn't have an XNA 4.0 redistributable.

So, where can I find resources on how to make a WiX installer for an XNA 4.0 game?

I've tried these links, but with no luck. They are targeting a different XNA version, and I want to make sure that a silent install would be supported (while still installing all prerequisites).

Link

http://xnainstaller.codeplex.com/

# Answer
According to the XNA Installer website:

> The presence of the DirectX 9.0c runtime files needed by XNA 4.0 is checked as well as the XNA Framework 4.0 itself. If any of those two don't exist in the target system, the installer will, depending on its configuration, either require the user to install them or automatically install them.

In fact,

> The installer's overhead can be as little as 460 KB (without XNA Framework integrated) or 6.0 MB (including the XNA Framework 4.0) - less than the XNA Framework 4.0 redistributable alone - due to some clever compression tricks.

It looks to me like it will support your XNA 4.0 needs, albeit the project is built for SharpDeveloper, not VS2010. As robust as it is, the XNA Installer source code will be your best resource for achieving your goal. To answer your question, your best bet would be to check the WiX Documentation, and the tutorial linked from it. Alas, I can't post more than 2 hyperlinks. Have a look at the following resources (if you're new to WiX), and customize the XNA Installer source code (which is very well commented, by the way) however you need:

A great bottom-up tutorial describing more robust WiX installer creation.

https://stackoverflow.com/questions/471424/wix-tricks-and-tips

You'll be able to customize for use in VS2010 by changing a few variables and paths dependent on your personal setup, e.g. `<WixToolPath>`, `<WixTargetsPath>` and `<WixTasksPath>` on lines 9-11 of `MyGame.wixproj`. You could alternatively just build the `.wixproj` from the VS command prompt using `msbuild` after you customize to your liking. Hope this helps!
> 11 votes

---
Tags: c#
---


title: Collisions not working as intended

text:
# Question
Title: Collisions not working as intended
I'm making a game, it's a terraria-like game, with 20x20 blocks, and you can place and remove those blocks. Now, I am trying to write collisions, but it isn't working as I want, the collision successfully stops the player from going through the ground, but, when I press a key like A + S, that means if I walk down and left (Noclip is on atm), my player will go into the ground, bug up, and exit the ground somewhere else in the level. I made a video of it. The red text means which buttons I am pressing.

You see, if I press A and S together, I go into the ground. Here is my collision code:

```
Vector2 collisionDist, normal;

private bool IsColliding(Rectangle body1, Rectangle body2)
{
    normal = Vector2.Zero;

    Vector2 body1Centre = new Vector2(body1.X + (body1.Width / 2), body1.Y + (body1.Height / 2));
    Vector2 body2Centre = new Vector2(body2.X + (body2.Width / 2), body2.Y + (body2.Height / 2));

    Vector2 distance, absDistance;

    float xMag, yMag;

    distance = body1Centre - body2Centre;

    float xAdd = ((body1.Width) + (body2.Width)) / 2.0f;
    float yAdd = ((body1.Height) + (body2.Height)) / 2.0f;

    absDistance.X = (distance.X < 0) ? -distance.X : distance.X;
    absDistance.Y = (distance.Y < 0) ? -distance.Y : distance.Y;

    if (!((absDistance.X < xAdd) && (absDistance.Y < yAdd)))
        return false;

    xMag = xAdd - absDistance.X;
    yMag = yAdd - absDistance.Y;

    if (xMag < yMag)
        normal.X = (distance.X > 0) ? xMag : -xMag;
    else
        normal.Y = (distance.Y > 0) ? yMag : -yMag;

    return true;

}

private void PlayerCollisions()
{
    foreach (Block blocks in allTiles)
    {
        collisionDist = Vector2.Zero;
        if (blocks.Texture != airTile && blocks.Texture != stoneDarkTexture && blocks.Texture != stoneDarkTextureSelected && blocks.Texture != airTileSelected && blocks.Texture != doorTexture && blocks.Texture != doorTextureSelected)
        {
            if (IsColliding(player.plyRect, blocks.tileRect))
            {
                if (normal.Length() > collisionDist.Length())
                {
                    collisionDist = normal;
                }

                player.Position.X += collisionDist.X;
                player.Position.Y += collisionDist.Y;

                break;
            }
        }
    }
}

```

I got PlayerCollisions() running in my Update method. As you can see it works partly, but if it runs perfectly, it would be awesome, though I have no idea how to fix this problem. Help would be greatly appreciated.

EDIT:

If I remove the break; it works partly, then it is just the thing that it spasms when it hits two or more blocks at once, like, if I touch 2/3 blocks at once, it does twice the force up. How can I make it so that it only does the force for one block, so it stays correct, and does not spasm? Thanks.

# Answer
> 1 votes
I suggest you have a look at the platformer starter kit provided on MSDN, it has working collision detection code. Download and MSDN Description

Pseudocode:

```
Narrow down tiles to only those adjacent to the player (Excluded from the code below)

Begin loop through tiles
    Check if the current tile is impassable
    Get the bounding rectangle of the tile
    Get the depth of intersection between player and tile bounds
    If depth != (0,0)
        Resolve collision by moving the player using the depth
End loop

Set the new player position

```

The code looks like this (Position is the bottom centre of the player):

```
        // Reset flag to search for ground collision.
        isOnGround = false;

        // For each potentially colliding tile,
        for (int y = topTile; y <= bottomTile; ++y)
        {
            for (int x = leftTile; x <= rightTile; ++x)
            {
                // If this tile is collidable,
                TileCollision collision = Level.GetCollision(x, y);
                if (collision != TileCollision.Passable)
                {
                    // Determine collision depth (with direction) and magnitude.
                    Rectangle tileBounds = Level.GetBounds(x, y);
                    Vector2 depth = RectangleExtensions.GetIntersectionDepth(bounds, tileBounds);
                    if (depth != Vector2.Zero)
                    {
                        float absDepthX = Math.Abs(depth.X);
                        float absDepthY = Math.Abs(depth.Y);

                        // Resolve the collision along the shallow axis.
                        if (absDepthY < absDepthX || collision == TileCollision.Platform)
                        {
                            // If we crossed the top of a tile, we are on the ground.
                            if (previousBottom <= tileBounds.Top)
                                isOnGround = true;

                            // Ignore platforms, unless we are on the ground.
                            if (collision == TileCollision.Impassable || IsOnGround)
                            {
                                // Resolve the collision along the Y axis.
                                Position = new Vector2(Position.X, Position.Y + depth.Y);

                                // Perform further collisions with the new bounds.
                                bounds = BoundingRectangle;
                            }
                        }
                        else if (collision == TileCollision.Impassable) // Ignore platforms.
                        {
                            // Resolve the collision along the X axis.
                            Position = new Vector2(Position.X + depth.X, Position.Y);

                            // Perform further collisions with the new bounds.
                            bounds = BoundingRectangle;
                        }
                    }
                }
            }
        }

        // Save the new bounds bottom.
        previousBottom = bounds.Bottom;

```

This should work in a majority of cases, including moving diagonally.

# Answer
> 0 votes
If you are checking XNA Rectangles for collisions you might want to just use

```
if (body1.Intersects(body2) ...

```

Maybe there is some bug in your custom collision check.

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


title: OpenXDK Questions

text:
# Question
Title: OpenXDK Questions
I was strolling around XBox development. Apart form buying a DevKit from Microsoft, another thing got my attention is called, OpenXDK which stands for Open XBox Development Kit.

From their main site its pretty obvious that there hasn't been any update since 2005 but digging a little deeper, I found that in their project repository is was being updated. *Last time stamp was 2009-02-15.* Quick google search said, its not actually really on a good place to poke around. Many and MANY features are absent. Being a hobby project I perfectly understand. But, those search results/posts/comments are quite old.

The question is, is there anybody who has any experience with OpenXDK? If is, that is it possible to shade some light on this? about its limitations? Is this a mature project? How's the latest version and what's it capable of doing?

Or should I just stay away from it?

# Answer
> 1 votes
The project itself is very outdated, it lacks many many many components that are in the actual XDK, aside from that fact, its for the original Xbox.. In my opinion just stay away from it, you're much better off sticking to personal computers, if you would like to do console development your best chances are to go to XNA (I hate to say it because I hate C#) or applying to work at a developer that does work on Xbox 360.

---
Tags: xbox
---


# Question
Title: How many achievements should I include, and of what challenge?
I know this question is fairy broad and subjective, but I'm wondering if there's been any published research into what an optimal number of achievements is and what kind of challenge they should present. The game this question directly relates to is a shoot-em-up, but an ideal answer is fairly theoretical.

If there are too few achievements, or they are not challenging, I would expect they would fail in their goal to keep people playing. If there are too many, or they are unreasonably difficult, I would expect people to quickly give up. I personally witnessed the latter happening in Starcraft 2; a section of the achievements would have you win hundreds of games against their AI opponents (boring!)

# Answer
> I personally witnessed the latter happening in Starcraft 2; a section of the achievements would have you win hundreds of games against their AI opponents (boring!)

That presupposes that you're actually trying to get that achievement. Most people that get this achievement play AI matches in order to *practice* and get better at the game.

Your overall question really depends on what you want achievements to do. They can have many functions, and not all achievements need to do the same things.

### Design Feedback

It is really important to understand this: achievements were invented for *game designers*, not players. Oh, they have useful psychological effects, but they're really just tools for knowing what someone is doing with the game.

Take Civilization V's Steam Achievements. There are a number of achievements that are basically, "Beat the game with character X." By monitoring these achievements, Civ V's developers can *know* which characters are popular and which are not.

That's why a lot of games have achievements that are basically, "Got this far in the game." They're used to tell how far players progress on average. If you find that most of your players stop 30% of the way through the game, you may want to check to see what happened between your 30% achievement and your 50% achievement.

Not all of your achievements should be for game design achievements. But some certainly should be.

### Grinding Rewards

Like the StarCraft II example you gave, sometimes you just want to give players an award for doing something that isn't itself particularly interesting. This shows how dedicated the player in question is at mastering the game. For a game like SC2, these could be considered rights of passage along your progress as a skilled player.

These generally don't *encourage* grinding. They're rewards, not encouragement. It's a way of saying, "You played our game a lot. Here you go." Some OCD players may actively try to achieve them, but that's not what they're for. They don't really encourage replay; they reward replay that you would have done anyway.

### Behavior Encouragement

This one is mostly for multiplayer games. It can have positive and negative consequences, depending on how well you design them.

Team Fortress 2 has quite a few achievements that reward playing in a certain way. Some of them work well. An achievement for backstabbing a certain number of characters helps to encourage proper play of the Spy class. Some don't, such as the one that encourages Medics to *stop doing their job* and go attack people with their pathetic weapons, *leaving their teammates to die* and **lose the match!**

So... yeah. Make sure that if you're trying to encourage behavior, you don't promote *negative* or abborant behavior. Behavior achievements should encourage play that helps the game.

These generally don't help the replay value. They're there mainly to point the user in the right way of playing the game, and reward them for doing so.

### Challenge Rewards

Challenge rewards are essentially you giving the player something to strive to. They should be difficult to achieve.

These do promote replay value, depending on the kind of challenge. However, it only promotes replay among players who like the particular challenge in question. You need to design these with a firm understanding of what is easy and what is hard in your game. Also, you need to know what is *possible* in the game. And most of all, what your *players* will find enjoyable.

Civ V's set of achievements has quite a few of these. The most famous of which is probably the One City Challenge.

### Accidental Awards

These are mostly *failed* Challenge Rewards. The developers thought something might be a challenge, but the circumstances that might bring it about are either completely out of the player's control, or so unlikely to work that the only way it would happen is by dumb luck.

So when making Challenge Rewards, make sure not to go so far that the player really has no control of when they would even get the chance to pull it off.

### Awesomeness Rewards

A particular intersection of "Behavior Encouragment" and "Challenge Rewards." These recognize that there is some particularly difficult but *cool* that someone could do. You want people to try it, and you want to reward them for pulling it off.

Not all Challenge rewards require awesome behavior. But Awesomeness Rewards are probably the most coveted kind, because getting them is both hard and awesome.

A great example is the TF2 achievement "Be Efficient" A Sniper kills 3 people without missing a shot. It's hard to *make* that happen, but when you finally pull it off, you feel like a boss.

Again, you have the potential issue of encouraging improper behavior. So you make sure that the awesome thing is something that benefits the team and doesn't work against good play.

### Consolation Prizes

The consolation prize is an achievement given because the player screwed up. A lot. It's not designed to encourage behavior, since the behavior it would "encourage" already has plenty of negative stigma on it (like for example, dying a lot). It's mostly a way to point out that fail happened. To you.

Obviously, these don't encourage replay value.
> 20 votes

# Answer
In my opinion, the number of achievements is not important, what is important is that there is something for everyone.

In my mind, there are two objectives for achievements in games.

1. Keep people playing (to gain more achievements)
2. Give palyers bragging rights

Without servicing both goals adding achievements is not worth the effort.

As long as you have a nice linear progresson of difficulty for achievements you'll have some that are easy for everyone, the middle ones will be hard for beginners (but they'll keep playing), the hard ones will be super hard for beginners (but they are served by the easy and medium achievements) but they will be difficult for even advanced players, giving them something to work towards.

Most big games on Steam appaer to have achievements, and the list of them is public along with a percentage of players who unlocked them. I'd recommend checking out some of them. For example, see Left 4 Dead: only 0.6% of players obtained the least obtained achievement and even the easiest (based on percentage) only at 76% of players unlocked it. If you step back and look at the trend of player percentage unlocking a given achievement, its pretty linear from roughly 0% to 75%.
> 2 votes

# Answer
Humans are suckers for small awards, often. They have to be in return of some effort though, in case of a virtual environment like a game.

Look at all the most successful mobile and flash games. People replay levels just to get the full score per level often even. I don't have the reference, but I know I've read summaries from studies that researched the sweet spot for dealing out these rewards. Maybe a 1-2 minute window, for mobile games at least... people keep mining rock to be able to build small things, or keep watering some crops to.. harvest it.. or similar.

Look at the xp and level systems of the old "grinding" games - Diablo 1/2, Everquest, etc... and all MUD's I've seen have had players endlessly playing to get small awards, often in the form of something you can invest to be more efficient next round.

Awards can be explicit like in the above examples but they can be implicit as well, like you feel you do something in the game which required some skill even if the game doesn't tell you.

The most boringly bad games I've played have been those which require little skill and where you have to run endlessly through corridors. Adding a button to push every 30 seconds in the level doesn't help, you need to at least have some small danger or skill effort in between.

In old-skool shoot'em'ups you have a fairly established cycle of enemy waves and a boss to cap it all, in around 2-3 minute cycles.. you want the player to feel the "just one more" thrill. Give the player some points to spread on power ups after each boss to encourage repetitive play even if the enemies start repeating.

Of course there are the other grand achievement awards listed in a lot of the other good answers here, but I'm not sure that they are the ones that actually sell your game to the broad masses by keeping players "jacked in" enough that their friends get curious and have to try the game etc.. they will certainly be nice to the hardcore players, but then again, you have to decide who are your main customers.

Just my 5 cents...
> 0 votes

---
Tags: game-design, social, achievements
---


# Question
Title: How to achieve after-image pixel shader effect
How would one go about writing a pixel shader like this one in XNA 4.0?

http://www.youtube.com/watch?v=f1uZvurrhig&feature=related

# Answer
Go to the shaders section of Microsoft's App Hub XNA samples and start poking around.

The bloom sample demonstrates a similar effect.

To achieve the effect from the video you would want to render the highlights to a buffer, which you then would clear gradually (using a semi-transparent quad), rather than clearing it completely each frame.

(Or you might bounce it between buffers, with a shader that does the appropriate fall-off.)
> 1 votes

# Answer
> How would one go about writing a pixel shader like this one in XNA 4.0?

1. learn how pixel shaders work by researching websites, articles, books.
2. follow various tutorials and gain familiarity and comfort level with HLSL.
3. experiment. experiment. Ask ***specific questions*** about it. Play around till you get it.
> -2 votes

---
Tags: xna-4.0, hlsl, fragment-shader
---


# Question
Title: How to calculate a 3x3 rotation matrix from 2 direction vectors?
I've got 2 direction vectors, for the X axis and the Y axis of the object. How do I calculate the rotation matrix of the object using these?

# Answer
> 17 votes
The basic idea is to use a cross product to generate the extra orthogonal axes of your rotation matrix, based upon the axes that you already have.

```
Matrix3x3 MakeMatrix( Vector3 X, Vector3 Y )
{
    // make sure that we actually have two unique vectors.
    assert( X != Y );

    Matrix3x3 M;
    M.X = normalise( X );
    M.Z = normalise( cross_product(X,Y) );
    M.Y = normalise( cross_product(M.Z,X) );
    return M;
}

```

Note that the above does not make assumptions about X and Y vectors (apart from them not being identical), and does a lot of extra math that it might not have to do in your situation.

For example, in this code I'm doing a second cross-product to be sure our matrix gets an orthogonal Y axis, instead of blindly trusting that the input X and Y axes are precisely 90 degrees apart. If in your situation you are sure that your input axes really are orthogonal to each other, then you can skip the second cross product, and just assign the input Y vector directly, instead of recalculating it.

Note that I'm assuming that your matrix representation has accessible 'X, Y, Z' vector members. Some implementations just expose an array of nine floats instead, in which case the 'X' vector will be either elements 0, 1, and 2, or 0, 3, and 6, depending upon whether the matrix is row-major or column-major. In this (annoying) situation, I usually find that it's easier to just try both ways and see which one works, rather than to search through documentation to try to figure out which ordering your particular matrix implementation is using. :)

Finally, note that depending on your 3D coordinate system's handedness, you may need to multiply M.Z by negative one, in order to generate a legal rotation matrix for your 3D engine.

---
Tags: 3d, rotation, geometry
---


# Question
Title: The true cost to get my XNA game on XBox?
There seem to be many hurdles to get ones game onto Xbox, so far I have uncovered:

1. You need Visual Studio (once your game becomes commercial you cannot use Express - but have to pay for professional). $1000+
2. You then buy a XBox to find you also need a harddrive - so buy a Xbox harddrive too. $400
3. You need to buy XBox Gold LIVE subscription. $70 (Free)
4. You need to buy AppHub Creators Club subscription $100

Then after all that I cannot even find the place on my XBox to download Indie games?!!! Seriously WTF - after doing all this I could have come proficient in WebGL and done it all for free...

**Before I go all the way down this path (hole) are there any other hidden hurdels before I can publish my game?**

UPDATE: "Indie Games are not available in Australia, due to the requirement for all games to be rated by the Australian Classification Board, and the prohibitive expenses involved."....... im going to have to break something....

# Answer
> 11 votes
1. You can commercially release games on the xbox as a live indie game with the express version. I believe you can release PC games too.
2. The xbox you develop on does need a hard-drive.
3. You need (at least) a silver Xbox LIVE account (free).
4. You do need an app hub account.

---

Note, i'm quoting parts of an EULA, but i'm not a lawyer, this is my interpretation of it.

For the first point from the EULA of Xna Game Studio (v4.0):

> i. Commercial Use. Use of any programs developed for the Xbox platform using the software is restricted to your personal, non-commercial use, **with the exception of commercial distribution via Xbox LIVE Marketplace**.

For last 3 points see here: http://msdn.microsoft.com/en-us/library/bb975643.aspx

> At the very least, you will need a Silver Xbox LIVE membership, an App Hub membership, and a hard drive for your Xbox 360 to be able to develop games for Xbox 360 by using XNA Game Studio.

---

Re commercial games on windows, again from the EULA:

> iv. Commercial Programs using Games for Windows LIVE. You may not use the software to develop commercial programs that connect to Games for Windows LIVE.

I interpret that as, you can create commercial games, but not ones that connect to windows live.

# Answer
> 1 votes
So the final total is:

$100 if you already own an Xbox with a hard drive
$300 if you do not already own an Xbox
or
$500 and the endless hardship of dealing with a government that hates video games if you don't own an Xbox and you live in Australia.

Good luck!

---
Tags: xna-4.0, xbox360
---