title: Walkin on terrain - Opengl

text:
# Question
Title: Walkin on terrain - Opengl
i wanna walk to terrain... first i created the terrain

```
void desenha_terreno(float px, float pz){

for (int z = 0; z < iwidth-1; z++)
{
    glBegin(GL_TRIANGLE_STRIP);

    for (int x = 0; x < iheight-1; x++)
    {
        // for each vertex, we calculate the grayscale shade color,
        // we set the texture coordinate, and we draw the vertex.
        /*
           the vertices are drawn in this order:

           0  ---> 1
                  /
                /
             |/
           2  ---> 3
        */

        // draw vertex 0
        glColor3f(terreno[x][z][1]/255.0f, terreno[x][z][1]/255.0f, terreno[x][z][1]/255.0f);
        glTexCoord2f(0.0f, 0.0f);
        glVertex3f(terreno[x][z][0], terreno[x][z][1], terreno[x][z][2]);

        // draw vertex 1
        glTexCoord2f(1.0f, 0.0f);
        glColor3f(terreno[x+1][z][1]/255.0f, terreno[x+1][z][1]/255.0f, terreno[x+1][z][1]/255.0f);
        glVertex3f(terreno[x+1][z][0], terreno[x+1][z][1], terreno[x+1][z][2]);

        // draw vertex 2
        glTexCoord2f(0.0f, 1.0f);
        glColor3f(terreno[x][z+1][1]/255.0f, terreno[x][z+1][1]/255.0f, terreno[x][z+1][1]/255.0f);
        glVertex3f(terreno[x][z+1][0], terreno[x][z+1][1], terreno[x][z+1][2]);

        // draw vertex 3
        glColor3f(terreno[x+1][z+1][1]/255.0f, terreno[x+1][z+1][1]/255.0f, terreno[x+1][z+1][1]/255.0f);
        glTexCoord2f(1.0f, 1.0f);
        glVertex3f(terreno[x+1][z+1][0], terreno[x+1][z+1][1], terreno[x+1][z+1][2]);

    }
    glEnd();
}
}

```

I can move the camera with the functions:

```
void keyboard (unsigned char key, int x, int y) {
if (key=='w')
{
    float xrotrad, yrotrad;
    yrotrad = (yrot / 180 * 3.141592654f);
    xrotrad = (xrot / 180 * 3.141592654f);
    xpos += float(sin(yrotrad))*5;
    zpos -= float(cos(yrotrad))*5;
    ypos -= float(sin(xrotrad))*5;

}

if (key=='s')
{
    float xrotrad, yrotrad;
    yrotrad = (yrot / 180 * 3.141592654f);
    xrotrad = (xrot / 180 * 3.141592654f);
    xpos -= float(sin(yrotrad))*5;
    zpos += float(cos(yrotrad))*5;
    ypos += float(sin(xrotrad))*5;
}

if (key=='d')
{
    float yrotrad;
    yrotrad = (yrot / 180 * 3.141592654f);
    xpos += float(cos(yrotrad))*5;
    zpos += float(sin(yrotrad))*5;
}

if (key=='a')
{
    float yrotrad;
    yrotrad = (yrot / 180 * 3.141592654f);
    xpos -= float(cos(yrotrad))*5;
    zpos -= float(sin(yrotrad))*5;
}

if (key=='q')
{
    yrot += (float) -0.5*5;    //set the xrot to yrot with the addition of the difference in the x position
}

if (key=='e')
{
    yrot += (float) 0.5*5;    //set the xrot to yrot with the addition of the difference in the x position
}

if (key=='r')
{
    xrot += (float) -0.5*5;    //set the xrot to yrot with the addition of the difference in the x position
}

if (key=='f')
{
    xrot += (float) 0.5*5;    //set the xrot to yrot with the addition of the difference in the x position
}

if (key==27)
{
    exit(0);
}

glutPostRedisplay();
`

```

and, i change the position with the values of x,y,z positions

```
    // clear screen and depth buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();

//glTranslatef(0.0f, 0.0f, -cRadius);
glRotatef(xrot,1.0,0.0,0.0);
glRotatef(yrot,0.0,1.0,0.0);  //rotate our camera on the    y-axis (up and down)

glTranslated(-xpos,-ypos,-zpos); //translate the screen to the position of our camera

// set the camera position
//gluLookAt(cameraX, cameraY, cameraZ, lookX, lookY, lookZ, 0.0, 1.0, 0.0);

// set the current texture to the land texture
//glBindTexture(GL_TEXTURE_2D, land);

    desenha_terreno(xpos,ypos);
    glEnable(GL_BLEND);

// enable read-only depth buffer
glDepthMask(GL_FALSE);

// set the blend function to what we use for transparency
glBlendFunc(GL_SRC_ALPHA, GL_ONE);

// set back to normal depth buffer mode (writable)
glDepthMask(GL_TRUE);

// disable blending
glDisable(GL_BLEND);

    glFlush();

    glutSwapBuffers();

    angle++; //increase the angle
   }

```

well... i need to walk to the terrain, above the terrain, help me please!

# Answer
The answer is very simple.

When you render terrain you supply 3 values, x,y,z. Lets assume that z value is height. So when walking you just need to keep camera above z value! You get camera x,y query height in that spot and place camera above z value.When there is no z value for this spot interpolate from near by points.

Thats all.

You also may want to keep camera some constant above terrain itself (to give illusion of being physical character).

You also may want to put all height in one array. And assume that x and y change by const interval, to simplify your terrain generation. And you get height-map!
> 4 votes

# Answer
You may have some luck with using gluLookAt() to manipulate the camera. It'd probably be easier to move the camera position and the point that it's looking at instead of rotating the camera yourself. This would also simplify doing things like "looking around" from a stationary point.
> 0 votes

# Answer
The best way to make sure you're above a triangle is to use barycentric coordinates. In short, this is a coordinate system local to a triangle that allows you to get the height of a point somewhere in the interior of the triangle.

So your algorithm would go something like:

* Get the camera/player position
* Figure out what triangle that player is on (assuming you have a regular grid of triangles in the (x,y) plane this should be trivial).
* Using the 3 points of that triangle convert the camera point to triangle space and use the barycentric coordinates to solve for the height.
* Unproject it from triangle space back to world space and you'll have the point on the triangle where the camera should be. You'll probably want to move this up so that it appears the camera is on the terrain proper.
> 0 votes

---
Tags: c++, c, opengl, 3d
---


# Question
Title: Vector problem: which one is the left / centre / right one?
In aviation, runways are named according to their magnetic orientation seen from the pilot's perspective. For example: a strip of asphalt oriented along the east-west axis will be named `9` for the pilot coming from west (east is at 90° from North) and `27` for a pilot coming from east (west is 270° from North).

When several runways have the same orientation, the naming convention uses letters L/C/R for distinguishing between the Left/Centre/Right ones (look at the `22` runways in the capture above).

In the game I'm coding, I chose to describe runways by the following three attributes:

* **Orientation** (between 0° and 180°).
* **Position of their geometrical centre** relative to the aeroport one.
* **Length**

With this data I'm able to generate all the touchdown points and give them the correct *number*, but I can't find a straightforward method to assign the correct *letter*, as **I could not think to a straightforward way to mathematically determine which one is "left/centre/right"** from a "landing pilot's perspective".

So the question is:

> **Is there a simple, straightforward vector formula that - given two parallel vectors pointing in the same direction - will return the leftmost (or rightmost) one?**

Please note that **this question is really about the *straightforwardness* of the formula**, as I already found a *non-straightforward* way to get the result, but I would like to find a more elegant way to solve the problem.

Many thanks in advance for your expertise and contributions!

# Answer
> 7 votes
Of course there is. Compute the determinant of the orientation vector of the runways and the vector from one runway centre to another, the result will be positive or negative depending on which runway are to the right of the other.

Calculation of determinant for a pair of 2D vectors:

```
Det(A,B) = Ax*By - Ay*Bx

```

There is a load of other stuff one can learn about the use of determinants, but for this purpose it's all you need to know.

**Edit, same thing in different words:**
Compute the dot product of the orientation vector of the runways and the tværvector of the vector from one runway centre to another, the result will be positive or negative depending on which runway are to the right of the other.

```
DotProduct(A,B) = Ax*Bx + Ay*By

```

A tværvector is the rotation of a 2D vector 90 degrees counter-clockwise. The tværvector T of A is calculated as follow:

```
Tx = -Ay
Ty = Ax

