# Question
Title: How do I set an event off when player is on certain tile?
Here is the code I use to create and print my map to the canvas:

```
var board = [];
function loadMap(map) {
    if (map == 1) {
        return  [

            [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,3,0,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,3,0,0,2],
            [2,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,3,3,0,0,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,3,3,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,3,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,3,0,3,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,3,3,3,3,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,3,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,3,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,0,0,3,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,3,0,0,0,0,0,0,0,0,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,3,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,3,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,3,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,3,3,3,3,3,3,3,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,3,3,3,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2],
            [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2]
        ];
    }
}

board = loadMap(1);
enterfor (y = 0; y <= viewHeight; y++) {
        for (x = 0; x <= viewWidth; x++) {
            var theX = x * 32;
            var theY = y * 32;
            context.drawImage(mapTiles[board[y+viewY][x+viewX]], theX, theY, 32, 32);
        }
    }

```

And here is the code I use for player movement:

```
canvas.addEventListener('keydown', function(e) {
    console.log(e);
    var key = null;
    switch (e.which) {
        case 37:
            // Left
            if (playerX > 0) playerX--;

            break;
        case 38:
            // Up
            if (playerY > 0) playerY--;
            break;
        case 39:
            // Right
            if (playerX < worldWidth) playerX++;
            break;
        case 40:
            // Down
            if (playerY < worldHeight) playerY++;
            break;
    }

viewX = playerX - Math.floor(0.5 * viewWidth);
    if (viewX < 0) viewX = 0;
    if (viewX+viewWidth > worldWidth) viewX = worldWidth - viewWidth;

    viewY = playerY - Math.floor(0.5 * viewHeight);
    if (viewY < 0) viewY = 0;
    if (viewY+viewHeight > worldHeight) viewY = worldHeight - viewHeight;

}, false);

```

What I am looking for is a method for when the player lands on tile 3 he loses health.

I have tried to use this in the player movement but it doesnt seem to work e.g the left movement:

```
case 37:
            // Left
            if (playerX > 0) playerX--;
            if(board[x2 - 1] == 3)
            {
                health--;
                playerX--;
            }

```

**EDIT**

Im nearly there guys but for some reason the board position my player should be at isnt coming out correct, yet if i print the array it shows the correct value

```
case 37:
            // Left
            if (playerX > 0) {
                playerX--;
                alert(board[playerX][playerY])
                alert(board);
            };

            if(board[playerX][playerY] == 3){

            }

```

Heres the code with the alerts to help my explanation, if i can figure out why the players position thinks its somewhere else, i should be able to implement my idea

Thanks

# Answer
> 3 votes
I would check if the player moved, and call an event to handle all the checks for new tiles. Something like:

```
...

if(playerX != oldPlayerX || playerY != oldPlayerY) {
    onTileChange(player);
}

...

onTileChange(Character character) {
    int characterTile = getTileAt(character.positionX, character.positionY);
    switch(characterTile) {
       case 3:
          character.subtractHealth(1);
          break;
    }
}

```

This example also shows making the player into an extension of a character object. This means you can use this same method for other creatures in your game too. Plus it puts things in a common place, so for example the `subtractHealth()` function can do the following for characters:

```
subtractHealth(int amount) {
    health -= amount;
    if(health < 0)
      triggerCharacterDeath(this);
}

```

Then you don't have to repeat that code everywhere that you subtract health. Makes for cleaner code.

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


# Question
Title: How to create realistic 2d lighting using colour temperature
I'm looking for a lighting algorithm that produces realistic lights expressed in kelvins, from about 2500k to 6500k. What I'm confused about is how to make the lights properly interact with the colors of game objects.

If a whole level is fully lit (overcast daylight) then it would seem that I should use just the color of the object. But what if I'm in a closed room with no windows, and there is an incandescent bulb shining light in the room? How would that light properly light up the objects in the room?

There does not seem to be an obvious solution to the problem. And simply mixing the color of the light with the colors of the object, seems an inaccurate approach.

# Answer
The "color of the object", i.e. the RGB value of the texture, formally represents its reflectance spectrum, discretized by averaging it over the response curves of the three color receptors in the human eye.

Thus, to get the apparent color of a point on an object's surface, you simply sum together the colors of the lights that fall on it and multiply the result with the color of the surface, doing this separately for all the three color channels.

Of course, this doesn't account for the fact that real lights and real surfaces may have complicated spectra that are not fully represented by a simple RGB triplet, but in practice it works pretty well — the spectral details that are not well represented by the RGB approximation tend to also be the ones that the human eye can't distinguish.

---

For example, let's say you have two lights A and B, with colors *C*A = (1.0, 1.0, 1.0) and *C*B = (1.2, 1.0, 0.8) and brightnesses *L*A = 1000 and *L*B = 5, which are at distances *d*A = 50 and *d*B = 4 from a point P with color *C*P = (0.3, 0.8, 0.2). Assuming the standard falloff of light intensity as the inverse of the squared distance, the total light intensity at the point P (assuming that both lights actually hit the point) is:

*C*total = *C*A *L*A / *d*A2 \+ *C*B *L*B / *d*B2
= (1.0, 1.0, 1.0) · 1000 / 502 \+ (1.2, 1.0, 0.8) · 5 / 42
= (1.0, 1.0, 1.0) · 0.4 + (1.2, 1.0, 0.8) · 0.3125
= (0.4, 0.4, 0.4) + (0.375, 0.3125, 0.25)
= (0.775, 0.7125, 0.65)

Now multiply this componentwise with the surface reflectance *C*P to get the apparent color of the point:

*C*refl = *C*total*C*P = (0.775 · 0.3, 0.7125 · 0.8, 0.65 · 0.2) = (0.2325, 0.57, 0.13)

(If you're doing indirect illumination, this is also the color of the light reflected from the point P.)

Note that, in the example above, I normalized the light colors *C*A and *C*B so that the average of their components is 1.0 and used the separate scaling factors *L*A and *L*B to represent their intensities. This is just a matter of personal preference, and you could just as well bake the intensities into the light colors if you wanted, but this way seems clearer to me. Also, for lights that are very distant and very bright, such as the sun, you'll probably want to leave out the 1/*d*2 term and just let the *L* represent the brightness of the light *at the scene*.

Also note that, while the light intensities can (and typically will) exceed 1.0, the reflectance values should not. If they did, that would mean that the object would reflect more light than falls on it, which is obviously absurd. The reflected light intensity can also exceed 1.0; that just means that the light exceeds the maximum brightness that can be displayed on the screen. You can just clip those color values to 1.0, although you'll probably get nicer results if you render them unchanged into a HDR buffer and apply a bloom shader to the result. If the average illumination level can change a lot (e.g. if the player can move between outdoors and indoors), you'll probably also want to include a variable scaling factor to account for adaptation of the eye to the varying light levels.

Also, if you're not doing true indirect illumination, you'll probably want to include an "ambient" light term (preferably with some approximate ambient occlusion factor) in your calculations to avoid your shadows being completely dark. One way is to simply let the ambient light have a fixed color (usually neutral gray) and brightness everywhere, but you could also e.g. try making the ambient light proportional to the total light level in the area, ignoring (most) shadows, or use more advanced techniques for estimating the ambient illumination. Another term you may want to include is light emission from glowing surfaces; that can simply be handled by adding it to the final result.

Finally, everything I've written above only deals with diffuse reflection; specular reflection and highlights are a whole 'nother kettle of fish entirely (although the same basic physical principles still apply).
> 7 votes

# Answer
A Common way to do nice lighting in 2d games are to blend the level with light shaped textures. not sure if thats what your after...
> 1 votes

---
Tags: c++, 2d, lighting
---


# Question
Title: How can I edit .qvm (Quake Virtual Machine) files?
I was browsing through how to mod a game (Urban Terror, a Quake 3 mod). I found that it can be done by editing .qvm files in the game. Under the file named zpak000.pk3. That file contains other files named

```
ui.qvm
qagame.qvm
cgame.qvm

```

But I can't find a way in which I can edit these files.

# Answer
You create qvm files using the c-compiler in the Quake SDK.

**You can't edit QVM files.**

(You could technically modify them using a hex editor, in the same way that you can modify other compiled programs, but this is not useful for your purposes.)
> 10 votes

# Answer
There are basically 2 ways to "mod a mod". Either you get hands on the original source code or you have to delve into the blackbox.

Since the source of Urban Terror is closed-source (except for the engine; which is a fork of the Quake 3 engine, called ioQuake 3), you have to 'delve' into the blackbox.

This involves using a disassembler, which is able to process them .qvm's binary data and yields the assembler logic of the mod. Using this, one is able to make modifications. The "workflow" is quite comparable to "cracking" existing software: Disassemble the binary. Find the instructions of interest overwritte them.

On the links posted below, you'll find a small guide and a disassembler.

It is important to notice, that the License of the game prohibits **ANY** modifications.

> EDIT: I answered this when I was 14, the original answer isn't good. But left here "historical" reasons.
>
> Well, never heared about google :) ?
>
> Look at game-deception it explains how to modificate a qvm (' after it has been compiled '). It just over-compile the certain lines / commands. The only problem ( for you ) is, that you have to work with opcodes ( / assembler ). Well, here's the tutorial made by the great macpunk : http://www.gamedeception.net/threads/19198-Runtime-QVM-Modification

```
> vmHeader_t *hook_VM_LoadQVM( vm_t *vm, qboolean alloc )
>
> {
>
> vmHeader_t *ret = orig_VM_LoadQVM(vm, alloc);
>
> if(!strcmp(vm->name, "cgame")
>
> {
>
>     vm->instructionPointers[0x0FF5E7] = 0x00; //0x00 is the opcode of whatever you want the instruction to be
>
> }
>
> return ret; }

```

> You need to Quake3 Engine SDK for the structs.
> 1 votes

# Answer
Edit them with a hex editor downloaded somewhere from the 'net.
> -7 votes