```

**Edit, I guess I should try to explain why this works.**
The result of a dot product is equal to the product of the length of the two vectors, by the cosine of the angle between them. Since lengths are always positive and cosine is positive for angles in the range `]-90 deg; 90 deg[` the dot product is positive for acute angles, and negative for obtuse angles.

Imagine two parallel lines and a vector from any point on line 1 to any point on line 2, this vector may point in any direction within a 180 degrees arc, except from the two extremes. If we rotate this vector 90 degrees we also rotate the arc 90 degrees. This rotated arc is positioned exactly so that a vector parallel to the lines will either have an acute angle to all vectors within the arc, or an obtuse angle to all of them, depending on the position of the lines and the direction of the vector. Since the dot product works as an acute/obtuse test it can be used to tell whether a line is to the right of left of another, depending on which direction you look at them.

# Answer
> 2 votes
Compute a vector perpendicular to the runways that share an orientation, in such a fashion that it always points in a particular direction (right, for example) as seen from the runway's perspective. As you have the orientation, such a vector can be computed by rotating an unit vector like \<0, 1\> by the angle+90 to get a vector that points "rightward".

Then you can project the runway centers onto this right-vector, which will result in a scalar that denotes how far along the right-vector they are, which is what you want to order by to get them in local left-to-right.

An alternative and mathematically equivalent method is to rotate the center points by -angle and project them onto the X axis, ordering them by their position there.

---
Tags: vector, mathematics
---


# Question
Title: If you are a solo programmer, how do you manage the graphics artistry part?
If you are a solo programmer creating a game, what do you do for the graphics and art part?

Should I work with graphics artist to draw the characters and the environment? I don't know how to draw any way.

# Answer
You basically have three options:

1. You can outsource it -- Tetrad's links in his comment provide a great starting point for outsourcing -- either in terms of hiring somebody to produce the art for you, or gathering it from art repositories that make their contents available for free and/or under a permissive license.
2. You can learn to produce it yourself. This could mean learning to model or draw yourself -- there's a lot of information out there on learning to use 3D modelling programs (for example if you use the freely-available Blender, you can check this out). It could also mean learning to draw -- this *is* a learnable skill to an extent. I took a drawing class in college (we used this book) and I was surprised how much I improved. It will take a lot of practice, of course.
3. You can design your game such that it requires very little in the way of "real art." Simple or primitive graphics, perhaps built procedurally, can look good in the right contexts.
> 14 votes

# Answer
Josh raises some good points, with Blender the latest version is 2.5x and it has a built in game engine, you can use for prototyping. If you use 3d models, it lets you import pictures as a background, and set the transparency. Using pictures, you can literally trace your 3D model.

* Just remember, when building a game, the more you can do yourself, the less dependent you are on others to get "their work" done.

There are considerable resources that are "open source", here is a link. It covers sprites, sounds, tiles, etc. Pick your search engine and type, "open source game art".

http://letsmakegames.org/resources/art-assets-for-game-developers/
> 2 votes

---
Tags: graphics, art, ios
---


# Question
Title: How do I calculate the exit vectors of colliding projectiles?
I'm trying to create projectiles which bounce/ricochet off one another when they collide in mid-air.

All projectiles are spherical and have identical size, mass, and speed. Each has two vectors: one representing its current location and the other its direction and speed. (Vectors, here, basically being `<x,y,z>` tuples.) The distance/direction between the two projectiles can easily be calculated as a fifth vector.

In my head, I envision the ricochet as reflecting each projectile's velocity off of a plane perpendicular to the line between the two projectiles, but Googling for "vector reflection" and the like just gets me pages full of math I don't know how to translate into code. :-)

How can I model this collision? I'm not worried about real-world factors like drag, friction, or gravity — simple reflection is enough.

```
static void ricochet(Projectile projectile1, Projectile projectile2) {
    Vector position1 = projectile1.position;
    Vector position2 = projectile2.position;

    Vector direction1 = projectile1.direction;
    Vector direction2 = projectile2.direction;

    Vector distance = new Vector(position1).subtract(position2);

    Vector reflection1 = new Vector();
    Vector reflection2 = new Vector();

    // MAGIC!

    projectile1.direction = reflection1;
    projectile2.direction = reflection2;
}

```

# Answer
Here's some code from Gamasutra which calculate the velocity vector of two colliding circles (edited to exclude mass):

```
// First, find the normalized vector n from the center of
// circle1 to the center of circle2
Vector n = circle1.center - circle2.center;
n.normalize();
// Find the length of the component of each of the movement
// vectors along n.
// a1 = v1 . n
// a2 = v2 . n
float a1 = v1.dot(n);
float a2 = v2.dot(n);

// Using the optimized version,
// optimizedP =  2(a1 - a2)
float optimizedP = (2.0 * (a1 - a2)) / 2;

// Calculate v1', the new movement vector of circle1
// v1' = v1 - optimizedP * n
Vector v1' = v1 - optimizedP *  n;

// Calculate v1', the new movement vector of circle1
// v2' = v2 + optimizedP * n
Vector v2' = v2 + optimizedP * n;

circle1.setMovementVector(v1');
circle2.setMovementVector(v2');

```

**Update:**

Here's a flash demo I created to illustrate the concept:
> 8 votes

# Answer
A little correction to lukevanin's answer, the balls can end up sticking to one another by colliding perpetually, this problem can be resolved by preventing collisions between balls moving away from one another, this phenomena happens to coincide with `optimizedP` being negative, so here is a simple fix:

```
private function collideMoving(pA:Point, vA:Point, pB:Point, vB:Point):void
{
    // excerpt from http://www.gamasutra.com/view/feature/3015/pool_hall_lessons_fast_accurate_.php?page=3

    // First, find the normalized vector n from the center of
    // circle1 to the center of circle2
    var normal:Point = pA.subtract(pB);
    normal.normalize(1);

    // Find the length of the component of each of the movement
    // vectors along n.
    // a1 = v1 . n
    // a2 = v2 . n
    var tA:Number = dotproduct(vA, normal);
    var tB:Number = dotproduct(vB, normal);

    // Using the optimized version,
    // optimizedP =  2(a1 - a2)
    //              -----------
    //                m1 + m2
    // Math.min added to prevent collisions between balls moving away
    // from one another, thus preventing "entanglement".
    var optimizedP:Number = Math.min((2.0 * (tA - tB)) / 2, 0);

    // Calculate v1', the new movement vector of circle1
    // v1' = v1 - optimizedP * m2 * n
    vA.x = vA.x - (optimizedP * normal.x);
    vA.y = vA.y - (optimizedP * normal.y);

    // Calculate v1', the new movement vector of circle1
    // v2' = v2 + optimizedP * m1 * n
    vB.x = vB.x + (optimizedP * normal.x);
    vB.y = vB.y + (optimizedP * normal.y);
}

```

http://wonderfl.net/c/qZbk
> 3 votes

# Answer
Reflection is unnecessarily complex, the problem is much simpler than that.

Consider two projectiles (A and B), where A is moving and B is stationery. At the point of collision all the force in A will be passed onto B, resulting in A coming to a complete stop, and B shooting off at the speed that A was travelling at when it hit. That's exactly how a newtons cradle works.

What actually happens is that A's velocity is added to B. We know that every action has an equal and opposite reaction, so the same velocity is subtracted from A. The result is A's velocity vector is transferred to B, and vice-versa.

Now consider if A and B are flying directly towards each other. At the point of collision we add A's velocity to B, and subtract the same value from A. We apply the same calculation to B since it is also moving. The code would look something like this:

```
Vector newVelocityA = velocityA.add(velocityB).subtract(velocityA);
Vector newVelocityB = velocityB.add(velocityA).subtract(velocityB);

```

This can be simplified by removing the unnecessary arithmetic:

```
Vector newVelocityA = velocityB;
Vector newVelocityB = velocityA;

```

As you can see it basically boils down to swapping the vectors of the two particles.

The reason why such a simple system works is that we're assuming perfect elastic collision and projectiles with identical masses. In a more complex system with different masses you would need to base the calculations on the force rather than the velocity, but is based on the same principles.

**Update:**

Here's an example in Flash which I put together to illustrate the concept.
> 0 votes

---
Tags: 3d, java, projectile-physics
---


title: Detecting a sequence of nodes in a grid

text:
# Question
Title: Detecting a sequence of nodes in a grid
Given the image below, I need to detect the most optimal sequence on the board (the green line). The blue/red lines represent possible, but not the best moves.

Here are the rules:

1. You can move to any tile that is the same, and is your neighbor (diagonal is valid)
2. Once you have visited a tile, you can't visit it again.

I have thought about looping through each node, and looking at its neighbors, then recursively going through. Once I find a possible move I can put it into a structure. Once all possible moves are found I just pick the move with the highest count of node. It becomes more difficult when a node has more than one neighbor that matches.

So, is there some algorithm that I can use? I was thinking some sort of flood fill, but that doesn't meet rules #2.

As requested, here is a video of similar gameplay. http://youtube.com/watch?v=eumnCTG0AE8

# Answer
You can consider each group of linked identical symbols (and by linked I mean you can travel from one symbol to another) a separate graph. For each such graph apply a Depth First Search (DFS) starting from each node in the graph *that isn't already part of the longest path for that graph*. Every time you reach a dead end while applying a DFS, check to see if the path you've just traversed is longer than the global maximum that you've found so far. If it is, store it as the new longest path.

You'll notice that in the previous paragraph I mentioned applying a DFS multiple times for each graph. A single DFS ran on a graph wouldn't be enough. Consider this particular case:

```
    1
1 1 1
    1
    1
    1
    1

```

If by chance you would first run a DFS on this graph in the topmost node, you would discover the longest possible path as being the vertical line, but that wouldn't be correct. This would happen every time you start the DFS algorithm in a node that's somewhere inside the resulting path or is not part of it at all. What you need to do in this particular example is also start a DFS algorithm from the left-most node in the second line. That will find the correct path. Generally speaking, you'll need to run DFS algorithms in each node that isn't currently part of the longest path for that graph, as stated above.

The absolute worse case scenario for this algorithm would be a board filled or mostly filled with a single symbol type, however that's unlikely to happen in the game. Also, be careful how you store the longest paths for each graph. If you don't optimize this bit, you might be better off just calling a DFS for each node on the stage. Assuming that you don't work with very large boards and that speed isn't that big of an issue, this solution should be fast enough.

Technically speaking, by breaking down your board into separate graphs you end up with multiple "Longest path problem"s. As we can see from your example, you can have cycles in your graph (for example, having all of the symbols on the outside of the stage of the same type), which means that in this particular problem you need to find the longest path in several cyclic undirected graphs, which can't be done in polynomial time.

If you find that this is too slow, see this answer on StackOverflow for more details on how to optimize the individual "Longest Path Problems".
> 6 votes

---
Tags: algorithm
---


# Question
Title: Why do I get this null pointer exception?
When I execute this code it gives me the Exception Glthread 8 Java.lang.null.pointer

```
MouseJointDef md = new MouseJointDef();
md.bodyA = _body;
md.bodyB = _body;
md.target.set(locationWorld);
md.collideConnected = true;
md.maxForce = 1000.0f * _body.getMass();

_mouseJoint =  (MouseJoint) _world.createJoint(md);
_body.setAwake(true);

```

Thanks.

# Answer
This is a case of "give a man a fish/teach a man to fish". You should learn to use the debugger to figure this problem out yourself.

Here is a good place to start:

http://www.infinitezest.com/articles/debugging-an-android-application.aspx

and you can find more here:

the google

FWIW as your code stands, the most likely perpetrator are `md.target`, `_body` and `_world`.
> 5 votes

---
Tags: android, java
---


# Question
Title: Help: -[GameScene spiderBelowScreen]: unrecognized selector sent to instance 0x257f50
I am currently doing the tutorials in the book: "learn iPhone and iPad cocos2d Game Development" by Steffen Itterheim and have been running into problems with the code for the DoodleDrop tutorial, chapter 4. I have tried to find the source of the problem but i am not able to do so.

Here is the code i am using:

```
#import "GameScene.h"

@implementation GameScene

-(void) spiderBelowScreen:(id)sender {
NSLog(@">>spiderBelowScreen<<");

// Make sure sender is actually of the right class
NSAssert([sender isKindOfClass:[CCSprite class]], @"sender is not a CCSprite!");
CCSprite* spider = (CCSprite*)sender;

// Move the spider back up outside the top of the screen
CGPoint pos = spider.position;
CGSize screenSize = [[CCDirector sharedDirector] winSize];
pos.y = screenSize.height + [spider texture].contentSize.height;
spider.position = pos;
}

-(void) runSpiderMoveSequence:(CCSprite*)spider {
NSLog(@">>runSpiderMoveSequence<<");

// Slowly increase the spider speed over time
numSpidersMoved++;

if (numSpidersMoved % 8 == 0 && spiderMoveDuration > 2.0f) {
    spiderMoveDuration -= 0.1f;
}

// This is the sequence which controls the spiders' movement
CGPoint belowScreenPosition = CGPointMake(spider.position.x, [spider texture].contentSize.height);
CCMoveTo *move = [CCMoveTo actionWithDuration:spiderMoveDuration position:belowScreenPosition];
CCCallFuncN *call = [CCCallFuncN actionWithTarget:self selector:@selector(spiderBelowScreen)];
CCSequence *sequence = [CCSequence actions:move, call, nil];
[spider runAction:sequence];
}

-(void) spidersUpdate:(ccTime)delta {
NSLog(@">>spidersUpdate<<");

// Try to find a spioder which isn't currently moving
for (int i = 0; i < 10; i++) {
    int randomSpiderIndex = CCRANDOM_0_1() * [spiders count];
    CCSprite *spider = [spiders objectAtIndex:randomSpiderIndex];

    // If the spider isn't moving it won't have any running actions
    if ([spider numberOfRunningActions] == 0) {
        // This is the squense wich controls the spiders' movement
        [self runSpiderMoveSequence:spider];

        // Only onbe spider should start moving at a time
        break;
    }
}
}

-(void) resetSpiders {
NSLog(@">>resetSpiders<<");

CGSize screenSize = [[CCDirector sharedDirector] winSize];

// Get any spider to get its image width
CCSprite *tempSpider = [spiders lastObject];
CGSize size = [tempSpider texture].contentSize;

int numSpiders = [spiders count];

for (int i = 0; i < numSpiders; i++) {

    // Put each spider at its designated position outside the screen
    CCSprite *spider = [spiders objectAtIndex:i];
    spider.position = CGPointMake(size.width * i + size.width * 0.5f, screenSize.height + size.height);
    [spider stopAllActions];
}

// Uschedule the selector just in case. If it isn't scheduled it wont do anything
[self unschedule:@selector(spidersUpdate:)];

// Schedule the spider update logic to run at the given interval
[self schedule:@selector(spidersUpdate:) interval:0.7f];
}

-(void) initSpiders {
NSLog(@">>initSpiders<<");

CGSize screenSize = [[CCDirector sharedDirector] winSize];

// using a temporary spider sprite is the easiest way to get the image's size
CCSprite *tempSpider = [CCSprite spriteWithFile:@"spider.png"];
float imageWidth = [tempSpider texture].contentSize.width;

// Use as many spiders as can fit next to each other over the whole screen width
int numSpiders = screenSize.width / imageWidth;

// Initialize the spider array using alloc
spiders = [[CCArray alloc] initWithCapacity:numSpiders];

for (int i = 0; i < numSpiders; i++) {
    CCSprite *spider = [CCSprite spriteWithFile:@"spider.png"];
    [self addChild:spider z:0 tag:2];

    // Also add the spider to the spider array
    [spiders addObject:spider];
}
// call the method to reposition all spiders
[self resetSpiders];

}

-(void) update:(ccTime)delta {
NSLog(@">>update:(ccTime)delta<<");

// Keep adding up the playerVelocity to the players's position
CGPoint pos = player.position;
pos.x   += playerVelocity.x;

// The player should also be stopped from going outside the screen
CGSize  screenSize  = [[CCDirector sharedDirector] winSize];
float   imageWidthHalved    = [player texture].contentSize.width * 0.5f;
float   leftBorderLimit     = imageWidthHalved;
float   rightBorderLimit    = screenSize.width - imageWidthHalved;

// Preventing the player sprite from moving outside the screen
if (pos.x < leftBorderLimit)
{
    pos.x   = leftBorderLimit;
    playerVelocity  = CGPointZero;
}
else if (pos.x > rightBorderLimit)
{
    pos.x   = rightBorderLimit;
    playerVelocity  = CGPointZero;
}

player.position = pos;

}

-(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
NSLog(@">>accelerometer<<");

// controls how quickly velocity decelerates (lower = quicker to change direction)
float   deceleration    = 0.2f;

// determines how sensitive the accelerometer reacts (higher = more sensitivity)
float   sensitivity     = 6.0f;

// how fast the velocity can be at most
float   maxVelocity     = 550;

// adjust velocity based on current accelerometer acceleration
playerVelocity.x    = playerVelocity.x * deceleration + acceleration.x * sensitivity;

// we must limit the maximum velocity of the player sprite, in both directions
if (playerVelocity.x > maxVelocity)
{
    playerVelocity.x    = maxVelocity;
}
else if (playerVelocity.x < -maxVelocity)
{
    playerVelocity.x    = -maxVelocity;
}
}

+(id)scene {
NSLog(@">>scene<<");
CCScene *scene = [CCScene node];
CCLayer *layer = [GameScene node];
[scene addChild:layer];
return scene;
}

-(id)init {
NSLog(@">>init<<");
if ((self = [super init])) {
    CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);

    self.isAccelerometerEnabled = YES;

    player = [CCSprite spriteWithFile:@"alien.png"];
    [self addChild:player z:0 tag:1];

    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    float imageHeight = [player texture].contentSize.height;
    player.position = CGPointMake(screenSize.width / 2, imageHeight / 2);

    // scheduling the update method in order to adjust the player's speed every frame
    [self scheduleUpdate];
    [self initSpiders];

}
return self;
}

-(void) deallaoc {
NSLog(@">>dealloc<<");
CCLOG(@"%@: %@", NSStringFromSelector(_cmd), self);

// The spiders array must be released, it was created using [CCArray alloc]
[spiders release];
spiders = nil;

// Never forget to call [super dealloc]
[super dealloc];
}

@end

```

The result i get (edited), including the NSLog i have included, is:

```
2011-08-13 15:18:38.401 DoodleDrop[1751:707] >>update:(ccTime)delta<<
2011-08-13 15:18:38.404 DoodleDrop[1751:707] -[GameScene spiderBelowScreen]: unrecognized selector sent to instance 0x257f50
2011-08-13 15:18:38.407 DoodleDrop[1751:707] >>accelerometer<<
2011-08-13 15:18:38.417 DoodleDrop[1751:707] >>update:(ccTime)delta<<
2011-08-13 15:18:38.419 DoodleDrop[1751:707] -[GameScene spiderBelowScreen]: unrecognized selector sent to instance 0x257f50

```

I wonder if there is someone nice that can help me here?

# Answer
> 4 votes
I think you need to use `@selector(spiderBelowScreen:)`. Note the `:`.

---
Tags: iphone, cocos2d-iphone, objective-c
---


title: How does one buy the rights for a game?

text:
# Question
Title: How does one buy the rights for a game?
Let's take some old popular at a time but abandoned game: WorldRacing/HiOctane/Constructor/any other. Say I with a team want to revitalize said game and bring it to year 2011 without major changes and then work on improving it (e.g. add multiplayer). Also it is important to keep the game's spirit, assets, story, music, so basically the game remains the same, but gets better (e.g. adapting DOS game to Win7).

My questions are from "How is it usually made?" area:

* How do I purchase rights to the title and the game's assets (graphics, sounds, music, storyline). Whom to contact and what purchase options are possible? Is it possible to obtain source codes, design documents.
* How to deal with various platforms, is it terms of contract saying which platforms are allowed to be used if there are several?
* How to deal with localizations in other languages, are they to obtain from other companies or do they belong to master publisher?
* What could be the reasonable price for said games in example?
* Is it possible to pursue owners to release the game as open source?

Remember Heroes of Might and Magic was owned by New World Computing, but later changed its owner to Nival. I'm interested in that sort of process.

# Answer
> 26 votes
Byte published a high-level summary of the "abandonware" situation in 2001, which answers many of these questions. However, it's dealing with the case where you simply want the company to re-release the software or release it into the public domain. If you intend to license it and resell it, you will definitely need a lawyer to draft up a contract to protect *your* commercial rights, at some point in the process.

> How To Do It
>
> You don't need to be an attorney or work at a software publisher to bring new life to old software anyone can help make it happen. The hardest part is often finding the right person to ask. If the company that published the software has been sold, you'll have to find out who bought it: A little Web research goes a long way here.
>
> Once you find the company, it's time to approach their attorneys. Call the company's main office and ask for the legal department, or write to the company. The person you talk to may not have heard of the software you're referring to, so be ready to provide as many details as possible, including who published it, in what year, and for what platforms.
>
> Also, know what you want: Asking for a license to distribute the software for free on your web site may be reasonable to many publishers. Or perhaps you'd like the publisher to release the software into the public domain an option that will be distasteful to many publishers who are unwilling to completely give up rights to their work, no matter how old. Don't expect an answer right away even once you find a helpful individual, it may take months for them to give you an answer.

To answer your specific queries:

> Whom to contact and what purchase options are possible?

You contact whoever owns the copyrights. This can actually be very tricky to track down in the case of some old games, and unfortunately, there is no general way to handle it. In some cases the paper trail may just be buried too deep, and you're SOL. For example, as described in the Byte article, the legal records needed to transfer the rights to MECC's game catalog are apparently gone forever.

> Is it possible to obtain source codes, design documents. How to deal with localizations in other languages, are they to obtain from other companies or do they belong to master publisher?

They're assets like any other. These may have been owned by a different party to begin with; they may have been sold to a different party during liquidation; they may be lost forever.

Some things, like trademarks, may now be owned by entirely unrelated entities. If they're actually using them for their unrelated business, you probably can't get them at all.

> How to deal with various platforms, is it terms of contract saying which platforms are allowed to be used if there are several? What could be the reasonable price for said games in example?

This depends entirely on your negotiating skill. You want to convince the current holders it's worth $0 to them, and that even $1 would be a great move on their part to let you remake the game on all platforms.

> Is it possible to pursue owners to release the game as open-source?

Sure. Open source licensing is licensing like any other. If you have the rights, you can do what you want.

# Answer
> 3 votes
You've asked a lot of questions here - let me cherry pick one of them.

> How to deal with localizations in other languages, are they to obtain from other companies or do they belong to master publisher?

Localization is also one of those areas where it could be managed on a case-by-case basis.

Most companies I have worked with treat any localization work provided by the republisher (the localizing local publisher) as a slightly limited work for hire, meaning, the republisher probably has exclusive rights for the localized version while the republishing agreement is in effect. That said, if you acquire the rights to a product, you need to do proper due diligence and have your expectations incorporated into the agreement.

---
Tags: game-industry, copyright, licensing
---


# Question
Title: How can I store information about what cells are connected to others in a 2D array?
I have a 10x11 array in my game. What is the best structure and way to store the connections between the elements of the array?

Some info about the connections:

* they are simple (2 elements are connected or not)
* an element can be connected with its 8 neighbours
* when I move from one position to another I need to add that connection
* when I'm in a position I need to check that element's connections

For example: "the player" is at \[6,1\]

1. I need to check for all 8 directions if there is a connection there or not(this function returns a byte or int\[8\], doesn't matter)
2. If the player wants to move to \[6,2\] I dont allow it
3. If the player wants to move to \[6,1\] I allow it and store the new connection

# Answer
> 8 votes
bummzack's answer is good if you need to store an arbitrary graph. Since you are storing a graph that is also a 2D grid, there is an even better way.

Associate eight bits with each index; each bit indicates whether a connection is available in one of the eight possible directions. If the connection costs are not uniform, you can instead store eight bytes (or eight ints, or eight floats). This will use significantly less memory than a full adjacency matrix, and scales linearly rather than quadratically with the number of nodes.

# Answer
> 3 votes
Since the amount of nodes is known, an efficient way to store connections would be an adjacency matrix.

It's basically a two-dimensional array of booleans (or ints/floats if you want to store edge-costs) that has a row and a column for each node. So if you want to get/set the edge from node `3` to node `6`, you would look up the entry in row `3` and column `6`. If the value there is `true` (or not zero), then there's an edge from `3` to `6`.

Since you have 110 nodes, your adjacency matrix will be a 110x110 array.

This way of storing the graph is suitable for a dense graph (eg. you have lots of connections) and it's *very* fast to get and set edges (connections).

# Answer
> -1 votes
I would create a simple `node` class, with eight `node` properties, one for each direction. (N, NE, S, etc.) Any connection that does not exist has a null `node` element in that direction's property. Store these in your array, and use them like sort of like a linked list. It's simple and understandable. Each node could have a `value` property, which points to what you had originally stored in the array, or you could simply add the eight navigation properties to your existing data.

---
Tags: c#, data-structure
---


# Question
Title: Momentum and order of update problems in my physics engine
This question is a "follow-up" question from my previous one, regarding collision detection and resolution, which you can find here.

---

If you don't want to read the previous question, here's a brief description on how my physics engine works:

> Every physical entity is stored in a class called SSSPBody.
>
> Only AABBs are supported.
>
> Every SSSPBody is stored in a class called SSSPWorld, which updates every body and handles gravity.
>
> Every frame, SSSPWorld updates every body.
>
> Every updated body looks for nearby bodies in a spatial hash, checks if they need to detect collisions with them. If yes, they invoke a "collision" event and check if they need to resolve collisions with them. If yes, they calculate the penetration vector and directional overlap, then change their position in order to resolve the penetration.
>
> When a body collides with another, it transfers its velocity to the other one by simply setting the body's velocity to its own.
>
> A body is velocity is set to 0 when it hasn't changed position from the last frame. If it also collides with a moving body (such as a lift or a moving platforms) it calculates the movement difference of the lift to see if the body hasn't moved from its last position.
>
> Also, a body invokes a "crushed" event when all its AABB corners overlapped something in a frame.

This is the FULL source code of my game. It's divided in three projects. SFMLStart is a simple library handling input, drawing and updating of entities. SFMLStartPhysics is the most important one, where the SSSPBody and SSSPWorld classes are. PlatformerPhysicsTest is the game project, containing all the game logic.

And this is the "update" method in the SSSPBody class, commented and simplified. You can take a look only at this if you don't feel like looking at the whole SFMLStartSimplePhysics project. (And even if you do, you should still take a look at this since it's commented.)

---

The .gif shows two problems.

1. If bodies are placed in a different order, different results happen. The crates on the left are identical to the crates on the right, only placed in the inverse order (in the editor).
2. Both crates should be propelled towards the top of the screen. In the situation on the left, no crates are propelled. On the right, only one of them is. Both situations are unintended.

---

## First problem: order of update

This is fairly simple to understand. In the situation on the left, the topmost crate is updated before the other one. Even if the crate on the bottom "transfers" velocity to the other one, it needs to wait the next frame to move. Since it didn't move, the bottom crate's velocity is set to 0.

I don't have any idea how to fix this. I'd prefer the solution to not be dependent on "sorting" the update list, because I feel I'm doing something wrong in the whole physics engine design.

How do the major physics engines (Box2D, Bullet, Chipmunk) handle the update order?

---

## Second problem: only one crate is propelled towards the ceiling

I yet don't understand why this happens. What the "spring" entity does is set the body's velocity to -4000 and re-position it on top of the spring itself. Even if I disable the re-positioning code, the problem still occurs.

My idea is that when the bottom crate collides with the top crate, its velocity is set to 0. I'm not sure why this happens.

---

Despite the chance of looking like someone who gives up at the first problem, I posted the whole project source code above. I don't have anything to prove it, but believe me, I tried hard to fix this but I just couldn't find a solution and I don't have any previous experience with physics and collisions. I've been trying to solve these two problems for more than a week and now I'm desperate.

I don't think I can find a solution on my own without stripping many features out of the game (velocity transfer and springs, for example).

Thanks a lot for the time spent reading this question, and thanks even more if you even try coming up with a solution or a suggestion.

# Answer
Actually, order of update problems are quite common for normal impulse physics engines, you can't just delay applying the force as Vigil suggests, you'd end up breaking energy preservation when an object simultaneously collides with 2 other. Usually they do though manage to make something that seems pretty real, even though a different order of update would have made a significantly different outcome.

In any case, for your purpose there is enough hiccups in an impulse system that I'd suggest you instead build a mass-spring model.

The basic idea is that instead of trying to resolve a collision in one step you apply a force to the objects colliding, this force should be equivalent to the amount of overlap between the objects, this is comparable to how real objects during a collision transform their movement energy into deformation and then back into movement, the great thing about this system is that it allows force to travel through an object without that object having to bounce back and forth, and it can reasonably be done completely order of update independent.

In order for objects to come to a halt rather than bounce around indefinitely you will have to apply some form of dampening, you can greatly affect the style and feel of your game depending on how you do it, but a very basic approach would be to apply a force to two touching objects equivalent to their internal movement, you may choose to apply it only when they are moving towards one another, or also when they move away from one another, the latter can be used to completely prevent objects from bouncing back when they hit the ground, but will also make them a little sticky.

You can also make a friction effect by braking an object in the perpendicular direction of a collision, the amount of braking should be equivalent to the amount of overlap.

You could get around the concept of mass pretty easily by making all objects have the same mass, and immovable objects will work like having infinite mass if you simply neglect accelerating them.

Some pseudo-code, just in case the above wasn't clear enough:

```
//Presuming that you have done collision checks between two objects and now have
//numbers for how much they overlap in each direction.
overlapX
overlapY
if(overlapX<overlapY){ //Do collision in direction X
    if(obj1.X>obj2.X){
        swap(obj1,obj2)
    }
    //Spring effect:
    obj1.addXvelocity-=overlapX*0.1 //Constant, the lower this is set the softer the
                                    //collision will be.
    obj2.addXvelocity+=overlapX*0.1
    //Dampener effect:
    velocityDifference=obj2.Xvelocity-obj1.Xvelocity
    //velocityDifference=min(velocityDifference,0) //Uncomment to only dampen when
                                                   //objects move towards each other.
    obj1.addXvelocity+=velocityDifference*0.1 //Constant, higher for more dampening.
    obj2.addXvelocity-=velocityDifference*0.1
    //Friction effect:
    if(obj1.Yvelocity>obj2.Yvelocity){
        swap(obj1,obj2)
    }
    friction=overlapX*0.01
    if(2*friction>obj2.Yvelocity-obj1.Yvelocity){
        obj1.addYvelocity+=(obj2.Yvelocity-obj1.Yvelocity)/2
        obj2.addYvelocity-=(obj2.Yvelocity-obj1.Yvelocity)/2
    }
    else{
        obj1.addYvelocity+=friction
        obj2.addYvelocity-=friction
    }
}
else{ //Do collision in direction Y

}

```

The point of the addXvelocity and addYvelocity properties is that these are added to their object's velocity after all collision handling is done.

**Edit:**
You could do stuff in the following order, where each bullet must be performed on all elements before the next is performed:

* Detect collisions, they may be resolved as soon as they are detected.
* Add the addVelocity values to the velocity values, add gravity Yvelocity, reset the addVelocity values to 0, move objects according to their velocity.
* Render the scene.

Also, I realize that the following might not be completely clear in my initial post, under the influence of gravity objects will overlap when resting on top of one another, this suggests that their collision box should be slightly higher than their graphical representation to avoid overlapping visually. This problem will be lesser if the physics is run at a higher update rate. I suggest you try running at 120Hz for a reasonable compromise between CPU time and physics accuracy.

**Edit2:**
Very basic physics engine flow:

* Collisions and gravity produce force/acceleration. `acceleration = [Complicated formulas]`
* Force/acceleration are added to velocity. `velocity += acceleration`
* Velocity is added to position. `position += velocity`
> 12 votes

# Answer
Well, you're obviously not a someone who gives up easily, you're a real man of iron, I would have thrown my hands in the air much earlier, since this project bears a strong resemblance to a kelp forest :)

First of all, positions and velocities are set all over the place, from a viewpoint of physics subsystem it's a recipe for a disaster. Also, when changing integral things by various subsystems, create a private methods like "ChangeVelocityByPhysicsEngine", "ChangeVelocityBySpring", "LimitVelocity", "TransferVelocity" or something like that. It will add an ability of checking changes made by a specific part of logic and provide an additional meaning to these velocity changes. That way debugging would be easier.

**First problem.**

Onto the question itself. Now you're just applying position and velocities fixes "as they go" in order of appearance and game logic. That won't work for complex interactions without carefully hard-coding the physics of each complex thing. A separate physics engine is not needed then.

In order to do complex interactions without hacks, you need to add an additional step between detecting collisions based on positions which were changed by initial velocities and final changes of positions based on "after-velocity". I imagine it would go like this:

* integrate velocity using the all the forces acting on bodies *(you're applying velocity fixes directly now, leave velocity calculations to your physics engine and use forces to move things instead)*, then use the new velocity to integrate positions.
* detect collisions, then restore velocity and positions,
* then process collisions (using impulses without immediate position update, ofc, only velocity is changed until the final step)
* integrate new velocity again and process all collisions using impulses again, except now collisions are inelastic.
* make final integration of positions using resulting velocity.

Additional things may pop up, like dealing with jerking, refusal to stack up when FPS is small, or other things like that, be prepared :)

**Second problem**

Vertical velocity of both those "deadweight" crates never changes from zero. Strangely, in PhysSpring's Update loop you assign velocity, but in PhysCrate's Update loop it's already zero. It's possible to find a line where velocity goes wrong, but I stopped debugging here since it's "Reap What You Sew" situation. It's time to stop coding and start rethinking everything when debugging becomes hard. But if it comes to a point where it's impossible even for code's author to understand what's going on in the code, then your code base is already dead without you realizing it :)

**Third problem**

I think that something is off when you need to recreate a portion of Farseer to do a simple tile-based platformer. Personally, I would think of your current engine as of tremendous experience, and then ditch it completely for more simple and straightforward tile-based physics. While doing so, it would be wise to pick up on things like Debug.Assert and maybe even, oh the horror, unit tests, since it would be possible to catch unexpected things earlier.
> 14 votes

# Answer
> When a body collides with another, it transfers its velocity to the other one by simply setting the body's velocity to its own.

Your problem is that these are fundamentally wrong assumptions about motion, so what you're getting doesn't resemble motion as you're familiar with it.

When a body collides with another, momentum is conserved. To think of this as "A hits B" versus "B hits A" is to apply a transitive verb to an intransitive situation. A and B collide; the resulting momentum must be equal to the initial momentum. That is, if A and B are equal mass, they are now both traveling with the mean of their original velocities.

You will also likely need some collision slop and an iterative solver, or you'll run into stability issues. You should probably read through some of Erin Catto's GDC presentations.
> 7 votes

# Answer
I think you have made a really noble effort, but it seems there are fundamental problems with how the code is structured. As other have suggested, it may help to separate the operations into discreet parts, eg:

1. **Broad phase**: Loop through all the objects - do a quick test (eg, AABB) to determine which objects may be colliding - discard those that aren't.
2. **Narrow phase**: Loop through all the colliding objects - calculate a penetration vector for the collision (eg, using SAT).
3. **Collision response**: Loop through the list of collision vectors - calculate a force vector based on the mass, then use this to calculate an acceleration vector.
4. **Integration**: Loop through all the acceleration vectors and integrate position (and rotation if needed).
5. **Rendering**: Loop through all the calculated positions and render each object.

By separating the phases all objects are updated progressively in sync and you won't have the order dependencies you are currently struggling with. The code also generally turns out to be simpler and easier to change. Each of these phases is fairly generic, and it's often possible to substitute better algorithms after you have a working system.

That said, each of these parts is a science in itself, and can occupy a great deal of time trying to find the optimal solution. It may be better to start with some of the most commonly used algorithms:

* **Broad phase collision detection**: Spatial hashing.
* **Narrow phase collision detection**: For simple tile physics, you can just apply Axis Aligned Bounding Box (AABB) intersection tests. For more complicated shapes you can use Separating Axis Theorem. Whatever algorithm you use, it should return the direction and depth of an intersection between two objects (called the penetration vector).
* **Collision response**: Use Projection to resolve inter-penetration.
* **Integration**: The integrator is the largest determinant of the engine's stability and speed. Two popular options are Verlet (fast but simple) or RK4 (accurate but slow) integration. Using verlet integration can lead to an extremely simple design as most physical behaviours (bounce, rotation) just work without too much effort. One of the best references I have seen for learning RK4 integration is Glen Fiedler's series on physics for games.

A good (and obvious) place to start is with Newton's laws of motion.
> 4 votes

---
Tags: c#, collision-detection, physics, .net, aabb
---


# Question
Title: How can I make my units follow predetermined paths?
I'm planning my first game and am planning on using the engine set out in Beginning Android Games, as it deals with a load of stuff that is just noise at the moment to me (because I've no real world experience yet). There's no real time restraint - this is a learning experience more than a real world project, although I would love to be able to release something at the end of this project.

The way the book tells me how to do movement has been very much acceleration and velocity based with other forces thrown in (wind, gravity etc) but it's not covered how I can set a predetermined path for an enemy to follow. I was thinking that I could use a lookup table to map points for the enemy to head for, and then I'd just need a way of smoothing out the turning so that the motion is fluid. Is this the correct approach?

I know this is a bit of a vague question, and I would give you some code, but I'm very much in the planning phase at the moment, so I'm just looking for some pointers or things to think about whilst I'm trying to work out how it's all going to hang together.

# Answer
Here are some resources to get you started:

You can find more on Wikipedia, which has some good articles on specific algorithms, and of course Google. Once you start investigating a little more, feel free to post more questions specific to your implementation.
> 2 votes

# Answer
This tutorial at XNA Resources shows one approach.

Basically, you store your waypoints as a queue of coordinates, then move the entity toward the first point in the list. Once you reach that point, remove it from the queue and continue to the next point. Depending on your game, you might want to set some limits on how quickly the entity can change speed/angle so the corners aren't so sharp.
> 2 votes

# Answer
You could use a steering algorythm, giving the entity a (set of) goals/waypoints and let the entity manage itself, considering its position/velocity/acceleration and its goal.

* The avantage is that is easy to go from a static waypoint to a mobile target :)
* The inconvenient is that its not really a pathfinding, and more a local search : the entity react to obstacle, but does not search the map (to avoid ntering a cul-de-sac for exemple). You may have to add some waypoints using some higher level reasonning (ie high level pathfinding to get the waypoints, and low-level steering to go from one waypoint to another one)

There are some good algo and exemples here, with differents method.
> 1 votes

# Answer
I'd suggest creating a list of cubic Bézier curves for each unit to follow. This will give you nice smooth paths.

To join multiple curves into a single curve smoothly, every control point at which two curves join must be on the line between the two control points on either side.

They only difficulty with them is that maintaining a consistent speed of travel requires a bit of extra work. One way to achieve that is to do a binary search each frame to find the new value of the curve parameter required to travel a specified distance.
> 0 votes

---
Tags: path-finding
---


# Question
Title: Wise approach to becoming good at C# XNA
Would finishing an entire course about C# at HomeAndLearn.co.uk and then jumping into XNA be a wise path to take?

Ultimate goal is to create a multiplayer 2D game.

# Answer
> 8 votes
Since I have never taken those courses, I can't speak for that site. However, I can tell you that no amount of classes or lessons will compare to experience. The best way to learn is to jump in and do stuff.

C# is a pretty easy language to pick up. There are plenty of sites that offer tutorials free. Also, XNA is just a library that sits on C#. There really isn't any reason why you can't learn C# by making simple games.

Start by making something simple. Maybe a static sprite that moves across the screen when you press certain buttons. Add some objects to play with collision. Then when you feel comfortable with that work on sprite animations, and a simple camera. It really isn't hard.

If you want a jump start, look at something like Flat Red Ball. It is simple 2.5D game engine that might help. If you want to make your own, look at this tile engine series. It will show you stuff like how to make a camera, animations, collision, and the rest. There is also this 2d tutorial series. I don't have a nice playlist for it so you will have to search youtube for the different parts. For even more resources, check out the ever-growing list of samples on the App Hub site.

If you really want to take classes, I can vouch for http://LearnVisualStudio.net. I know a few people who have taken them, and have seen the content. It is presented nicely and easy to follow.

When in doubt, come back here and ask questions. The people here are very responsive and helpful. If you need help on general C#/programming concepts try http://stackoverflow.com. It is another wonderful resource.

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


title: Dynamic bodies with Parallax Scrolling

text:
# Question
Title: Dynamic bodies with Parallax Scrolling
I have an object that has a dynamic body. Currently, I'm setting it's position to follow the sprite when the parallax layer move. After a certain event, the object suppose to fall to the ground. That's when I set it to Awake. But as the object falls and the parallax is moving, how do I control these factor?

When the object falls by right the sprite should be updated to follow the dynamic body position. Let's say I have a character, to avoid the falling object, I move the parallax layer. The sprite is attached to the parallax layer. I'm asking what should I do in this case. Any advice?

# Answer
The object should be offset along with the parallax in addition to its movement within the layer.

When doing parallax rendering, the layers themself aren't actually moving, its just the viewport that changes. Anything on the same depth as a parallax layer should be moving along with it, and if it is moving, you should simply add that on top.
> 1 votes

---
Tags: iphone, physics, box2d, cocos2d, parallax-scrolling
---


# Question
Title: How does one do alpha transparency testing in XNA 4.0?
I've read a lot of tutorials, but it just doesn't seem to work. Here's the code as suggested by a tutorial, using the built-in AlphaTestEffect class:

```
Matrix projection = Matrix.CreateOrthographicOffCenter(0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 0, 1);
Matrix halfPixelOffset = Matrix.CreateTranslation(-0.5f, -0.5f, 0);
alphaTest = new AlphaTestEffect(GraphicsDevice);
alphaTest.VertexColorEnabled = true;
alphaTest.DiffuseColor = Color.White.ToVector3();
alphaTest.AlphaFunction = CompareFunction.Greater;
alphaTest.ReferenceAlpha = 128;
alphaTest.World = Matrix.Identity;
alphaTest.View = Matrix.Identity;
alphaTest.Projection = halfPixelOffset * projection;

```

Then this object is just passed in to the SpriteBatch.Begin method. The result: Nothing appears on the screen, whereas the exact same code that doesn't pass in the alphaTest object renders correctly.

Note that this is the case even with CompareFunction.Always! (I tried CompareFunction.Never too in case I misunderstand the comparison order).

I am following this tutorial, but I've also seen that same code elsewhere. The tutorial has a downloadable file for XNA 4.0 to demonstrate it. I downloaded and tried it, and - *It doesn't work*. No craters show up. So what the heck is going on?

# Answer
> 1 votes
I followed your link and checked out the tutorial, your code seemed a little strange after looking at crater's texture which had alpha pixels as mask, so I downloaded tutorial's source. It's working fine for me, and there are differences from your code in these lines:

```
  alphaTestEffect.AlphaFunction = CompareFunction.Equal;
  alphaTestEffect.ReferenceAlpha = 0;

```

These code lines mean pixels whose alpha is equal to zero will be kicked out. In the context of this tutorial it means only actual transparent crater with it's half-transparent edges will be drawn to the stencil buffer setting it to 1, and solid white background will be discarded.

---
Tags: xna-4.0, transparency
---


# Question
Title: Flash saves in Windows, not in Linux, FileReference.save()
The code below compiles fine on the Flex 4 SDK on Fedora 15. Mouse-click opens the dialog box, I click okay, and a file is saved, **but the file is empty**. I run the same SWF file (that was compiled on the Linux machine) on a Windows machine, and the created file contains the expected data.

Then I broke the FileReference declaration out of the function into the class level, hoping to avoid a known bug and to keep a reference to the file alive outside the function. However, the same problem persists.

Hoping to set up a workaround, I added the debug Flash player to my path and ran the file from Flash without the benefit of the browser, and it **works**. So now a Flex problem has become a Firefox problem, maybe owing to a shady procedure I used to install the plugin without really understanding what was happening. I am running Firefox 5.0.

In essence my workflow is fixed, but perhaps people who performed the above will not be able to use projects with FileReference.save()? Should I be worried about this edge case?

```
/*
WriteTheFile.as
Original code by Brian Hodge
Test to see if ActionScript/Flash can write files
*/
package{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.utils.ByteArray;
    import flash.net.FileReference;

    public class WriteTheFile extends Sprite
    {
        private var _xml:String;
        private var fr:FileReference;

        public function WriteTheFile():void
        {
            if (stage) init();
            else addEventListener(Event.ADDED_TO_STAGE, init);
        }

        private function init(e:Event = null):void
        {
            removeEventListener(Event.ADDED_TO_STAGE, init);
            //Calling the save method requires user interaction and Flash Player 10
            stage.addEventListener(MouseEvent.MOUSE_DOWN, _onMouseDown);
        }
        private function _onMouseDown(e:MouseEvent):void
        {
            fr = new FileReference()
            fr.save("<xml><test>data</test></xml>", "filename.txt");
        }
    }
}

```

EDIT: addressed answer in code above, but the same problem exists.

EDIT: This works on the same system when the standalone player is invoked. Therefore this is a browser (FF 5.0) plugin problem.

# Answer
The problem is due to the garbage collector disposing the `FileReference` object before it has completed writing to the file.

As for why it works on Linux and not Windows could be attributed to a different memory management strategy in the Linux version of the player compared to the Windows version.

The solution is to keep a reference to the `FileReference`, eg:

```
public class WriteTheFile extends Sprite
{
    private var _xml:String;
    private var fr:FileReference = new FileReference();

    private function _onMouseDown(e:MouseEvent):void
    {
        fr.save("<xml><test>data</test></xml>", "filename.txt");
    }
}

```
> 2 votes

---
Tags: actionscript-3, file
---


# Question
Title: How should I move 2D objects in OpenGL ES 2?
I am a bit confused about what I need to move a basic square. Should I use a translation matrix or just change the object vertices? Which one is better?

I use a simple vertex shader, `gl_Position = myPMVMatrix * a_vertex`, along with a VBO.

# Answer
> 7 votes
The best approach is to change the value of your matrix. It is a parameter that is sent to the shader once per object and costs very little to update; changing all your vertices would mean updating the VBO with a very high bandwith cost.

---
Tags: opengl, rendering, opengl-es2
---


# Question
Title: 2D Platformer Collision/Physics Problems
I'm making a 2D platformer similar to Terraria, although I'm having some problems with some collision detection code. I'm using the code from the AppHub Platformer sample, but tweaked so it fits with my character size and tilesize. Although, I am having a few problems:

If I box myself in, and then jump. Instead of just canceling the jump it will move me through a wall (most likely to the right) and then when it can jump, it performs the jump.

Next problem I'm having is if I have a 1x1 gap above the character, I am freely able to jump through it. The character size is 2 blocks wide by 3 high.

I don't want to use a physics engine because I will not be using 95% of the features, and I don't really want to add it if i'm not going to use most of it. I just require a basic collision detection and basic physics. Honestly, I can't see anything wrong with my code and it's pretty much the same as the sample. Just by changing the tile size must have added these bugs and I'm not exactly sure how to fix it. This is my existing code.

**Basically, what I'm asking is:** How could I modify my current system to eliminate these bugs, or what new system could I implement to have a better, fully functional physics system without these bugs. (Without implementing a whole engine).

# Answer
Well, there is no solution to debug, so let's play a guessing game :)

* First problem seems to be caused by resolving jump collision on the X axis alone thanks to absDepthX always being bigger in `if
(absDepthY < absDepthX ...)` condition.
* Second problem seems to be caused by either bad intersection detection or velocity which is bigger than single block dimension, then collision logic would fail to detect any collisions.
* Not really a big problem, just a strange thing: it looks like velocity is scaled by frame delta time twice.

I would fix those problems by creating a strong mental image of how I want my collision system to work, imagining its progression by time, drawing several images of main hero colliding with walls and ceiling to keep weird cases in mind, and then writing code from scratch while using other developer's code sample only for insight on some concrete feature implementation details or general inspiration. Well, it's possible to tweak code of others, but then it is a must to understand the said code even better than its original author, or esoteric behavior will emerge sooner or later.
> 3 votes

# Answer
What I usually do in my code is quite simple:

First of all, you must calculate how much your character has penetrated inside the other object, in each axis.

```
int penX = (character.Left < object.Right)
  ? character.Left - object.Right
  : character.Right - object.Left;

```

Then, one at a time, substract this distance, which will be smaller than the character's delta, from the character position and check if the collision is no more. If the collision still exists, undo the substraction and test the next axis (or both at the same time). If, on the other hand, the collision is no more, your character is now collision free, right beside/above/below the object it collided with.

Since it is a one step system, there is no way you'll end appearing above the object you collided with. That is, unless the character is completely inside a wall or something like that. In this case, adding a couple more calculations to take movement delta into account (knowing where you are coming from) would fix the problem.

Note: it only works when calculating collisions of one moving object against a static one. For collisions of two moving objects it requires a precedence system or some tweaks (e.g. distinguishing dynamic from kinematic objects, as Unity does). Otherwise, strange things happen.

P.S.: I'm sorry I am not adding the code. It's in an old project in my SVN, and finding it would take quite some time.
> 0 votes

# Answer
A simple solution is:

1. Calculate the new position for the character (based on velocity, or button presses, or platforms, etc), but don't move them just yet.
2. Check for collisions with the character at the new position.
3. If there are no collisions at the new position, then move the character, otherwise, keep the character where they are.

Apply these steps separately to the X and Y axis so that the character can slide along the unconstrained axis.

By decoupling the movement of the character from the actual position, the character will only move until it collides with an object.

Additional info: If the character is moving at high speed, then you may end up with a problem where the character collides a few pixels before a boundary. In that case you can apply the steps by recursively sub-dividing the distance in halves until the distance between the colliding and non-colliding positions is one pixel.
> 0 votes

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


# Question
Title: Is there any equivalent to glPushMatrix in XNA?
I'm trying to implement a scene graph for my 2D game in XNA, and I was looking for a way to draw every object while saving only the local transformation of the object. This seems a bit like glPushMatrix. If such a function exists I can just push a matrix for every node and then call the draw function for all its children.

The whole idea is to avoid passing parent transformations to children. Is there anyway to do so?

# Answer
XNA (nor D3D) does not expose any kind of API-side matrix stack.

There is not that much of a difference between a scene graph visitor that uses the OpenGL matrix stacks and a visitor that maintains its own private stacks.

```
class GLStyleVisitor
{
    public void visit(GroupNode node)
    {
        glMatrixMode(GL_MODELVIEW);
        glPushMatrix(glGetMatrix() * node.mtx);
        foreach (Node child in node.children)
        {
            visit(child);
        }
        glPopMatrix();
    }
}

```

The traditional visitor shown above doesn't have to be changed much to bundle its own stack or any other context along when visiting the graph. At any place inside the visitor, you have access to the state you need for passing into whoever needs it.

```
class PersonalVisitor
{
    Stack<Matrix> transforms;

    public PersonalVisitor()
    {
        transforms.push(Matrix.Identity());
    }

    public void visit(GroupNode node)
    {
        transforms.push(transforms.top() * node.mtx);
        foreach (Node child in node.children)
        {
            Visit(child);
        }
        transforms.pop();
    }
}

```

Note that class names and methods are not overly accurate, as I am not fluent in C# or XNA.
> 5 votes

---
Tags: xna, rendering
---


# Question
Title: Declaring controls in multi form/usercontroll game
In my game I have 2+ forms and 4+ usercontrols. Where should I declare, lets say a textbox that I use in form2, but I need to modify it in form1.

Should I make them public in their own form/usercontrol or should I make a static class with all the controls?

(Edited to clarify my question) I want to know the most used and flexible way.

# Answer
I think I would make the actual TextBox private in its Form, then expose functionality (like get/set text) using either methods or properties, depending on 'obviousness' factor, ie:

```
public string Text1
{
    get { return myTextBox1.Text; }
    set { myTextBox1.Text = value; }
}

```

or...

```
public void SetTextFromVars(int var1, DateTime var2)
{
    myTextBox1.Text = String.Format("Hey, I have got {0} objects since {1}", var1, var2);
}

```
> 2 votes

---
Tags: c#
---


# Question
Title: What technologies were used to create "Dueling Network"?
I want to make a similar browser online multiplayer game like "Dueling Network" (link below) but for a different TCG.

What technologies you believe they used to create it?

Could anyone kindly refer to any good resources/books to start from, so that eventally (not soon) I myself can create something very similar to the game mentioned above, perhaps a little more simpler.

Assuming Flash and AS3 are involved, and I have 0 knowledge of them. Only have been exposed to VB, C#, and most web programming languages.

Dueling Network NSFW: loud music

# Answer
Apache Server, Flash, PHP, Javascript, and a few other things.

Source: http://builtwith.com/duelingnetwork.com

This may not be 100% accurate, but it at least lets you tell what technology that front page is reporting.
> 2 votes

# Answer
I may not be able to answer the direct question of what technologies this specific game uses, but the more general question of what technologies are ideal.

For an MMO-WEB style game Flash (AS3) is an extremely useful client interface for the game. Flash is cross browser and cross platform compatible, and has access to a high level socket layer (used for network communications).

AS3 has two kinds of sockets: The Socket and the XMLSocket. Now most people make the very faulty assumption that XMLSockets are easier to use, when in reality they are identical except one is meant to parse only XML data (from things like feeds, or web page data), which isn't very useful for games. The regular plain Socket is what you should spend time learning. Unfortunately there are very few tutorials around the web, as Socket programming is still quite young in Flash, but still very useful.

The basic idea from the Flash (Client) side of things is:

> Create Socket Object -\> Give It Server IP/Port To Connect To -\> Attempt Connection -\> Create Listener For Incoming Data -\> Wait For All Data On Line -\> Use Data -\> Send Data -\> Listen For Incoming...

---

Now as for the Server side, DO NOT USE FLASH. Flash may be very useful as a Client, but as a Server it's pretty much useless. You need a language that supports threading, I'm currently using C# as my Server backend so that's the only I can recommend (but it is by no means the only or best option). C# provides easy use of threads and has a similar Socket system.

The Server is FAR more complicated than the Client, as you must manage every connection asynchronously (at the same time), and worry about things like bad data, attacks, disconnects, flooding, overloading, timeouts, lost packets, and a seemingly endless list of trivialities.

You also have to manage all user data, lobby handling, game handling for which I personally use mySQL. It looks super complicated on the surface, but it's pretty much a beefy excel (please no flames for the slack comparison). It's quite easy to make a simple database to store usernames/passwords, or game information, and if you use raw access from C# it's also quite zippy.

---

So in a nutshell, you don't need a book. Go look for information on simple socket interfaces in AS3 and C# (or a language of your choice, but I recommend C#). Learn about threading and why it's used, there are plenty of great tutorials. Then learn about how games transfer data to and from the server, and why they do the things they do. But before you do all of this make sure you have a STRONG working knowledge of both Flash, AS3 and C#. You should be able to create the game to be made networked in full, start to finish - then only after it is complete add networking last.
> 0 votes

---
Tags: flash, actionscript-3, multiplayer, online
---


# Question
Title: Bodies are colliding but refusing to rotate in Box2D
I'm running box2d in C++ and hooking it up to C# via p/invoke. All physics stuff occurs in C++.

My problem is that bodes know when they are colliding and do so with great precision. However if I have two boxes which are 10x10 units, one located at the origin and is static while another is set 30 units in the sky 4 units across and is dynamic, when the dynamic box falls and hits the static one it stops falling but doesn't turn and slide off the edge.

Here's a screenshot of what I mean:

The box on top is as far to the left as it possibly can be, any further left and it will fall past the box on the bottom. There is barely a pixel overlap that's keeping the top box there. As you can see it's not rotating to fall off.

This also happens (again only the lowest most box is static, the rest fell down a distance to get there),

Any ideas what I'm doing wrong?

My code for creating boxes is as such:

```
extern "C"
int CreateBox(b2Vec2 dim, b2Vec2 pos, bool dynamic, int worldid)
{
    dim.x /= 100.0f;
    dim.y /= 100.0f;
    pos.x /= 100.0f;
    pos.y /= 100.0f;

    World &g = GetWorld(worldid);
    b2BodyDef bodef;

    bodef.type = b2_staticBody;
    if(dynamic)
    {
        bodef.type = b2_dynamicBody;
    }
    bodef.position = pos;
    bodef.angle = 0;
    b2Body* pBody = g.m_pWorld->CreateBody(&bodef);

    b2PolygonShape groundBox;
    b2Vec2 center = b2Vec2(-dim.x / 2.0f, -dim.y / 2.0f);
    groundBox.SetAsBox(dim.x / 2.0f, dim.y / 2.0f, center, 0);
    for(int i = 0; i < b2_maxPolygonVertices; i++)
    {
        b2Vec2 vert = groundBox.m_vertices[i];
        vert.x += dim.x / 2.0f;
        vert.y += dim.y / 2.0f;
        groundBox.m_vertices[i] = vert;
    }

    b2FixtureDef fixtureDef;
    fixtureDef.shape = &groundBox;
    pBody->CreateFixture(&fixtureDef);
    //fixtureDef.density = 10;

    pBody->SetUserData((void*)++g.m_actorid);

    g.m_bodies.push_back(pBody);

    if(dynamic)
    {
     //   pBody->SetAngularVelocity(0.5f);
    }

    return g.m_actorid;
}

```

and I create the boxes in C# like so:

m\_worldid = CreateWorld(ToB2(new Vector2(0, -1.8f)));

m\_boxID1 = CreateBox(ToB2(new Vector2(50, 50)), ToB2(new Vector2(-51,300)), true, m\_worldid); m\_boxID2 = CreateBox(ToB2(new Vector2(50, 50)), ToB2(new Vector2(0,0)), false, m\_worldid);

Using the box ids I grab positions and rotations from the C++ code (and the get functions take into account that I've /= 100 the dimensions), it all works fine on that front, code here for those interested:

```
extern "C"
ActorTransform BodyTransform(int bodyid, int worldid)
{
    World &g = GetWorld(worldid);

    for(int i = 0; i < g.m_bodies.size(); i++)
    {
        if( (int)g.m_bodies[i]->GetUserData() == bodyid)
        {
            ActorTransform c;
            c.Position = g.m_bodies[i]->GetPosition();
            c.Rotation = g.m_bodies[i]->GetAngle();
            c.Position *= 100.0f;

            return c;
        }
    }
}

```

Another interesting thing to note is if I set an angular velocity on the box it actually is physically represented on screen and it can cause the box to fall off, setting rotatens on bodes also seems to work.

Actually continuing on from setting angular velocities. I found that if I set an angular velocity just once the velocity doesn't go away, even after it lands on the static box it continues to rotate as if it were a motor or something. I'm guessing this has something to do with my core problem since bodies aren't meant to maintain an angular velocity that was set on them just once..

so any ideas?

# Answer
Ok fixed it thanks to someone from the box2d forums correct an obvious mistake.

Change this:

```
pBody->CreateFixture(&fixtureDef);
//fixtureDef.density = 10;

```

into this:

```
fixtureDef.density = 10;
pBody->CreateFixture(&fixtureDef);

```

Done.
> 4 votes

---
Tags: 2d, physics, box2d, ios
---


# Question
Title: How can I cancel a contact in a b2ContactListener?
To know when contacts happen we can derive from b2ContactListener and implement our own solution which is great. I'm wondering is there anyway we can cancel a contact, that is to say when we hit begin contact we call a function or do something to destroy the contact before it has a chance to be resolved?

My game logic relies on setting any number of collision groups (which are basically integers). Collision groups can have settings to interact with one another, for example collision group 41 and 13 may be set to never collide while group 41 and 56 will collide. Some groups which are set not to collide are still meant to generate an OnContact callback (but will obviously never get to end contact).

# Answer
> 12 votes
Use `PreSolve` rather than `BeginContact`. From the Box2D documentation:

> Pre-Solve Event
>
> This is called after collision detection, but before collision resolution. **This gives you a chance to disable the contact based on the current configuration**. For example, you can implement a one-sided platform using this callback and calling **b2Contact::SetEnabled(false). The contact will be re-enabled each time through collision processing, so you will need to disable the contact every time-step.** The pre-solve event may be fired multiple times per time step per contact due to continuous collision detection.

---
Tags: collision-detection, physics, box2d, callbacks
---


title: Drawing a 2D Coordinate Map

text:
# Question
Title: Drawing a 2D Coordinate Map
I'd like to draw a 2Dimensional coordinate system using C#. Unfortunately, in terms of a graphics rendering engine, XNA is out of the question since I'm running Linux. Thus, is this possible without XNA? How exactly would I go about doing this? My goal is to have something which allows the user to click on any specific area and have a dot appear in the spot where the mouse has clicked.

If I can't do this in C#, how would I go about coding it in C++?

# Answer
> 3 votes
I remember advocating AgateLib to you, but it's hard to get into and it wont work without a bit of OpenGL knowledge. So it is as good time as ever to remember some OpenGL :)

First step would be to download OpenTK. You may want to google for any OpenTK tutorials, but since I doubt their existence, we will just code away.

After unpacking OpenTK somewhere, lauch MonoDevelop, Ctrl+Shift+N, select empty project, add references to the OpenTK.dll and System.Drawing, add new empty class named "PointsExample" or something, and that's it.

Now let's get those points on the screen! Here is a complete code with commentaries.

```
namespace Points
{
    using System;
    using System.Drawing;
    using System.Collections.Generic;
    using OpenTK;
    using OpenTK.Input;
    using OpenTK.Platform;
    using OpenTK.Graphics.OpenGL;

    public class PointsExample : GameWindow
    {
        // These are clipping planes, forget them for now.
        private const int nearPlane = 1;
        private const int farPlane = 11;

        // Here we will store mouse position on click.
        private List<Vector2> points = new List<Vector2>(32);

        public PointsExample()
            : base(800, 600, OpenTK.Graphics.GraphicsMode.Default, "The shortest distance between two points is under construction.")
        {
            // It's a bad karma to place complex logic in constructors,
            // so we will perform initialization elsewhere.
        }

        protected override void OnLoad(EventArgs e)
        {
            // This method will be called on window load,
            // looks like a good place for initialization.

            // Lets enable VSync and remove distracting buzz of coolers.
            // Actually, coolers are still buzzing, because VSync won't work in windowed mode.
            OpenTK.Graphics.GraphicsContext.CurrentContext.VSync = true;

            // Depth buffer isn't needed for simple 2D drawing,
            // so we tell OpenGl to not update it.
            GL.Disable(EnableCap.DepthTest);

            // Disable polygon culling, it's not needed in 2D drawing.
            GL.Disable(EnableCap.CullFace);

            // Points will be drawn with anti-aliasing.
            GL.Enable(EnableCap.PointSmooth);
            GL.PointSize(24.0f); // Make points large and noticable.

            // Points will have smooth edges.
            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);

            GL.Viewport(ClientRectangle);

            // Grab a kvass and read: http://www.songho.ca/opengl/gl_transform.html
            // It's important to understand matrices, or your attempts at drawing
            // will be constantly thwarted by math.

            // Lets setup a projection by switching to projection matrix stack,
            // then multiply identity matrix and a transformation that produces a parallel projection.
            // Now (0, 0) is the top left, X coord is going to the right
            // and Y coord is going to the bottom, both coords map to the screen pixels.
            GL.MatrixMode(MatrixMode.Projection);
            GL.LoadIdentity();
            GL.Ortho(0, Width, Height, 0, nearPlane, farPlane);

            // Still confused?
            // Selectively read this: http://www.falloutsoftware.com/tutorials/gl/gl0.htm
            // and keep in mind that even though we're drawing 2d stuff, we're doing so in the 3d world.

            // Also notice that the near clip plane is set at depth of 1, and far plane at the depth of 11.
            // Everything closer than 1 and farther than 11 will be cut off.

            // Now coord (31, 63) would mean 32-nd pixel to the right from left border
            // and 64-th pixel downwards from top border of the screen.

            Mouse.ButtonDown += OnMouseClick;
        }

        private void OnMouseClick(object sender, MouseButtonEventArgs e)
        {
            // User clicks — we add a point for drawing later.
            // Thanks to orthographic projection mouse coords
            // directly correspond to the world coords.
            // Later you may want to read about Project/Unproject.
            points.Add(new Vector2(e.X, e.Y));
        }

        protected override void OnUnload(EventArgs e)
        {
            // Not used in this example,
            // but typically you will want to do a complete deinitialization here.
        }

        protected override void OnResize(EventArgs e)
        {
            // Update viewport when resizing window.
            GL.Viewport(ClientRectangle);

            // Uncomment these lines to disable scaling on screen resize:
            // GL.MatrixMode(MatrixMode.Projection);
            // GL.LoadIdentity();
            // GL.Ortho(0, Width, Height, 0, nearPlane, farPlane);
        }

        protected override void OnUpdateFrame(FrameEventArgs e)
        {
            // Typically your game logic will be updated in this update loop.
            // We don't have any time-dependent progress logic yet, so it's empty.
        }

        protected override void OnRenderFrame(FrameEventArgs e)
        {
            GL.ClearColor(Color.CornflowerBlue);  // It's almost like XNA :)
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            // Finally, it's time to draw the points in the draw loop.

            // Remember the setup of the clipping planes?
            // We will need to draw our geometry somewhere between the two clip planes
            // so it will be visible.

            // Start operations on model-view matrix stack...
            GL.MatrixMode(MatrixMode.Modelview);

            // Pushing matrices is not really needed in this simple example,
            // but typically you will use PushMatrix before drawing object
            // whose transformations depend on previously computed matrix,
            // and that's going to happen very often.
            GL.PushMatrix();
            GL.LoadIdentity();
            // Remember that negative Z axis is going "into the screen", so we move vertices away from camera.
            GL.Translate(0.0f, 0.0f, -((nearPlane+farPlane) / 2f));

            // Begin drawing points.
            // Read about drawing primitives here:
            // http://www.opentk.com/doc/chapter/2/opengl/geometry/primitives
            GL.Begin(BeginMode.Points);
            GL.Color3(Color.Gold);  // From now on all vertices will be golden.

            foreach(var point in points)
            {
                GL.Vertex2(point);
            }

            GL.End(); // End drawing points.

            GL.PopMatrix(); // We pushed, so now we need to pop previous matrix from the stack.

            SwapBuffers();
        }

        [STAThread]
        static void Main()
        {
            using (var game = new PointsExample())
            {
                game.Run(200.0, 0.0);
            }
        }
    }
}

```

And that's all for a simple task of drawing colored points. I hope that you've found it useful and that I didn't do anything wrong :)

---
Tags: c++, c#
---


# Question
Title: Techniques for (literally) cutting corners on square grid maps
My game involves a level with deformable terrain and units that can travel in any direction but are slowed down by uneven terrain. Normal A-star should work fine in most cases, except on flat land where no matter how the general purpose pathfinder worked it would not send units on a direct path. Theta-star would work if the entire level was fairly flat, but would be much slower if it initially had to take uneven terrain into account.

I think a Manhattan-distance base A-star algorithm would be fast and give a good enough hint to allow other path finding or steering algorithms to take over, but I'm not sure what type of algorithm to use to look ahead and decide when to abandon the path, take a more direct route, and where to jump back on the path later.

(Theta-star seems like it would be too inefficient if it was adjusted to take things like slopes, obstacles, or roads into account. See the solution proposed to the comment about avoiding minefields at: http://aigamedev.com/open/tutorials/theta-star-any-angle-paths/ )

Edit: I did not mention that I already implemented and tested A-star on a similar grid. (I think I accidentally deleted something in this question.) Some of the more obvious cost/heuristic functions I considered just don't result in realistic paths on a grid when an obstacle blocks the most direct path (basically when path-finding is useful) (example pictures). The change to the cost function used by the Theta-star algorithm seems like an ideal solution (considering the constraint of using a grid), but it makes the assumption that tiles have the same travel costs (and it takes much longer).

My original reasoning behind using Manhattan distance was to outsource the "corner cutting" algorithm from the path-finding algorithm, since it was more important to have a fast path-finding algorithm in case the obstacle layout or terrain changed. It makes more sense to do the "corner cutting" algorithm once when the unit arrives than on every permutation of every search of path-finding algorithm (the results of which may end up being scrapped anyway.) A four-neighbor search with Manhattan distance is also interesting because you can see boxes of alternate paths and identify right triangles formed by the original path and the shortest path.

A better question would have been "What is a fast way to identify shortcuts in a path with 90 degree turns?"

# Answer
Have you given A\* a chance yet? Provided you weight your costs for different types of terrain appropriately, it will find a best path given the available nodes. It will not however find a straight line over open plains if you give it a square grid, which seems to be your problem with it.

If you want to be able to create straight-line paths across plains, you can collapse the edges of your path into segments wherever the new path is equal or lower cost (I.E. same or less distance and doesn't pass through rougher terrain.) Just take each two pairs of nodes in the path (A-B and B-C) and see if A-C is a better route. If A-C is equal or lesser cost, remove B from the list. Repeat over the list until the iteration where the list doesn't change anymore, and that will solve your plains problem. You do have to do some extra processing to ensure that A-C is a legal move, and to calculate the cost across an arbitrary distance. Or, you could have your units use the path as a general guideline, and move toward the node several positions of them, using simple obstacle avoidance at the same time.

You can also significantly improve your quality of your path by giving A\* more options for nodes to traverse. For instance, just adding diagonals with a x√2 cost will produce a much better path than simple 4-direction traversal.

> I'm not sure what type of algorithm to use to look ahead and decide when to abandon the path, take a more direct route, and where to jump back on the path later.

A\* handles this already. As soon as the node currently being explored is no longer the lowest cost+heuristic, it moves on to the lowest cost+heuristic node.
> 4 votes

---
Tags: path-finding
---


title: Inverted textures

text:
# Question
Title: Inverted textures
I'm trying to draw textures aligned with this physics body whose coordinate system's origin is at the center of the screen. (XNA)Spritebatch has its default origin set to top-left corner. I got the textures to be positioned correctly, but I noticed my textures are vertically inverted. That is, an arrow texture pointing Up , when rendered points down. I'm not sure where I am going wrong with the math.

My approach is to convert everything in physic's meter units and draw accordingly.

```
        Matrix proj = Matrix.CreateOrthographic(scale * graphics.GraphicsDevice.Viewport.AspectRatio, scale, 0, 1);
        Matrix view = Matrix.Identity;

        effect.World = Matrix.Identity;
        effect.View = view;
        effect.Projection = proj;

        effect.TextureEnabled = true;
        effect.VertexColorEnabled = true;

        effect.Techniques[0].Passes[0].Apply();
        SpriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, DepthStencilState.Default, RasterizerState.CullNone, effect);

        m_Paddles[1].Draw(gameTime);

        SpriteBatch.End();