---
Tags: modding, quake3
---


# Question
Title: Do I need a Point and a Vector object? Or just using a Vector object to represent a Point is ok?
Structuring the components of an engine that I am developing along with a friend (learning purposes), I came to this doubt.

Initially we had a Point constructor, like the following:

```
var Point = function( x, y ) {
    this.x = x;
    this.y = y;
};

```

But them we started to add some Vector math to it, and them decided to rename it to Vector2d.

But now, some methods are a bit confusing (at least in my opinion), such as the following, which is used to make a line:

```
//before the renaming of Point to Vector2, the parameters were startingPoint and endingPoint
Geometry.Line = function( startingVector, endingVector ) {
    //...
};

```

I should make a specific constructor for the Point object, or there are no problems in defining a point as a vector?

I know a vector have magnitude and direction, but I see so many people using a vector to just represent the position of an object.

# Answer
It's unlikely there would be any problems with conflating the definitions and treating points as vectors — but be a little careful, because some APIs have a 'Point' class that you might need to use (for representing, e.g., vertices of polygons) and if you define your own class you'll want to be able to port them back and forth.

What I *would* do, though, is treat them equivalently in your code; if you do use vector and point interchangeably, then there's no reason that your declaration for the Line() function should be talking about 'startingVector' and 'endingVector'. I would strongly encourage going back to

```
Geometry.Line = function( Vector startingPoint, Vector endingPoint ) {
    //...
};

```

Points are what those parameters represent, even if they're using class Vector to do so.
> 8 votes

# Answer
Just use the Vector object. Even if you feel this is/has been used incorrectly in the past, it's what people expect. Plus, it's not necessarily incorrect to use a vector as a point. And would difficult to do outside of discussion since both data structures require the same primitive types. The only differences will be the member functions, and it's easy enough to put those in the same class, since there's not much in the way of conflicting methods between the two.

Since you're learning, it's good to learn that doing what people expect is often the best way to do things (for trivial choices like the one being presented).
> 4 votes

# Answer
Points are locations in space. Once you have a coordinate system, you can describe those points as a distance and a direction from the origin (a vector). So it is perfectly reasonable to use vectors to describe the start and end points of a line.

Just be aware that all points can be represented as a vector, but vectors are not points. Most vectors, e.g velocity, normal etc, don't have any sense of location.

Think of the wind, you can talk about it's direction and it's strength, but you can't talk about its position or location. This is how you should think of vectors when they are NOT being used to describe points in space.
> 3 votes

# Answer
To define a point, you need only one vector. To define a line, you need two. Typically, you have either two points that lie on the line or one vector representing a point that lies on the line and the other vector representing the direction of the line.

There are no problems defining a point as a vector, because a point IS a vector with direction equal to its coordinates and magnitude equal to its distance from 0,0.

So you don't need two separate classes to represent a Point and "Vector2d", although a Point could presumably be a subclass of Vector2d with different member functions directly related to your drawing or processing, while Vector2d might only do strict vector math functions like dot products.
> 2 votes

# Answer
Yes, it's ok to use a single `Vector` class to define both points and vectors, **as long as you ensure that the `w` component of the vector is `0`**.

The *key* difference between a point and a vector is that a point represents a physical location in space, offset from the origin, whereas a vector represents a *direction*. A point can be translated, a vector *can not*. The `w` component of a 2- or 3-dimensional `Vector` class is what allows the translation component of a transformation matrix to take effect. If `w` is `1`, then translation and rotation will be applied; if it is `0`, then only rotation will be applied.

Not having the `w` component of a vector set `0` can come back to bite you; it leads to bugs that are rather difficult to track down. To be safe, you can make a `Point` class that inherits from the `Vector` class and explicitly sets `w` to `1`, where the `Vector` class defaults `w` to `0`.
> 2 votes

# Answer
Points and vectors can be thought of as the same thing. If it makes sense to you, you can think about vectors that represent position this way, and then it is logical to use a `Vector2` class everywhere you would have otherwise used a `Point` class.

In mathematics, vectors are sometimes used to represent position. When used in this sense, the vector represents where some entity is located relative to an origin point. For example, suppose you are making a sh'mup and you want to keep track of where the player's ship is in the playing area. If you treat the bottom-left hand corner of the play area as (0, 0), then you could represent the player's location with a `Vector`:

```
   * Player (3,3)
  /
 /
. (0,0)

```

What the vector means in this case is that the ship is 3 units to the right of and 3 units above the origin. (Note that you can also use a vector for the player's speed, in which case the player would move 3 units right and 3 units up every second or frame. Both position and speed would be represented by the same vector class, but their vectors would be processed differently in the player's script.)

To use your line example, the position vector represents where the starting "point" and ending "point" are located relative to the origin. If your origin is the center of the playing area, you could determine a line like this:

```
             * (8, 2)
             |
     . (0,0) |
             |
             * (8, -2)

```

So one end of the line is 8 units to the right of and 2 units above the center of the playing field, and the other one is 8 units right and 2 units down.

Just to be clear, this isn't to say you have to use a `Vector` class instead of a `Point` class. This is just one way of thinking about this situation that can make it easier to decide how to implement those ideas.
> 2 votes

# Answer
It depends on the implementation. If you have to have methods on the Vector2d instead of its prototype, then there's a cost for that, given the amount of points you'd need in a game, a major one. It's just how JavaScript works. In that situation it's better to create a Point2d class that doesn't have all the unnecessary functions.
> 0 votes

---
Tags: mathematics, architecture, javascript, vector
---


# Question
Title: Using NumPy arrays as 2D mathematical vectors?
Right now I'm using lists as position, velocity, and acceleration vectors in my game. Is that a better option than using NumPy's arrays (not the standard library's) as vectors (with `float` data types)? I'm frequently adding vectors and changing their values directly, then placing the values in these vectors into a Pygame `Rect`. The vector is used for position (because `Rect`s can't hold floats, so we can't go "between" pixels), and the `Rect` is used for rendering (because Pygame will only take in `Rect`s for rendering positions).

# Answer
> 0 votes
This answer recommends gameobjects which has a Vector2 class. I'm not sure how it will interact with Pygame's Rects.

---
Tags: mathematics, vector, python, data-structure, pygame
---


# Question
Title: Help w/ iPad 1 performance for tile-based DOM Javascript game
I've made a 2D tile-based game with DOM/Javascript. For each level, the map data is loaded and parsed, then lots of tiles ( elements) are drawn onto a larger "map" element. The map is inside of a container that hides overflow, so I can move the map element around by positioning it absolutely. Works a treat on desktop browsers, and my iPad 2.

My problem is that performance is really bad on iPad 1. The performance hit is directly related to all the tile elements in my map, because when I remove or reduce the number of tiles drawn, performance improves. Optimizing my collision detection loop has no effect.

My first thought was to batch groups of tiles into containers, then hide/show them based on proximity to the player, however this still causes a huge hiccup when the player moves and a new group of tiles is displayed (offscreen). Actually removing the out-of-sight elements from the DOM, then re-adding them as necessary is no faster.

Anyone know of any tips that might speed up DOM performance here? My map is 1920 x 1920 pixels, so as far as I know should be within the WebKit texture limit on iOS 5/iPad. The map is being moved with CSS3 transforms, and I've picked all the other obvious low-hanging fruit.

# Answer
> 3 votes
The trick is to only use enough tiles to fill your viewport - that's also how classic consoles (like the NES) simulated huge/wide backgrounds and maps. This is also the reason why these consoles (especially the NES) had sometimes colors overlapping from one side of the screen to the other (as it's essentially continuous memory being wrapped).

For example, if your viewport is 320 pixels wide and one tile has a width of 32 pixels, then you use 11 columns to render the Background/tiles (10 tiles just for the width and another column to fill the gap on the left or right).

How so? Easy: No matter how you move the tiles, there'll always be a maximum of 11 tiles be visible next to each other. If your viewport is exactly at the borders of tiles, you see ten tiles. Move them a bit to the left or right and an eleventh tile appears on the other side.

So rather than creating, deleting and/or moving tiles around, just move them to have proper tile borders and update their content accordingly. This way 32px wide tiles will move by a Maximum of 32 pixels in one direction.

This sounds a bit complicated, but it's actually rather easy.

I've had to look around a bit to find some sources without having to draw something myself (rather late already).

Look for the section **Tiled Backgrounds and Levels**, which will show you an image of a tiled background. They use a different width, so they always show 12 or 13 tiles horizontally. Just consider how the grid would move. Once a full row of tiles disappears on either side, all tiles are moved back by one row and their images are updated accordingly.

Also just to mention it: I'm not sure about the iPad's capabilities, but shouldn't you be able to use the canvas element? I'm sure it would be more performant.

# Answer
> 0 votes
I suggest you use canvas, and then prerender the tile map. This is a process of rendering large chunks of your tile map to off-screen images, which are then blitted to the screen. This can dramatically redice the number of image draws, which should increase performance. We've managed to get some pretty good performance from iPad 1's using this technique.

BTW: the playcraft engine will do this for you automatically (plug). It's in open beta and is free. http://playcraftlabs.com

---
Tags: javascript, html5, optimization, ipad
---


# Question
Title: Scaling Sound Effects and Physics with Framerate
(I'm using XNA and C#) Currently, my game (a shooter) runs flawlessly with 60 FPS (which I developed around). However, if the framerate is changed, there are two major problems:

* Gunshot sound effects are slower
* Jumping gets messed up

Here's how I play gunshot sounds:

```
update(gametime)
{
    if(leftMouseButton.down)
    {
        enqueueBulletForSend();
        playGunShot();
    }
}

```

Now, obviously, the frequency of playGunShot depends on the framerate. I can easily fix the issue if the FPS is higher than 60 FPS by capping the shooting rate of the gun, but what if the FPS is less than 60? At first I thought to just loop and play more gunshots per frame, but I found that this can cause audio clipping or make the bullets fire in "clumps."

Now for the second issue: Here's how jumping works in my game:

```
if(jumpKey.Down && canJump)
{
    velocity.Y += 0.224f;
}

// ... (other code) ...
if(!onGround)
    velocity.Y += GRAVITY_ACCELERATION * elapsedSeconds;

position += velocity;

```

The issue here is that at \< 60 FPS, the "intermediate" velocity is lost and therefore the character jumps lower. At \> 60 FPS, the game adds more "intermediate" velocities, and therefore the character jumps higher.

For example, at 60 FPS, the following occurs:

1. Velocity increased to 0.224
2. Not on ground, so velocity decreased by X
3. Position increased by (0.224 - X) \<-- this is the "intermediate" velocity

At 30 FPS, the following occurs:

1. Velocity increased to 0.224
2. Not on ground, so velocity decreased by 2X
3. Position increased by (0.224 - 2X) \<-- the "intermediate" velocity was lost

All help is appreciated!

# Answer
Regarding the jumping problem:

You need to incorporate the time since the last frame into your calculation when you apply velocity to position. Assuming you have perfected things for 60fps:

```
//Time values in milliseconds, 1000/60fps = 16.6667
position += velocity * ((thisFrameTime - lastFrameTime) / 16.6667);

```

You will need to post more information about the sound issue. How are you playing your sounds?
> 2 votes

# Answer
I don't know about XNA specific but as I understand your scenario, you have two options for the jumping problem (that will probably appear again in other situations later, ie misdetected collisions that allow wall trespassing): 1- You must measure the delta time between frames and multiply each acceleration/velocity vectors using that delta as factor. 2- Fix your timesteps. You do this by not allow other than a fixed, previously choosen, delta. Depending on the time spend rendering each frame, you will call your logic update loop one time or more for each screen update, but each iteration is guaranteed to represent the same delta. Maybe this link can help you: http://gafferongames.com/game-physics/fix-your-timestep/ (pay attention to key concepts: "your renderer produces time, and your simulation consumes it", and "spiral of death" that is important when resuming from a pause for example. Ignore C++ specifics and concentrate in the concepts).

I like 2, because it simplifies logic planning and assumptions made for physic simulation as it lets you use constant values and the game will still adapt to different machines and produce the same results. In the worst case, the game will lag (ie: in old hardware), but still things like wall trespassing won't occur.

For the audio lag problem: you said all is ok if frame rate is 60 FPS. Well, if you use semi fixed timesteps the update logic loop will be called enough times to maintain a constant 60 updates per second, only will lag in very old hardware or when something else is sucking system resources. Also note that you can have 60 screen refreshes and 120 logic loop updates, for shooters I think is not bad solution.

If with "lag" you did mean latency (sounds delay): assuming your playSound function does not block, that's ok, but the code that look for the audio resource to play should block and run in the same thread that your game logic, game logic must stop until the sound resource is found (if you have some kind of audio resource manager for example). Otherwise you will notice that in some situations the sounds are not correctly synchronized with what happening in the rendered scene.
> 1 votes

# Answer
Have you tried decoupling the render loop from the update loop? I don't have any experience with XNA/C# though, so I'm not sure how complicated that might be for you.
> 1 votes

---
Tags: xna, c#, physics, sound, .net
---


# Question
Title: Good resources for learning about graphics hardware
I'm looking for some good learning resources for graphics hardware (and associated low level software). Basically I want to learn more about what goes on underneath the opengl/direcx API layers in terms of how things are implemented.

I familiar with what happens *in principle* during the various stages of the rendering pipeline (viewing, projection, clipping, rasterization etc).

My goal is to be able to make better and more informed decisions about tradeoffs and potential optimisations when graphics/shader programming with respect to the following kinds of issues;

* batching
* view culling
* occlusions
* draw order
* avoiding state changes
* triangles vs pointsprites
* texture sampling
* etc

Basically whatever the graphics programmer needs to know about modern graphics hardware in order to become more effective.

I'm not really looking for specific optimisation techniques, rather I need more general knowledge so that I will naturally write more efficient code.

# Answer
> 5 votes
Fabian Giesen's series of blog posts A Trip through the Graphics Pipeline is the best place I know of to get an under-the-hood view of how modern GPUs work, and what APIs like D3D and OpenGL are really doing for you.

---
Tags: graphics-programming, optimization, hardware
---


title: XNA- Transforming children

text:
# Question
Title: XNA- Transforming children
So, I have a `Model` stored in `MyModel`, that is made from three meshes. If you loop thrue `MyModel.Meshes` the first two are children of the third one. And was just wondering, if anyone could tell me where is the problem with my code.

This method is called whenever I want to programmaticly change the position of a whole model:

```
public void ChangePosition(Vector3 newPos)
{
    Position = newPos;

    MyModel.Root.Transform = Matrix.CreateScale(VectorMathHelper.VectorMath(CurrentSize, DefaultSize, '/')) * Matrix.CreateFromAxisAngle(MyModel.Root.Transform.Up, MathHelper.ToRadians(Rotation.Y)) *
        Matrix.CreateFromAxisAngle(MyModel.Root.Transform.Right, MathHelper.ToRadians(Rotation.X)) * Matrix.CreateFromAxisAngle(MyModel.Root.Transform.Forward, MathHelper.ToRadians(Rotation.Z)) *
        Matrix.CreateTranslation(Position);

    Matrix[] transforms = new Matrix[MyModel.Bones.Count];
    MyModel.CopyAbsoluteBoneTransformsTo(transforms);

    int count = transforms.Length - 1;
    foreach (ModelMesh mesh in MyModel.Meshes)
    {
        mesh.ParentBone.Transform = transforms[count];
        count--;
    }
}

```

This is the draw method:

```
foreach (ModelMesh mesh in MyModel.Meshes)
{
    foreach (BasicEffect effect in mesh.Effects)
    {
        effect.View = camera.view;
        effect.Projection = camera.projection;
        effect.World = mesh.ParentBone.Transform;
        effect.EnableDefaultLighting();
    }
    mesh.Draw();
}

```

The thing is when I call `ChangePosition()` the first time everything works perfectlly, but as soon as I call it again and again. The first two meshes(children meshes) start to move away from the parent mesh.

Another thing I wanted to ask, if I change the scale/rotation/position of a children mesh, and then do `CopyAbsoluteBoneTransforms()` will children meshes be positioned properlly(at the proper distance) or would achieving that require more math/methods?

Thanks in advance

# Answer
if you want change the whole model position that is not the code:

```
   // Copy any parent transforms.
    Matrix[] transforms = new Matrix[myModel.Bones.Count];
    myModel.CopyAbsoluteBoneTransformsTo(transforms);

    // Draw the model. A model can have multiple meshes, so loop.
    foreach (ModelMesh mesh in myModel.Meshes)
    {
        // This is where the mesh orientation is set, as well
        // as our camera and projection.
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.World = transforms[mesh.ParentBone.Index] *
                Matrix.CreateRotationY(modelRotation)
                * Matrix.CreateTranslation(modelPosition);

```

for moving other meshes... you have to change the bone... but it maybe quite hardcore... is better to use an animation tool

Keep in mind that the Bone transform is relative to its parent bone transform and play with it... You can do something like this:

```
        Vector3 scale, traslation;
        Quaternion rotation;

        myModel.Bones[4].Transform.Decompose( out scale, out rotation, out traslation );

        rotation *= Quaternion.CreateFromAxisAngle( Vector3.UnitY, ( float ) gameTime.TotalGameTime.TotalSeconds / (2 * MathHelper.Pi) / 8 );

        myModel.Bones[4].Transform = Matrix.CreateScale( scale ) * Matrix.CreateFromQuaternion( rotation ) * Matrix.CreateTranslation( traslation );

```
> 0 votes

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


# Question
Title: Where do I place XNA content pipeline references?
I am relatively new to XNA, and have started to delve into the use of the content pipeline. I have already figured out that tricky issue of adding a game library containing classes for any type of .xml file I want to read.

Here's the issue. I am trying to handle the reading of all XML content through use of an XMLHandler object that uses the intermediate deserializer. Any time reading of such data is required, the appropriate method within this object would be called. So, as a simple example, something like this would occur when a character levels:

```
public Spell LevelUp(int levelAchived)
{
    XMLHandler.FindSkillsForLevel(levelAchived);
}

```

This method would then read the proper .xml file, sending back the spell for the character to learn. However, the `XMLHandler` is having issues even being created. I cannot get it to use the `using namespace` of `Microsoft.Xna.Framework.Content.Pipeline`. I get an error on my using statement in the `XMLHandler` class:

```
using Microsoft.Xna.Framework.Content.Pipeline.Serialization.Intermediate;

```

The error is a typical reference error:

> Type or namespace name "'Pipeline' does not exist in the namespace 'Microsoft.Xna.Framework.Content' (are you missing an assembly reference?)"

I THINK this is because this namespace is already referenced in my game's content. I would really have no issue placing this object within my game's content (since that is ALL it deals with anyways), but the Content project does not seem capable of holding anything but content files.

In summary, I need to use the Intermediate Deserializer in my main project's logic, but, as far as I can make out, I can't safely reference the associated namespace for it outside of the game's content. I'm not a terribly well-versed programmer, so I may be just missing some big detail I've never learned here. How can I make this object accessible for all projects within the solution? I will gladly post more information if needed!

# Answer
Content pipeline can not be referenced from project using .NET Framework 4 Client Profile. You can change this in (Right click on project -\> Properties -\> Application -\> Target framework).

But can't you use normal content pipeline to build your XMLs and then load them as normal content?
> 1 votes

# Answer
The MSDN page for that namespace notes that it is only accessible from projects targeting Windows platforms. Double check that you are working with a standard XNA Game project and not an Xbox 360 one.

To check the target framework, select your project from the Solution Explorer then press **F4** to access the **Properties** panel for that project. **XNA Framework Platform** should be listed as one of the properties and should have the value **Windows** as Xbox 360 and Windows Phone 7 projects do not have complete access to the content pipeline.

**EDIT**

In what project is this troublemaker 'using' statement, a Content, Content Pipeline Extension or standard Game project? References to the Content.Pipeline assembly are only available to the first two. Whichever it is, select that project in the solution explorer, right click "References" then "Add reference..." Under the .NET tab, scroll down to the very bottom and, if it is an applicable project, you should see the Microsoft.Xna.Framework.Content.Pipeline assemblies.
> 0 votes

# Answer
You can't realistically ask people to download the entire XNA development framework just to run your game. And I'm pretty sure Microsoft won't allow you to just distribute the Content Pipeline DLLs willy nilly.

What you do to accomplish your goals depends on your answers to a couple of questions:

1. Do you need to be able to serialize data to XML at runtime, or is this purely so you can make a level editor and plug a bunch of data into XML files that are to be read by your game at runtime (your XMLHandler.FindSkillsForLevel suggests that the latter is your case).
2. Is it necessary for you to stream any data from a server that is meant to be deserialized, or can you assume it's all packaged in the game?
3. If you do indeed need runtime serialization, is it absolutely required that you use XML? You may find it easier to map your data to JSON, which is easier to read and a little faster to emit and parse for many cases.

If you are only using the XML for defining your game data (and making level editors for you to use, you should split your solution up into 4 projects: Engine, Game, Editor, Content. Don't think of Engine as this fancy thing, it's just the common code shared between Game and Editor (see my answer here). Game contains game-specific code, all the presentation and special handling of level data and end-user UI. Engine can contain most of the code (AI, level logic, etc.) since you'll probably want to use the editor project as a catch-all for editing all sorts of data related to your game.

If you intend to stream XNB files to a desktop game, you may have to experiment with instantiating a ContentManager object using the constructor that takes a string. I haven't done this, so I don't know what the limitations are.

If you require runtime serialization/deserialization for playing your game outside of typical content pipeline use, you must handle your own serialization instead of relying on the content pipeline. The reflection API isn't too hard to use and understand, it's just tedious. And if you have to serialize your own stuff anyway, you may want to consider looking into JSON. It usually maps more intuitively to classes. A couple libraries to check out would be LitJSON for something lightweight, and JSON.Net for something more featureful and robust.
> 0 votes

---
Tags: xna, xml, pipeline
---


# Question
Title: Routes on a sphere surface - Find geodesic?
I'm working with some friends on a browser based game where people can move on a 2D map. It's been almost 7 years and still people play this game so we are thinking of a way to give them something new. Since then the game map was a limited plane and people could move from (0, 0) to (MAX\_X, MAX\_Y) in quantized X and Y increments (just imagine it as a big chessboard).
We believe it's time to give it another dimension so, just a couple of weeks ago, we began to wonder how the game could look with other mappings:

* Unlimited plane with continous movement: this could be a step forward but still i'm not convinced.
* Toroidal World (continous or quantized movement): sincerely I worked with torus before but this time I want something more...
* Spherical world with continous movement: this would be great!

**What we want** Users browsers are given a list of coordinates like (latitude, longitude) for each object on the spherical surface map; browsers must then show this in user's screen rendering them inside a web element (canvas maybe? this is not a problem). When people click on the plane we convert the (mouseX, mouseY) to (lat, lng) and send it to the server which has to compute a route between current user's position to the clicked point.

**What we have** We began writing a Java library with many useful maths to work with Rotation Matrices, Quaternions, Euler Angles, Translations, etc. We put it all together and created a program that generates sphere points, renders them and show them to the user inside a JPanel. We managed to catch clicks and translate them to spherical coords and to provide some other useful features like view rotation, scale, translation etc. What we have now is like a little (very little indeed) engine that simulates client and server interaction. Client side shows points on the screen and catches other interactions, server side renders the view and does other calculus like interpolating the route between current position and clicked point.

**Where is the problem?** Obviously we want to have the **shortest path** to **interpolate between the two route points**. We use quaternions to interpolate between two points on the surface of the sphere and this seemed to work fine until i noticed that we weren't getting the shortest path on the sphere surface:

We though the problem was that the route is calculated as the sum of two rotations about X and Y axis. So we changed the way we calculate the destination quaternion: We get the third angle (the first is latitude, the second is longitude, the third is the rotation about the vector which points toward our current position) which we called orientation. Now that we have the "orientation" angle we rotate Z axis and then use the result vector as the rotation axis for the destination quaternion (you can see the rotation axis in grey):

What we got is the correct route (you can see it lays on a great circle), but we get to this ONLY if the starting route point is at latitude, longitude (0, 0) which means the starting vector is (sphereRadius, 0, 0). With the previous version (image 1) we don't get a good result even when startin point is 0, 0, so i think we're moving towards a solution, but the procedure we follow to get this route is a little "strange" maybe?

In the following image you get a view of the problem we get when starting point is not (0, 0), as you can see starting point is not the (sphereRadius, 0, 0) vector, and as you can see the destination point (which is correctly drawn!) is not on the route.

The magenta point (the one which lays on the route) is the route's ending point rotated about the center of the sphere of (-startLatitude, 0, -startLongitude). This means that if i calculate a rotation matrix and apply it to every point on the route maybe i'll get the real route, but I start to think that there's a better way to do this.

Maybe I should try to get the plane through the center of the sphere and the route points, intersect it with the sphere and get the geodesic? **But how?**

Sorry for being way too verbose and maybe for incorrect English but this thing is blowing my mind!

**EDIT:** Code below works just fine! Thanks to everybody:

```
public void setRouteStart(double srcLat, double srcLng, double destLat, destLng) {
    //all angles are in radians
    u = Choords.sphericalToNormalized3D(srcLat, srcLng);
    v = Choords.sphericalToNormalized3D(destLat, destLng);
    double cos = u.dotProduct(v);
    angle = Math.acos(cos);
    if (Math.abs(cos) >= 0.999999) {
        u = new V3D(Math.cos(srcLat), -Math.sin(srcLng), 0);
    } else {
        v.subtract(u.scale(cos));
        v.normalize();
    }
}

public static V3D sphericalToNormalized3D( double radLat, double radLng) {
    //angles in radians
    V3D p = new V3D();
    double cosLat = Math.cos(radLat);
    p.x = cosLat*Math.cos(radLng);
    p.y = cosLat*Math.sin(radLng);
    p.z = Math.sin(radLat);
    return p;
}

public void setRouteDest(double lat, double lng) {
    EulerAngles tmp = new AngoliEulero(
       Math.toRadians(lat), 0, -Math.toRadians(lng));
    qtEnd.setInertialToObject(tmp);
    //do other stuff like drawing dest point...
}

public V3D interpolate(double totalTime, double t) {
    double _t = angle * t/totalTime;
    double cosA = Math.cos(_t);
    double sinA = Math.sin(_t);
    V3D pR = u.scale(cosA);
    pR.sum(
       v.scale(sinA)
    );
    return pR;
}

```

# Answer
Your problem is purely two-dimensional, in the plane formed by the sphere centre and your source and destination points. Using quaternions is actually making things more complex, because in addition to a position on a 3D sphere, a quaternion encodes an orientation.

You may already have something to interpolate on a circle, but just in case, here is some code that should work.

```
V3D u, v;
double angle;

public V3D geographicTo3D(double lat, double long)
{
    return V3D(sin(Math.toRadians(long)) * cos(Math.toRadians(lat)),
               cos(Math.toRadians(long)) * cos(Math.toRadians(lat)),
               sin(Math.toRadians(lat)));
}

public V3D setSourceAndDest(double srcLat, double srcLong,
                            double dstLat, double dstLong)
{
    u = geographicTo3D(srcLat, srcLong);
    V3D tmp = geographicTo3D(dstLat, dstLong);
    angle = acos(dot(u, tmp));
    /* If there are an infinite number of routes, choose
     * one arbitrarily. */
    if (abs(dot(u, tmp)) >= 0.999999)
        v = V3D(cos(srcLong), -sin(srcLong), 0);
    else
        v = normalize(tmp - dot(u, tmp) * u);
}

public V3D interpolate(double totalTime, double t)
{
    double a = t / totalTime * angle;
    return cos(a) * u + sin(a) * v;
}

```
> 5 votes

# Answer
Make sure both quaternions are on the same hemisphere on the hypersphere. If their dot-product is less than 0, then they are not. In that case negate one of them (negate each of the its numbers), so they are on the same hemisphere and will give you the shortest path. Pseudocode:

```
quaternion from, to;

// is "from" and "to" on the same hemisphere=
if(dot(from, to) < 0.0)
{
    // put "from" to the other hemisphere, so its on the same as "to"
    from.x = -from.x;
    from.y = -from.y;
    from.z = -from.z;
    from.w = -from.w;
}

// now simply slerp them

```

My answer here explains in detail what negating each term of the quaternion does and why it is still the same orientation, just on the other side of the hypersphere.

---

**EDIT** the interpolation function should look like this:

```
public V3D interpolate(double totalTime, double t) {
    double _t = t/totalTime;
    Quaternion tmp;
    if(dot(qtStart, qtEnd) < 0.0)
    {
        tmp.x = -qtEnd.x;
        tmp.y = -qtEnd.y;
        tmp.z = -qtEnd.z;
        tmp.w = -qtEnd.w;
    }
    else
    {
        tmp = qtEnd;
    }
    Quaternion q = Quaternion.Slerp(qtStart, tmp, _t);
    RotationMatrix.inertialQuatToIObject(q);
    V3D p = matInt.inertialToObject(V3D.Xaxis.scale(sphereRadius));
    //other stuff, like drawing point ...
    return p;
}

```
> 3 votes

# Answer
Since you want a `V3D` back from your interpolator, the simplest approach is to skip the quaternions entirely. Convert the start and end points to `V3D` and slerp between them.

If you insist on using quaternions then the quaternion representing the rotation from `P` to `Q` has direction `P x Q` and `w` of `P . Q`.
> 0 votes

---
Tags: 3d, rotation, maps, quaternion, world-design
---


# Question
Title: Where would I find C# flocking tutorials?
Been looking for a while now and finding it difficult to find a good tutorial...

Where would I find a good tutorial on how to implement flocking in a C# XNA game? Something easy to understand .. for beginners!

Cheers!

# Answer
> 1 votes
MSDN offer a great project sample for flocking. Here is the link Hopefully, that will get your started

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


title: Artificial Neural Networks

text:
# Question
Title: Artificial Neural Networks
I have an Artificial Networks which needs to recognize 130 different types of moves encoded in terms of 1s and 0s. Therefore the number of outputs I used is 8 so that all my patterns could be distinguished. However, by using 8 outputs, the different types of patterns possible is 256, leaving me with 126 different types of patterns useless.

Do these extra 126 different patterns ruin my ANN's ability? Is there a better way not to have these unused holes?

# Answer
Irrelevant output values will make it harder to train, yes.

The output does not necessarily have to be 1s and 0s. In fact, if you're just treating each output as a binary bit then it's probably a bad idea because each bit of the output is a fairly arbitrary value compared to the semantics you're trying to train. For example, the difference between move 127 and 128 may be minor but the output is almost entirely different. You'll be asking a lot of your hidden layers to make sense of these arbitrary divisions. (Gray code may be a better answer in such cases, but don't quote me on that.)

To adequately address this - or in fact, most AI questions - it is important to know more about the representation of the data. Of the 130 outputs, is there any correlation between them? If so, is there a way to represent them that makes more sense and which makes similar numbers have similar semantics? (eg. You wouldn't represent a position on a chessboard as a number from 1-64, you'd use 2 numbers from 1-8.) If you can find an output method that more closely relates to your data's semantics and has less in the way of possibly redundant outputs, then training will be more successful.
> 3 votes

---
Tags: ai
---


# Question
Title: Prevent collisions between mobs/npcs/units piloted by computer AI : How to avoid mobile obstacles?
Lets says we have character `a` starting at point `A` and character `b` starting at point `B`. character `a` is headed to point `B` and character `b` is headed to point `A`. There are several simple ways to find the path(I will be using Dijkstra). The question is, how do I take preventative action in the code to stop the two from colliding with one another?

case2: Characters `a` and `b` start from the same point in different times. Character `b` starts later and is the faster of the two. How do I make character `b` walk around character `a` without going through it?

case3:Lets say we have `m` such characters in each side and there is sufficient room to pass through without the characters overlapping with one another. How do I stop the two groups of characters from "walking on top of one another" and allow them pass around one another in a natural organic way.

A correct answer would be any algorithm, that given the path to the destination and a list of mobile objects that block the path, finds an alternative path or stops without stopping all units when there is sufficient room to traverse.

# Answer
> 1 votes
The simple answer is steering. The steering is used to steer towards the waypoints of your found path. Further, it's used to avoid obstacles including other characters. Implementing a look ahead with a variable steering vector will help make it a smooth movement. Basically, the closer the object the larger the perpendicular vector to avoid the obstacle:

In addition to steering, the character being passed should slow down, or the character passing should speed up for a short time. This will give the passing a more natural look and make it take less time.

Characters should default to one side or the other if they're heading almost directly at each other. This way if both characters are about to head on collide they'll turn away from each other.

A more advanced step would be to implement flow field pathfinding. More information about how it works can be found in this question. A video demonstration of it can be found here.

# Answer
> 1 votes
If you're using Dijkstra, then every time your actor reaches a node on the graph, you could verify that the path he's taking is still valid. If it's not, you can then use Dijkstra's to find a valid path again assuming you've updated the graph to reflect the obstacles. Alternatively when the obstacle is detected you can attempt to steer around it to reach the next waypoint. Steering upon hitting an obstacle is discussed a bit here.

---
Tags: algorithm, path-finding, mobile
---


title: "Unclutter" units in RTS game

text:
# Question
Title: "Unclutter" units in RTS game
For intentional reasons, certain units in the game I'm currently programming don't have any collision detection and response among each other.

This enables them to clutter right on top of each other. This is a wanted behavior, since there will be situations in the game when the player does want them to stack like that.

However, I want to make the process of uncluttering them easy for the player, so that they just have to press a hotkey or click some button on the screen and have the units disperse just enough so it's easy to select a group of them with the mouse (if they stand on top of each other one mouseclick selects all units).

How could I do this without running a brute force N^2 nearest neighbor search on all units?

# Answer
> 8 votes
Create a grid with enough spaces for all the units you want to "unclutter", have them each choose the nearest *unclaimed* grid space. Then have them move towards their respective grid space.

This will move them into something like a formation, where the player can easily select an individual unit.

That's an O(N) operation with pretty good results.

---
Tags: 2d, rts
---


# Question
Title: Procedurally generated 2d terrain for side scroller on Sega Genesis hardware?
I'm working on the Sega Genesis that has a 8mhz Motorola 68000 CPU.

Any ideas on how to generate fast and decent 2d tile terrain for a side scroller in real time? The game would generate new columns or rows depending on the direction the player is scrolling in. The generation would have to be deterministic. The same seed value would generate the same terrain.

The style of game would be a platformer like Sonic The Hedgehog. Maximum size would be around 1024 x 1024 tiles, but smaller could also work.

A column or row doesn't have to be calculated every frame, just when a new one is needed. If the player moves 1 pixels a frame, then a new column is only needed every 8 frames.

I'm looking for algorithms that would satisfy the memory and CPU constraints of the hardware.

# Answer
> 1 votes
I would limit this to a SMB(1) style game where the Y-axis is bound throughout the game. Instead of randomizing everything, I would stick to building mini-stages in advance and then determining which of them will be next using a hash-like function that takes the seed and the current 'x' value to pick the next area. I suspect that because of the computational abilities of the Mega Drive (~7 MHZ), it would be unwise to further burden it with sophisticated level generation when it should be sufficiently occupied with collision detection, enemy behavior and other game mechanics.

If this experiment works out, you could layer mini-stages on top one another, breaking the y-axis bound and getting something similar to what your described.

---
Tags: 2d, procedural-generation, c, side-scroller
---


# Question
Title: What data structure to use for the map in Pac-Man?
I am trying to make a Pac-Man game in C# using GDI+. I have done some basic work and I have previously replicated games like Copter-It and Minesweeper, but I am confused about how I can implement the map in Pac-Man. I mean: which data structure to use, so I can use it for moving AI controlled objects and check collisions with walls.

I thought of a 2D array of `int`s but that didn't make sense to me. Looking for some help.

# Answer
> 3 votes
Why not use a simple 2d array of chars, and use some text editor as your level editor?

Something like this:

# Answer
> 1 votes
Perhaps a graph can be used. I imagine the vertices would represent intersections or corners in the maze and the edges would be the connections between the intersections.
Each edge should probably contain a length, and if the graph is used for rendering as well, each edge would have to contain a vertical/horizontal value too, i guess.

---
Tags: c#, collision-detection, maps, data-structure
---


# Question
Title: How can I make a C++ countdown timer that doesn't freeze user input?
I'm planning to use the `Sleep()` function to implement a countdown timer. But this freezes the input of the user at the same time. Thus I wanted to ask if it is possible to have the countdown still running in realtime, whether they're typing or not; or in other words not freeze everything.

Is it possible? If so, how?

Example : Pop Quiz with Timer

# Answer
> 1 votes
If I understand your question correctly, you should be able to do this by having a few variables:

```
float countdownDuration = 1.0f;
float cooldown = coutdownDuration;

```

Each frame, you subtract `deltaTime`, or the time that has passed since the last frame, from `cooldown`. When `cooldown` reaches `0` or below, your countdown timer has 'ticked' down, and you can reset `cooldown` to `countdownDuration` minus the value below `0` that `cooldown` has reached. In this particular case, by the way I initialized the variables above, each tick will be one second.

In this way, you do not have to `sleep` the main thread and will still check for input every frame.

---
Tags: c++, input, timer
---


# Question
Title: Storing large array of tiles, but allowing easy access to data
I've been thinking about this for a while. I have a 2D tile bases platformer in XNA with a large array of tile data, I've been running into memory problems with large maps. (I will add chunks soon!)

Currently, Each tile contains an `Item` along with other properties like how its rotated, if it has forground / background, etc.

An `Item` is static and has properties like the name, tooltip, type of item, how much light it emits, the collision it does to player, etc. Examples:

```
public class Item
{
    public static List<Item> Items;

    public Collision blockCollisionType;
    public string nameOfItem;
    public bool someOtherVariable,etc,etc

    public static Item Air
    public static Item Stone;
    public static Item Dirt;
    static Item()
    {
       Items = new List<Item>()
       {
            (Stone = new Item()
            {
                nameOfItem = "Stone",
                blockCollisionType = Collision.Solid,
            }),
            (Air = new Item()
            {
                nameOfItem = "Air",
                blockCollisionType = Collision.Passable,
            }),

        };
    }
}

```

Would be an Item, The array of Tiles would contain a `Tile` for each point,

```
public class Tile
{
     public Item item; //What type it is
     public bool onBackground;
     public int someOtherVariables,etc,etc
}

```

Now, Most would probably use an enum, or a form of ID to identify blocks. Well my system is really nice just to find out about an item. I can simply do `tiles[x,y].item.Name` To get the name for example. I realized my Item property of the tile is over 1000 Bytes! Wow! What I'm looking for is a way to use an ID (`Int` or `byte` depending on how many items) instead of an `Item` but still have a method for retreiving data about the type of item a tile contains.

# Answer
> 0 votes
Item is a class, the Tile class only stores a reference to it.

Your items are static instanced, so you have a few, and the tiles are sharing them... so the name is shared by all the tiles, is the same name for all tiles that are linked to the same Item.

You know that you have to make chunks and split the map... go for it.

---
Tags: xna, c#, 2d, platformer, memory
---


# Question
Title: How should I organize my matrices in a 3D game engine?
I'm working with a group of people from around the world to create a game engine (and hopefully a game with it) within the next upcoming years. My first task is to write a camera class for the engine to use in order to add cameras to the scene, with position and follow points.

The problem I have is with using matrices for transformations in the class, should I keep matrices separate to each class? Such as have the model matrix in the model class, camera matrix in the camera class, or have all matrices placed in one class/chuck? I could see pros and cons for each method, but I wanted to hear some input form a more professional standpoint.

# Answer
> 6 votes
The camera class should contain & maintain the view and projection matrices.

Each entity (as opposed to each model, several entities can share a model) will contain (or more commonly generate) it's own world matrix.

# Answer
> 2 votes
Have a `matrix` class that can be utilized by all the other classes. There's no point in duplicating code. You want to keep that to a minimum.

If you're talking about having the actual initialized matrices stored in a central location, don't do that. Keep the instantiated matrices with the classes that use them. This would get very confusing to have them separate. Try to stick to object oriented design. For example the camera is an object that owns its own data values, like its matrices.

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


# Question
Title: Updates for IOS AppStore Multiplayer Game
I am developing a multiplayer game for the web, android and ios. For the web and android i can instantly push out new versions of my game because they support executing remotly loaded code. But with IOS i need to wait for an Apple approval taking about 10 days. I want to push updates more then weekly.

What if my server code changes so the client MUST update? Run an old version of the server code just for IOS? How do other multiplayer devs handle this ?

# Answer
> 2 votes
If a change is introduced that is means you need to issue a client update as an "emergency bug fix", then you can apply to Apple for an expediated review. And in any case, Apple do seem a bit quicker at approving apps if the update is essentially a bug fix.

However, I would really recommend that you make your server protocol backwards-compatible. Part of the whole ethos of the way App Store updates work on iOS is that it is really up to the user when they update. Even if you manage to get an app accepted that forces the user to update, I think this would seem highly unusual to the player.

---
Tags: ios, appstore, patching
---


# Question
Title: OpenGl / C++ and some strange light problem on half board
I have some problem with lights in my opengl "game". I have board with is square (-50,50), (50, 50), (50, -50), (-50,-50) x and z since y doesn't matter at all.

I tried to make something like flashlight its moving and rotating with camera (me), but when I try to rotate more than 90 degree to left or right it just gives different light:

(left is spotlight, right point light) There is also a point light in the middle, but its working strange(not like a point light) it shines only on half of the board from (-50,50), (50, 50), (50, 0), (-50,-0) x and y:

Link to my repository where you can find game exe in download and full code in source: https://bitbucket.org/mlodziaszka/my\_game

All more fragments of light:

```
float gl_amb[] = { 0.2f, 0.2f, 0.2f, 1.0f };
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, gl_amb);

glEnable(GL_LIGHTING); // Wlaczenie oswietlenia
glShadeModel(GL_SMOOTH); // Wybor techniki cieniowania
glEnable(GL_LIGHT0); // Wlaczenie 0-go zrodla swiatla
glEnable(GL_LIGHT1);

```

Cubes parametri:

```
float m1_amb[] = { 1.0f, 0.0f, 0.0f, 1.0f };
float m1_dif[] = { 1.0f, 0.0f, 0.0f, 1.0f };
float m1_spe[] = { 1.0f, 0.0f, 0.0f, 1.0f };
glMaterialfv(GL_FRONT, GL_AMBIENT, m1_amb);
glMaterialfv(GL_FRONT, GL_DIFFUSE, m1_dif);
glMaterialfv(GL_FRONT, GL_SPECULAR, m1_spe);
glMaterialf(GL_FRONT, GL_SHININESS, 50.0f);

```

Texture parametri:

```
float m1_amb[] = { 1.0f, 1.0f, 1.0f, 1.0f };
float m1_dif[] = { 1.0f, 1.0f, 1.0f, 1.0f };
float m1_spe[] = { 1.0f, 1.0f, 1.0f, 1.0f };
glMaterialfv(GL_FRONT, GL_AMBIENT, m1_amb);
glMaterialfv(GL_FRONT, GL_DIFFUSE, m1_dif);
glMaterialfv(GL_FRONT, GL_SPECULAR, m1_spe);
glMaterialf(GL_FRONT, GL_SHININESS, 0.0f);
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );

```

Light0: //with some magic isn't working anyway

```
float l0_amb[] = { 0.2f, 0.2f, 0.2f, 1.0f };
float l0_dif[] = { 1.0f, 1.0f, 1.0f, 1.0f };
float l0_spe[] = { 1.0f, 1.0f, 1.0f, 1.0f };

float l0_pos[] = { g_Camera.m_vPosition.x, g_Camera.m_vPosition.y,        g_Camera.m_vPosition.z, 1.0f };

float temp = 0.0f, temp2 = 0.0f, temp3 = 0.0f;

if(g_Camera.m_vView.z < g_Camera.m_vPosition.z)
{
    temp = g_Camera.m_vView.x - g_Camera.m_vPosition.x;
temp2 = g_Camera.m_vView.z - g_Camera.m_vPosition.z;
 }
else
{
temp = g_Camera.m_vView.x - g_Camera.m_vPosition.x;
temp2 = g_Camera.m_vView.z - g_Camera.m_vPosition.z;
}

float l0_pos1[] = {temp, 0.0f, temp2};
//float l0_pos1[] = {-1.0f, 0.0f, -1.0f};

glLightfv(GL_LIGHT0, GL_AMBIENT, l0_amb);
glLightfv(GL_LIGHT0, GL_DIFFUSE, l0_dif);
glLightfv(GL_LIGHT0, GL_SPECULAR, l0_spe);
glLightfv(GL_LIGHT0, GL_POSITION, l0_pos);

glLightf (GL_LIGHT0, GL_SPOT_CUTOFF, 15.0f);
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, l0_pos1);

```

Light1:

```
float l1_amb[] = { 0.2f, 0.2f, 0.2f, 1.0f };
float l1_dif[] = { 1.0f, 1.0f, 1.0f, 1.0f };
float l1_spe[] = { 1.0f, 1.0f, 1.0f, 1.0f };
float l1_pos[] = { 0.0f, 0.0f, 0.0f, 1.0f };
glLightfv(GL_LIGHT1, GL_AMBIENT, l1_amb);
glLightfv(GL_LIGHT1, GL_DIFFUSE, l1_dif);
glLightfv(GL_LIGHT1, GL_SPECULAR, l1_spe);
glLightfv(GL_LIGHT1, GL_POSITION, l1_pos);

```

I know that way I made this very old, but for now i want to keep this like that.

I would be realty grateful if someone can tell me what is wrong with my lights xD

full code: link up ^^

# Answer
> 3 votes
You haven't set normals on the vertices of the meshes you're drawing. You'll need normals, for lighting to be calculated.

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


# Question
Title: How can I solve this SAT direct corner intersection edge case?
I have a working SAT implementation, but I am running into a problem where direct collisions at a corner do not work for tiled surfaces. That is, it clips on the surface when going in a certain direction because it gets hung up on one of the tiles, and so, for example, if I walk across a floor while holding both down and left, the player will stop when meeting the next shape because the player will be colliding with the right side rather than with the top of the floor tile.

This illustration shows what I mean:

The top block will translate *right* first and then up.

I have checked here and here which are helpful, but this does not address what I should do in a situation where I *don't* have a tile-based world. My usage of the term "tile" before isn't really accurate since what I'm doing here is manually placing square obstacles next to each other, not assigning them spots on a grid.

What can I do to fix this?

# Answer
After tinkering with this for a while, I've found a solution that works. Or rather, it works to solve this particular problem, and I don't know yet what other issues it causes. But at least for now it works perfectly.

To solve it I just iterated through each of the possible collisions, checked the translation against the others, and kept the vector with the greatest magnitude, or the successful resolution that resulted in the greatest distance.

```
private void ResolvePlayer()
{
    List<Vector2> possibleResolutions = new List<Vector2>();

    foreach (CollidableRectangle obstacle in obstacles)
    {
        if (obstacle.IsColliding(player.Bounds) && obstacle.GetMTV() != Vector2.Zero)
        {
            //player.Move(-obstacle.GetMTV());
            possibleResolutions.Add(-obstacle.GetMTV());
        }
    }

    Vector2 finalOffset = Vector2.Zero;
    float maxDistance = 0;
    foreach (Vector2 offset in possibleResolutions)
    {
        float thisDistance = Vector2.Distance(player.Position, player.Position + offset);
        if (thisDistance > maxDistance)
        {
            maxDistance = thisDistance;
            finalOffset = offset;
        }
    }

    player.Move(finalOffset);
}

```

This is what my resolution method looks like at the moment. I had a recursive call to handle jittering in corners but that gave me a stack overflow when testing against certain rotations, so for now I'm just resolving it twice. Fixing that bug shouldn't be too hard, though, and it can be possible to make it into one elegant method that handles everything.
> 0 votes

# Answer
OK, I've found an answer to my own question, however I'm not sure that it's the *best* answer. Basically the problem was in the order that the axes were checked which resulted in the hangup happening in some directions but not others.

So to resolve this I simply do the check one more time in reverse order. I was previously doing this recursively but not reversing the list. Here's the "working" code:

```
private void ResolvePlayer()
{
    List<ICollidable> reverse = obstacles;
    reverse.Reverse();

    foreach (CollidableRectangle obstacle in obstacles)
    {
        if (obstacle.ResolveCollision(player.Bounds) && obstacle.GetMTV() != Vector2.Zero)
        {
            player.Move(-obstacle.GetMTV());
            //ResolvePlayer();
            break;
        }
    }

    foreach (CollidableRectangle obstacle in reverse)
    {
        if (obstacle.ResolveCollision(player.Bounds) && obstacle.GetMTV() != Vector2.Zero)
        {
            player.Move(-obstacle.GetMTV());
            //ResolvePlayer();
            break;
        }
    }
}

```
> 1 votes

---
Tags: xna, c#, separating-axis-theorem
---


title: Gigantic 2d maps?

text:
# Question
Title: Gigantic 2d maps?
I've been thinking about a game idea for a week or two and the last few hours I was thinking of some technical stuff and came up with that the map would need to be 360,000x360,000 pixels in size. To me it sounds insane, but I've never done much in depth game development so I'm not sure if its reasonable or not to have a map that large.

Basicly my question is, would it work to have a map that large in a 2D game?

# Answer
> 10 votes
**First about the technical aspects:**

The vast majority of 2d game engines are tile-based. That means that the game world is built from a pool of small sub-images of a fixed size. Here is an example. Note that many of the 32x32 tiles in this image are identical to others:

(Image source: http://www.codeproject.com/Articles/106884/Implementing-Auto-tiling-Functionality-in-a-Tile-M)

When your tilesize is 36x36, you could represent your game world with ((360,000 / 36) * (360,000 / 36)) 100 million tiles. The only data you need per tile is the id number of the tile image which is used for it. So when you have between 256 and 65536 different tiles, you will need two bytes per tile, so your world data is less than 200MB. When you have about 1000 different tiles, and each tile is 36 x 36 x 4 bytes, you have about 5 MB of graphic data.

Considering that modern PCs have gigabytes of RAM (assuming that's your target platform), you don't even have a reason yet to not load the whole map into RAM... yet. A good reason to do that will very likely come up in a later development stage.

**Now about the gameplay aspects**

Assuming that you have a 2d engine with a fixed zoom factor, it's usually not a good idea to have such large maps in a 2d game.

When you have a 3d game, the strong point of a large game world is the ability to present great vistas to the player. Send him to a peak of a mountain, and have him stare at the huge stretches of land beneath him. Then make him realize that everything he sees is playable content, and it blows his mind.

Being able to see into the distance is also a great navigation help. When you see a tower a mile away, you know you just have to keep moving in that direction, and eventually you will reach it.

But that doesn't work in a 2d engine. The player only sees a small window of the game world which is at most 1920x1080 pixels in size on a consumer-grade monitor. He can't make out any landmarks in the distance. That makes large 2d maps a lot harder to navigate. For that reason, large open spaces should be avoided in 2d maps. Every possible map location should have a well-defined set of paths the player can follow and must be recognizable and unique, otherwise it gets too easy for the player to get lost.

As a result from this, the map design in a 2d game must be pretty compact and made with a lot of care about detail. The larger the map, the harder it gets to keep up the quality.

# Answer
> 10 votes
360,000 * 360,000 == 129,600,000,000 pixels in total.

Let's be generous, and assume that you're only using a 16-color palette, so each pixel can specify its color using only four bits.

129,600,000,000 pixels * 4 bits per pixel == 518,400,000,000 bits. Divide by 8 bits per byte gives us 64,800,000,000 bytes. Divide by 1024 bytes per kilobyte (or kibibyte, if you go in for that sort of naming), and then by 1024 kilobytes per megabyte (mebibyte), and you get approximately 61,798 megabytes. Let's round that off and call it an even 60 gigabytes (gibibytes).

Of course, if you want a 256-color palette (eight bits per pixel), then you'd need double that amount of space to store it. And if you want a modern "full-color" palette, then you need at least 24 bits per pixel, so that's about 360 gigabytes. Just for your map image.

Of course, if you have ways to compress your image (say, if you have large regions of a single color so you can run-length encode it, for example, or if you're happy to work with lossy compression), then you could bring that down a good deal. But if you're starting from 360 gigabytes of data, I doubt that this sort of compression is going to bring it down to a size which many people would be eager to download.

Most 2D games work by defining larger "tile" images, and placing those tiles together to form a map, rather than using a single large image.

# Answer
> 0 votes
It would work but much better is to create a data structure that holds coordinates of all needed tiles on your screen as a branches of binary or r\b tree, for example.
So you need a structure that holds the indexes of those tiles and their positions on the screen, when you'll call a render function of your game, you'll read data from that structure and form a raster image using tiles and that data. (So you will know where to place your tiles).
For a ready-made containers, that can hold map data, you can look at the different realizations of Map containers, like ones in the STL library for C++ or java.util.Collections if in Java, and other languages as well.

---
Tags: 2d, maps
---


# Question
Title: What would be an easy extensible technique to store game data?
I'm looking for a technique for storing my game resources - levels, object (effects,world info), items (price,effects,...), NPC (visual info, behavior), everything except graphics/audio stuff. I've seen *lua* used for Awesome WM configuration. protobuf looks good, but it seems to be designed for network communication. I've tried to write my own parser, but as the project grows it's more and more harder to manage it and catch all the bugs.

My requiremets:

* stability
* easy extension of data without need to convert older versions to newer
* not much coding
* not XML!

# Answer
A less over-engineered alternative to XML is JSON (Javascript Object Notations). Parser and serializer libraries are available for most common programming languages.

When you have a lot of assets and you plan to manage them primarily with selfmade tools, then using an SQL database would be a good idea. SQLite would be good for this use-case, because it can be integrated in an application as a library and doesn't need a server. But unfortunately it's hard to come up with a database schema which is upward-compatible.
> 3 votes

# Answer
I'd recommend either string maps or basic serialization.

* *string maps* \- all data is converted to strings and stored into dictionaries. Pros: changes won't necessarily break old save files, can inspect with a text editor, can use JSON and similar formats to store the data. Cons: might be a bit slower with huge data sets.
* *basic serialization* \- byte buffer, read/write functions for elements of each type (\[unsigned|signed\] int\[8|16|32|64\], float\[32|64\], byte buffers). Pros: lightning-fast. Cons: changes will most likely break old save files, not even a hex editor would help much here.

Both methods will require writing manual load/save functions for each serialized object. All the usual rules of inheritance and composition apply here (can reuse functions to serialize included objects) so it won't seem that hard in the end.

To me, it would most certainly beat writing obscure wrappers and configuration files for a complex system. But I suppose you've got to try both things to see what you like more.
> 0 votes

---
Tags: storage
---


title: Zooming into Mouse Position

text:
# Question
Title: Zooming into Mouse Position
I'm trying to implement my camera class for a simulation. But I cant figure out how to zoom into my world based on the mouse position. I mean the object under the mouse cursor should remain at the same screen position. My zooming looks like this:

```
VOID ZoomIn(D3DXMATRIX& WorldMatrix, FLOAT const& MouseX, FLOAT const& MouseY) {
    this->Position.z = this->Position.z * 0.9f;
    D3DXMatrixLookAtLH(&this->ViewMatrix, &this->Position, &this->Target, &this->UpDirection);
}

```

I passed the world matrix to the function because I had the idea to move my drawing origin according to the mouse position. But I cant find out how to calculate the offset in to move my drawing origin. Anyone got an idea how to calculate this?

Thanks in advance.

# Answer
> 1 votes
**SOLVED**

Ok I solved my problem. Here is the code if anyone is interested:

```
VOID CAMERA2D::ZoomIn(FLOAT const& MouseX, FLOAT const& MouseY) {
    // Get the setting of the current view port.
    D3DVIEWPORT9 ViewPort;
    this->Direct3DDevice->GetViewport(&ViewPort);

    // Convert the screen coordinates of the mouse to world space coordinates.
    D3DXVECTOR3 VectorOne;
    D3DXVECTOR3 VectorTwo;

    D3DXVec3Unproject(&VectorOne, &D3DXVECTOR3(MouseX, MouseY, 0.0f), &ViewPort,
        &this->ProjectionMatrix, &this->ViewMatrix, &WorldMatrix);
    D3DXVec3Unproject(&VectorTwo, &D3DXVECTOR3(MouseX, MouseY, 1.0f), &ViewPort,
        &this->ProjectionMatrix, &this->ViewMatrix, &WorldMatrix);

    // Calculate the resulting vector components.
    float WorldZ = 0.0f;
    float WorldX = ((WorldZ - VectorOne.z) * (VectorTwo.x - VectorOne.x)) /
        (VectorTwo.z - VectorOne.z) + VectorOne.x;
    float WorldY = ((WorldZ - VectorOne.z) * (VectorTwo.y - VectorOne.y)) /
        (VectorTwo.z - VectorOne.z) + VectorOne.y;

    // Move the camera into the screen.
    this->Position.z = this->Position.z * 0.9f;
    D3DXMatrixLookAtLH(&this->ViewMatrix, &this->Position, &this->Target, &this->UpDirection);

    // Calculate the world space vector again based on the new view matrix,
    D3DXVec3Unproject(&VectorOne, &D3DXVECTOR3(MouseX, MouseY, 0.0f), &ViewPort,
        &this->ProjectionMatrix, &this->ViewMatrix, &WorldMatrix);
    D3DXVec3Unproject(&VectorTwo, &D3DXVECTOR3(MouseX, MouseY, 1.0f), &ViewPort,
        &this->ProjectionMatrix, &this->ViewMatrix, &WorldMatrix);

    // Calculate the resulting vector components.
    float WorldZ2 = 0.0f;
    float WorldX2 = ((WorldZ2 - VectorOne.z) * (VectorTwo.x - VectorOne.x)) /
        (VectorTwo.z - VectorOne.z) + VectorOne.x;
    float WorldY2 = ((WorldZ2 - VectorOne.z) * (VectorTwo.y - VectorOne.y)) /
        (VectorTwo.z - VectorOne.z) + VectorOne.y;

    // Create a temporary translation matrix for calculating the origin offset.
    D3DXMATRIX TranslationMatrix;
    D3DXMatrixIdentity(&TranslationMatrix);

    // Calculate the origin offset.
    D3DXMatrixTranslation(&TranslationMatrix, WorldX2 - WorldX, WorldY2 - WorldY, 0.0f);

    // At the offset to the cameras world matrix.
    this->WorldMatrix = this->WorldMatrix * TranslationMatrix;
}

```

Maybe someone has even a better solution than mine.

---
Tags: c++, directx
---


title: Arrive steering behavior

text:
# Question
Title: Arrive steering behavior
I bought a book called *Programming game AI by example* and I am trying to implement the arrive steering behavior. The problem I am having is that my objects oscillate around the target position; after oscillating less and less for awhile they finally come to a stop at the target position. Does anyone have any idea why this oscillating behavior occur? Since the examples accompanying the book are written in C++ I had to rewrite the code into C#. Below is the relevant parts of the steering behavior:

```
private enum Deceleration
{
    Fast = 1,
    Normal = 2,
    Slow = 3
}

public MovingEntity Entity { get; private set; }

public Vector2 SteeringForce { get; private set; }

public Vector2 Target { get; set; }

public Vector2 Calculate()
{
    SteeringForce.Zero();

    SteeringForce = SumForces();

    SteeringForce.Truncate(Entity.MaxForce);

    return SteeringForce;
}

private Vector2 SumForces()
{
    Vector2 force = new Vector2();

    if (Activated(BehaviorTypes.Arrive))
    {
        force += Arrive(Target, Deceleration.Slow);

        if (!AccumulateForce(force))
            return SteeringForce;
    }

    return SteeringForce;
}

private Vector2 Arrive(Vector2 target, Deceleration deceleration)
{
    Vector2 toTarget = target - Entity.Position;

    double distance = toTarget.Length();

    if (distance > 0)
    {
        //because Deceleration is enumerated as an int, this value is required
        //to provide fine tweaking of the deceleration..
        double decelerationTweaker = 0.3;

        double speed = distance / ((double)deceleration * decelerationTweaker);

        speed = Math.Min(speed, Entity.MaxSpeed);

        Vector2 desiredVelocity = toTarget * speed / distance;

        return desiredVelocity - Entity.Velocity;
    }

    return new Vector2();
}

private bool AccumulateForce(Vector2 forceToAdd)
{
    double magnitudeRemaining = Entity.MaxForce - SteeringForce.Length();

    if (magnitudeRemaining <= 0)
        return false;

    double magnitudeToAdd = forceToAdd.Length();

    if (magnitudeToAdd > magnitudeRemaining)
        magnitudeToAdd = magnitudeRemaining;

    SteeringForce += Vector2.NormalizeRet(forceToAdd) * magnitudeToAdd;

    return true;
}

```

This is the update method of my objects:

```
public void Update(double deltaTime)
{
    Vector2 steeringForce = Steering.Calculate();

    Vector2 acceleration = steeringForce / Mass;

    Velocity = Velocity + acceleration * deltaTime;

    Velocity.Truncate(MaxSpeed);

    Position = Position + Velocity * deltaTime;
}

```

If you want to see the problem with your own eyes you can download a minimal example here.

Thanks in advance.

# Answer
I'm sure your steering code is fine, however there are some values you need to change to get it to work properly. There are a few factors to steering that need to be accounted for to successfully stop the first time.

If your mass is too high or your acceleration is too low the object will oscillate. The object won't have the power it needs to stop its self before overshooting the target. This can be solved by increasing the acceleration available for stopping, or by increasing the stopping distance.

---

Well, looking at your steering code, it is a little strange. There's no point in your arrival where the acceleration will point away from the target. That's fairly critical for slowing down. You can easily test this by manually taking some values and plugging them into your code, calculating the values by hand as you step through your code. You'll find that currently your code just decreases your acceleration more and more as you approach the target. You need to go negative at some point to stop your entity.

You need to define a distance at which to start slowing down. You'd likely want to decide this distance based on the entity's max speed and max acceleration. The distance it starts slowing down is the maximum distance required to stop with full acceleration away from the target. See the pseudo code below to get an idea of how to implement steering like that. The difference is that the below only uses speed, not acceleration, so you'll need to update it accordingly:

```
target_offset = target - position
distance = length (target_offset)
ramped_speed = max_speed * (distance / slowing_distance)
clipped_speed = minimum (ramped_speed, max_speed)
desired_velocity = (clipped_speed / distance) * target_offset
steering = desired_velocity - velocity

```

You can find more excellent steering examples here. Including the arrival behavior. Finally, this paper has more information on how to actually implement these algorithms.
> 3 votes

# Answer
Your arrive behaviour keeps on triggering unless the moving entity has exactly hit the target. This is fine if your time delta and/or your velocity are so small that the position delta in `Update` won't overshoot your target, unfortunately, this is not the case at first. This results in the oscillation you see before the moving entity finally stops moving.

To fix this, add an arrival threshold parameter, and change `Arrive` like this:

```
// Tweak this threshold parameter to prevent oscillation.
double arrivalThreshold = 0.1;
double distance = toTarget.Length();

    if (distance > arrivalThreshold)

```
> 0 votes

---
Tags: c#, steering-behaviors
---


# Question
Title: In HLSL pixel shader , why is SV_POSITION different to other semantics?
In my HLSL pixel shader, SV\_POSITION seems to have different values to any other semantic I use. I don't understand why this is. Can you please explain it?

For example, I am using a triangle with the following coordinates:

```
(0.0f, 0.5f)
(0.5f, -0.5f)
(-0.5f, -0.5f)

```

The w and z values are 0 and 1, respectively.

This is the pixel shader.

```
struct VS_IN
{
    float4 pos : POSITION;
};

struct PS_IN
{
    float4 pos : SV_POSITION;
    float4 k : LOLIMASEMANTIC;
};

PS_IN VS( VS_IN input )
{
    PS_IN output = (PS_IN)0;
    output.pos = input.pos;
    output.k = input.pos;
    return output;
}

float4 PS( PS_IN input ) : SV_Target
{
    // screenshot 1
    return input.pos;

    // screenshot 2
    return input.k;
}

technique10 Render
{
    pass P0
    {
        SetGeometryShader( 0 );
        SetVertexShader( CompileShader( vs_4_0, VS() ) );
        SetPixelShader( CompileShader( ps_4_0, PS() ) );
    }
}

```

When I use the first statement (result is first screenshot), the one that uses the `SV_POSITION` semantic, the result is completely unexpected and is yellow, whereas using any other semantic will produce the expected result. Why is this?

# Answer
SV\_Position gives you the position in screen coordinates, not in a \[0,1\] range though but basically in pixel coordinates. The range will correspond to the `D3D11_VIEWPORT` you set, possibly something along the lines of:

```
D3D11_VIEWPORT viewport = {0};
viewport.Width = 1280;
viewport.Height = 720;

```

So in order to get a \[0,1\] range again, for the colors, you could do:

```
return float4(input.pos.r/1280, input.pos.g/720, 0, 1);

```
> 14 votes

---
Tags: directx, hlsl, fragment-shader
---


title: XNA- Scale only parent

text:
# Question
Title: XNA- Scale only parent
I was wondering, is it possible to `Scale(Vector3)` a `ModelBone` without scaling its children. Lets say I got a **Bone A** at position `1,0,3`. And one of its children **Bone B** is at position `1,0,5` (he is touching **Bone A**). Could I scale **Bone A** along Z axis without scaling **Bone B**, but keep **Bone B** position and rotation so that he is still touching **Bone A**.

Thanks in advance

# Answer
If you scale the parent bone by factor A, scale the child by 1/A and it will keep the size.

Ej. if parent scale is multiplied by 2 you should mulptiply child scale by 1/2 = 0.5f
> 2 votes

# Answer
When you call `CopyAbsoluteBoneTransformsTo()`, it goes through the model's bone collection and applies parent SRTs to the children SRTs and places the results in a Matrix\[\]. So if after calling that, you then go into the resulting Matrix\[\], you could pick out BoneA's transform, apply some Z scale to it and it will not affect its children.

Notice you go into the resulting Matrix\[\] to do this, not the underlying model Bone collection. If you did this to BoneA's matrix in the underlying model bone collection, it would then apply that z scale to the children on the next frame when you again call `CopyAbsoluteBoneTransformsTo()` and it doesn't sound like you want that.
> 1 votes

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


# Question
Title: How to disguise a serverside mob as another?
I've been working a Minecraft sever mod and i want to be able to add a new entity to the server, but then make the server send the packets to the client, imitating another mob, for example..

Lets say say i have EntityPlayerNPC.class, what i want to do is have all of the packets that get sent to the client look like they are from that of another player which is on the player, therefore allowing me to add custom NPC's... Thinking about the theory i'm sure this can be done.

I've tried looking around for where the packets are being sent from and whatnot, can anyone think up a solution?

edit:

i tried adding a new constructor to the Packet20NamedEntitySpawn class like so:

```
public Packet20NamedEntitySpawn(String username, EntityLiving e){
       this.entityId = 0;
       this.name = username;
       this.xPosition = MathHelper.floor_double(e.posX * 32.0D);
       this.yPosition = MathHelper.floor_double(e.posY * 32.0D);
       this.zPosition = MathHelper.floor_double(e.posZ * 32.0D);
       this.rotation = (byte)((int)(e.rotationYaw * 256.0F / 360.0F));
       this.pitch = (byte)((int)(e.rotationPitch * 256.0F / 360.0F));
       this.metadata = e.getDataWatcher();
}

```

unfortunatley, that didn't work :(

# Answer
Im not too familiar with minecraft coding, but Id say take a look at other mods that have done similar things, such as adding extra animals and that, or also look at the code for existing NPCs such as the Pigmen Villagers and such.

Is what your wanting to do is make an NPC clone of the player with all of their fields like username and such?
> 0 votes

---
Tags: java, minecraft-modding
---