```

where Paddle::Draw looks like:

```
       SpriteBatch.Draw(paddleTexture,
            mBody.Position,
            null,
            Color.White,
            0f,
            new Vector2(16f, 16f),  // origin of the texture
            0.1875f, SpriteEffects.None,   // width of box is 3*2 = 6 meters. texture is 32 pixels wide. to make it 6 meters wide in world space: 6/32 = 0.1875f
            0);

```

The orthographic projection matrix seem fine to me, but I am obviously doing something wrong somewhere! Can someone please help me figure out what am i doing wrong here ?

Thanks

# Answer
> 4 votes
Look at the reference of Matrix.CreateOrthographic, and notice that it says this:

*The viewable area of this orthographic projection is centered on 0,0,0. The x-axis of the area ranges from -width/2 to width/2. The y-axis of the area ranges from -height/2 to height/2.*

So, in your case, the upper border of the screen has an Y coordinate of -scale/2 instead of 0, and the lower border is scale/2 instead of scale. And if you are drawing a quad of size (10,10) at the coordinates (0, 0), its point of origin will be at the center of the screen, but since your positive Y is downwards, you will see it inverted.

Your best choices are just to invert the second parameter so your Y axis points upwards, or define the orthographic matrix with Matrix.CreateOrthographicOffCenter so you can manually specify the world origin.

# Answer
> 0 votes
I *think* you should be able just invert things using your effects world matrix:

```
effect.World = Matrix.CreateScale(1, -1, 1);

```

Instead of using the identity, as you have now.

I hope this helps.

# Answer
> 0 votes
There's no need to manually create and assign your effect's transformation matrices. Spritebatch creates these for you. The simplest way is to create an effect with no vertex shader (unless you're doing something in there besides the expected world-view-projection), since SpriteBatch already has a vertex shader that will take care of the transformation. Then it will use your pixel shader.

Also, I'm not sure if the way you're currently doing it works correctly, but there is a different overload of `spriteBatch.Begin` that takes an Effect as a parameter. I'm not sure if SpriteBatch can properly assign to the current effect if you don't pass it in on `Begin()`.

---
Tags: xna, c#, xna-4.0, farseer-physics-engine, projection
---


# Question
Title: What should I keep in mind while developing a game for Steam?
I recently did the programming on a game that was just released and i've decided that for my next project I want to do something a little bigger scale. I plan to develop a game to be sold on Steam, it will be 3D. I've done large-scale games in Flash and a small game in C++ written with OpenGL. I realize that flash-based games can be submitted to Steam but I'd like for it to be written in some variation of C. I'm looking for information on a couple things.

1. What engine should I use? Ideally I'd like it to work on both Mac and PC. Seeing as it would be released on Steam, I'd like to use the Source Engine but I'm worried about having to pay licensing fees when I don't plan to make loads of money on it - it's mainly for the experience and as a resume builder.
2. What sorts of things should I keep in mind when developing so that when, and if, it gets accepted, the process of adding the Steam-specific functionality will be less painful.

# Answer
> 6 votes
I don't think it matters which engine you use; from what I've seen, steam accepts games that are of high enough quality (polish) and are relevant to the steam customer base.

Winning IGF or some such also helps.

---
Tags: steam
---


# Question
Title: Do you extend Java, to make games, or can you just use JFrame?
I'm starting to create my own side scroller, in Java. I think I've read that, when you create a game in Java, there is something you can extend your class with, like `GamePanel`.

Is this true, or can you just use JFrame for your Java games?

# Answer
> 3 votes
For a Java game that uses no libraries, I would suggest you extend the Canvas class and override the paint(Graphics) method. It is the most basic component you can use without a lot of overhead.

However, I strongly suggest you look into Slick or JMonkeyEngine. They both use LWJGL; the former is for 2D while the latter is for 2D and 3D.

To kill two birds with one stone, I would also suggest you look into Artemis, which is an awesome Entity System that works on top of Slick. The site contains some example games to help you get started.

---
Tags: java, jframe
---