title: Movement in RPG

text:
# Question
Title: Movement in RPG
I want to make an RPG game in which I move tile by tile. So when I hit up, the tile row that I am on decreases by one for example. Also, it's supposed to be a slow movement so that I can see the change in tile, i.e. I can see my sprite move from tile to tile. Currently, with the code I have, when I hit a direction on my keyboard, I move several blocks within seconds and by the time I release the button I have already gotten a nullPointerException error because I have left the map. How can I slow down the movement?

# Answer
> 1 votes
This is the code I used.

```
// These numbers represent the different directions in movement.
private final int STILL = 0, LEFT = 1, UP = 2, RIGHT = 3, DOWN = 4,
        STOP = 5;
// The current direction of movement of the player.
public int movement = 0;

// The move method, like any other player class.
private void move() {
// The keyboard input class works like this:
// If the up keyboard button is pressed, player.movement = player.UP,
// if right is pressed, player.movement = player.RIGHT, etc.
// and if no key is pressed, player.movement = player.STILL;

    if (movement == UP) {
        moveUp();
    }
    if (movement == LEFT) {
        moveLeft();
    }
    ....
    if (movement == STILL) {
        setDx(0);
        setDy(0);
    }
}

private void moveLeft() {
// Because this intends to work on a tile grid, this method checks if
// the tile to the left of the player is occupied.
    if (!tileIsOccupied(LEFT)) {
// The player can press a key every 200 ms. Sets the time moved to this
// point in time. If a player attempts to move before those 200 ms are
// over, no movement will occur.
        setTimeMoved(getCurrentTime());
// This tile is essential the tile to the left of the player.
        Tile tile = getGrid().getTiles()[getTileRow() - 1][getTileColumn()];
// If the xpos of the player is greater than the xpos of the tile, keep moving
// left.
        if (getXpos() > tile.getXpos()) {
            setDx(-1);
            setXpos(getXpos() + getDx());
        }
// If the xpos of the player is less than or equal to that of the tile,
// set the player's position equal to the tiles. In other words, when
// the player has moved to the tile.
// Set this current tile to equal the player's tile, and movement is reset to
// still.
        if (getXpos() <= tile.getXpos()) {
            setTileColumn(tile.getTileColumn());
            setTileRow(tile.getTileRow());
            setXpos(tile.getXpos());
            setMovement(STILL);
        }
    } else
        movement = STILL;
}

// It's essential that the update function be called on a loop. Otherwise, the
// player will not move.
public void update() {
    move();
}

```

# Answer
> 3 votes
This sounds like an input problem. You need to check your inputs to see if you've already processed a key press. Keep the state of the keyboard from the last frame and check it when you're on your new frame. Only move if the key was **not** being pressed in the previous frame. Similar to responding to the event of pressing the key instead of the key being down.

For example:

```
currentKeys.fillFromKeyboard();

if(currentKeys.isDown(Key.UP) && !previousKeys.isDown(Key.Up))
    character.moveUp();

...

previousKeys.fill(currentKeys);

```

That will apply one move to each key press. If you wanted to have a held key repeat movements you can do something like:

```
int repeatDelay = 500; //time in MS that we'll delay before repeating a key

if(currentKeys.isDown(Key.UP) && (getCurrentGameTime() - timeMoved) >= repeatDelay) {
    character.moveUp();
    timeMoved = getCurrentGameTime();
}

```

Additionally, you should probably be checking bounds when moving. So check that your character's position + movement amount is withing world bounds, before moving.

# Answer
> 1 votes
Just a note on structure - you are calling repaint(); in your update(); function, but it would probably be better if you didn't chain the calls like that, but rather have those in your main game loop, ie.:

```
while(true) {
   update();
   render();  // if you use double-buffering, which you probably should
   repaint();
}

```

---
Tags: java, movement, rpg
---


# Question
Title: Architecture for html5 multiplayer game?
Hello I want to write a HTML5 multiplayer game in which there are rooms with two players answering a series of questions with 3 possible answers, 10sec/question, which are being downloaded from a server. It will have some ratings and so on.

I want to make it as scalable as possible. I wonder what technologies to use to accomplish that. HTML5, CSS3 and JavaScript obviously. But what about the server-side? I have been researching and found that Socket.IO + Node.js + mongoDB would do the job but after doing some more research it maybe not.

Can you suggest me some kind of architecture for doing this game? Free technologies, if possible. Or what to read and from where to start in order to understand how to do it.

Thanx in advance!

P.S. I have an experience with HTML5, CSS3, JavaScript, C#, ASP.NET MVC and relational db's.

# Answer
> 1 votes
I hate to be "that guy", but check out BrowserQuest.

https://github.com/mozilla/BrowserQuest/ http://browserquest.mozilla.org/

Check out how Mozilla does, you might be able to learn a thing or two!

# Answer
> 1 votes
Also see GRITS: PvP Gaming with HTML5

Video: http://www.youtube.com/watch?v=Prkyd5n0P7k

Source: http://code.google.com/p/gritsgame/

---
Tags: architecture, multiplayer, html5
---


title: Basic 3D Collision detection in XNA 4.0

text:
# Question
Title: Basic 3D Collision detection in XNA 4.0
I have a problem with detecting collision between 2 models using BoundingSpheres in XNA 4.0. The code I'm using i very simple:

```
private bool IsCollision(Model model1, Matrix world1, Model model2, Matrix world2)
{
for (int meshIndex1 = 0; meshIndex1 < model1.Meshes.Count; meshIndex1++)
{
    BoundingSphere sphere1 = model1.Meshes[meshIndex1].BoundingSphere;
    sphere1 = sphere1.Transform(world1);

    for (int meshIndex2 = 0; meshIndex2 < model2.Meshes.Count; meshIndex2++)
    {
        BoundingSphere sphere2 = model2.Meshes[meshIndex2].BoundingSphere;
        sphere2 = sphere2.Transform(world2);

        if (sphere1.Intersects(sphere2))
            return true;
    }
}
return false;

```

}

The problem I'm getting is that when I call this method from the Update method, the program behaves as if this method always returns true value (which of course is not correct). The code for calling is very simple (although this is only the test code):

```
 if (IsCollision(model1, worldModel1, model2, worldModel2))
                {
                    Window.Title = "Intersects";
                }

```

What is causing this?

The way Im drawing the scene is to load the number of elements and their coordinates from a file like this (it is called from Update method):

```
OpenFileDialog Otvaranje = new OpenFileDialog();
        if (ks.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.L))
            {
                this.GraphicsDevice.Clear(Color.CornflowerBlue);
                Otvaranje.ShowDialog();
                try
                {
                    using (StreamReader sr = new StreamReader(Otvaranje.FileName))
                    {
                        String linija;
                        while ((linija = sr.ReadLine()) != null)
                        {
                            red = linija.Split(',');
                            model = red[0];
                            x = red[1];
                            y = red[2];
                            z = red[3];
                            elementi.Add(Convert.ToInt32(model));
                            podatci.Add(new Vector3(Convert.ToSingle(x), Convert.ToSingle(y), Convert.ToSinglez)));
                            sfere.Add(new BoundingSphere(new Vector3(Convert.ToSingle(x), Convert.ToSingle(y), Convert.ToSingle(z)), 1f));

                        }
                    }

```

And then in the Update() method I had the following code (this was my first attempt):

```
if(sfere.Count != 0){
for(int i = 1; i<sfere.Count; i++)
{
 if(sfere[0].Intersects(sfere[i])) Window.Title = "Intersects";
}
}

```

This code never returned that collision is true because the bounding boxes are moving when the box moves, and I don't know why. The code that moves the box is this:

```
if (Microsoft.Xna.Framework.Input.ButtonState.Pressed == Mouse.GetState().LeftButton)
                {
                    worldKutija = Matrix.CreateTranslation(new Vector3(0.01f, 0f, 0f)) * worldKutija;
                }

```

So if the model is set to be the box it is drawn into the worldKutija, and all other models are drawn into world matrix so they would not move with the box model. So why are their BoundingSpheres moving? After this started happening I tried the code I posted in the original question, and got the problems I was talking about

# Answer
You are forgetting to take the the bone transforms into account. Also It's not clear what is inside the World1 and World2 matrices, are you sure you move the boundingsphere's around and not just have them all be centered at (0,0)? Could you print out their origin's?

Anyway some code:

```
//Creates one bounding sphere for a model
BoundingSphere CreateBoundingSphereForModel(Model model, Matrix worldMatrix)
{
    Matrix[] boneTransforms = new Matrix[this.model.Bones.Count];
    this.model.CopyAbsoluteBoneTransformsTo(boneTransforms);

    BoundingSphere boundingSphere = new BoundingSphere();
    BoundingSphere meshSphere;

    for (int i = 0; i < model.Meshes.Count; i++)
    {
        meshSphere = model.Meshes[i].BoundingSphere.Transform(boneTransforms[i]);
        boundingSphere = BoundingSphere.CreateMerged(boundingSphere, meshSphere);
    }
    return boundingSphere.Transform(worldMatrix);
}

//Check intersection between two models
bool IsCollision(Model model1, Matrix world1, Model model2, Matrix world2)
{
    BoundingSphere bs1 = CreateBoundingSphereForModel(model1, world1);
    BoundingSphere bs2 = CreateBoundingSphereForModel(model2, world2);

    if(bs1.Intersects(bs2))
        return true;

    return false;
}

```

Note that it would be better to create a new class that holds the model, the matrix and caches the bounding spheres to improve performance.

Edit: it seems from the comments above that the problem is that the matrices are wrong, just putting both sphere's at (0,0,0). So instead to solve that use below code to create a proper world matrix:

```
Matrix world = Matrix.CreateTranslation(object1Position) * Matrix.CreateScale(object1Scale);
// We don't need rotation since it doesn't matter how the sphere is rotatated ;)

```

Here object1Position is a Vector3 that you probably also use the draw the model at a certain position in the world.
> 3 votes

# Answer
I think your BoundingSpheres might not be in the proper positions.

```
private bool IsCollision(Model model1, Matrix world1, Model model2, Matrix world2)
{
for (int meshIndex1 = 0; meshIndex1 < model1.Meshes.Count; meshIndex1++)
{
BoundingSphere sphere1 = model1.Meshes[meshIndex1].BoundingSphere;
sphere1 = sphere1.Transform(world1);
//EDIT:
sphere1.Center += obj1.Position;
//

for (int meshIndex2 = 0; meshIndex2 < model2.Meshes.Count; meshIndex2++)
{
    BoundingSphere sphere2 = model2.Meshes[meshIndex2].BoundingSphere;
    sphere2 = sphere2.Transform(world2);
    //EDIT:
    sphere2.Center += obj2.Position;
    //

    if (sphere1.Intersects(sphere2))
        return true;
}
}
return false;

```

Implying that obj1 and obj2 are the world objects, and their corresponding models are model1 and model2. I have no idea what you have in those world1 and world2 matrices though... maybe you could show us some more code.
> 1 votes

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


# Question
Title: 3D Vector "End Point" Calculation for procedural Vector Graphics
Alright, So I need some help with some Vector Math.

I've developing some game Engines that have Procedural Fractal Generation for Some Graphics, such as using Lindenmayer Systems for generating Trees and Plants. L-Systems, are drawn by using Turtle Graphics, which is a form of Vector graphics.

I first created a system to draw in 2D Graphics, which works perfectly fine. But now I want to make a 3D equivalent, and I’ve run into an issue.

For my 2D Version, I created a Method for quickly determining the “End Point” of a Vector-like movement. Given a starting point (X, Y), a direction (between 0 and 360 degrees), and a distance, the end point is calculated by these formulas:

```
newX = startX + distance * Sin((PI * direction) / 180)

newY = startY + distance * Cos((PI * direction) / 180)

```

Now I need something Similarly Equivalent for performing this Calculation in 3D, But I haven’t been able to Google anything that could show me how to do this.

I'm flexible enough to get whatever required information is needed for this method calculation, in any reasonable form (Vector3, Quaternion, ect).

To summarize: Given a starting point/vector position in 3D space (X, Y, Z), a Direction in 3D space (Vector3, Quaternion, ect), and a Distance, I need to find the “End Point” in 3D Space.

Thank you for your time and help.

# Answer
An equivalent in 3D is quite simple, without using quaternions or anything of the sort (since it's really not the case - you need to specify a convention, not to perform computations). Hence, spherical coordinates:

```
 NewPoint.X = Start.X + distance * Cos(longitudeAngle) * Cos(latitudeAngle);
 NewPoint.Y = Start.Y + distance * Sin(longitudeAngle) * Cos(latitudeAngle);
 NewPoint.Z = Start.Z + distance * Sin(latitudeAngle);

```

where `longitudeAngle` is between (-180 and 180) degrees or (-pi, pi) rads and the `latitudeAngle` is between (-90,90) degrees or (-pi/2, pi/2) rads.

Alternatively, take a look at some astronomical coordinate systems. They provide a fairly more similar approach to what you did to construct your fractal shapes by supplying a so called local direction via an angle (improperly called a direction, let's call it a heading or something...). This way, you can do some interesting things with L-Systems (even generate some weird random ones via any production rule you set..).
> 1 votes

# Answer
```
Vector3 endPoint = position + distance * direction;

```

Implying that direction is a normalized 3D vector.
> 0 votes

---
Tags: mathematics, graphics, xna-4.0, vector, procedural-generation
---


# Question
Title: Does anybody know of any resources to achieve this particular "2.5D" isometric engine effect?
I understand this is a little vague, but I was hoping somebody might be able to describe a high-level workflow or link to a resource to be able to achieve a specific isometric "2.5D" tile engine effect. I fell in love with http://www.youtube.com/watch?v=-Q6ISVaM5Ww this engine. Especially with the lighting and the shaders!

He has a brief description of how he achieved what he did, but I could really use a brief flow of where you would start, what you would read up on and learn and the logical order to implement these things.

A few specific questions:

1) Is there a heightmap on the ground texture that lets the light reflect brighter on certain parts of it?

2) "..using a special material which calculates the world-space normal vectors of every pixel.." - is this some "magic" special material he has created himself, or can you hazard a guess at what he means?

3) with relation to the above quote - what does he mean by 'world-space normal vectors of every pixel'?

4) I'm guessing I'm being a little bit optimistic when I ask if there's any 'all-in-one' tutorial out there? :)

# Answer
> 0 votes
You simply need to have normal-map texture for anything you want to be lit dynamically. You can do that also with height-map but usually it is done with normal-map.

Here is an example how to do it for XNA: http://www.soolstyle.com/2010/06/29/2d-lightning-continued/

---
Tags: xna, shaders, isometric, heightmap, 2.5d
---


title: Lua or C++ in Cococ2d-x

text:
# Question
Title: Lua or C++ in Cococ2d-x
I am going to use Cocos2d-x to make a game for Android and ios, but my question is, do I use the Lua integration or only c++, I see Lua useful here because the compilation thing.

Or do I use only Lua for the configuration, save data and things in runtime?

I don´t know if using Lua for the whole game is the right thing :/

Can anyone help me with this question and why use it or not?

Thanks

# Answer
> 1 votes
You would use both. Lua can be used for:

* Exporting code to a mobile device
* Making a UI (You should try first make an addon for a MMORPG if you want to get a better idea how you can use Lua)

C++ is the core code of the videogame, so maybe you can program a game without Lua but it might help you to do better UI for your games

---
Tags: android, ios, cross-platform, lua, cocos2d-x
---


# Question
Title: How to plot hex tiles with different length sides?
I'm trying to create a basic grid of hex tiles. I found some code:

```
s=h/Math.cos(30*Math.PI/180)/2;
tile._x=x*s*1.5;
tile._y=y*h+(x%2)*h/2;

```

That does just that, but I think it's setup for hexes that have same length sides. However, my hex has different length sides. Its width is 140 and its height is 80. How would I change that code to accomodate this?

# Answer
Try this: if `w,h` are the width and height of your tile image, replace the first two lines of that code sample with just

```
tile._x = x * 0.75 * w;

```

The factor of 0.75 comes from the geometry of hexagons, where the spacing between adjacent columns is 3/4 of the diameter of a single hexagon. (It's the same origin as the 1.5 in the original code, where `s` was the side length of the hexagon, which is half its diameter.)
> 5 votes

---
Tags: hexagonal-grid
---


title: Lighting effects with 2D sprites

text:
# Question
Title: Lighting effects with 2D sprites
I would like to know how to best achieve lighting effects with 2D.

I guess the only way is to make sprites of the area to be lit in specific colors? Say I have a streetlamp, and around this place sprites to make it appear lit?

Is there a better way?

Edit: Found a good screenshot of what I'm looking for: http://www.saltgames.com/wp-content/uploads/2009/11/multipleLights.png

# Answer
> 1 votes
If you are using Canvas, you may use a radial gradient:

1. create a radial gradient from a light color on the center, to a transparent color on the end see createRadialGradient
2. use `globalCompositeOperation="lighter"` is the trick to add color components and make the light effect
3. draw the created gradient on top of the image you want to light

---

This is basically one of the tip I used to implement illuminated.js, in case you want to see some real usage and code.

# Answer
> 1 votes
Step 1: Set the background to black.

Step 2: Calculate how much light is the tile getting (how far is it from light source(s), etc.).

Step 3: Lower the opacity of the image by a value according to what you calculated in Step 2.

Source: https://stackoverflow.com/questions/2644399/brightening-an-image-using-styles-or-javascript

---
Tags: javascript, html5
---


# Question
Title: How to get xy coordinates along a given path
Say i have two points (x,y), (0,0) and (10,10). Now i wan´t to get coordinates along the line by stepping through values of x and y. I thought i solved it with the following functions:

```
 fy = startY + (x - startX) * ((destY-startY)/(destX-startX));
 fx = (y + startY) / ((destY-startY)/(destX-startX)) + startX;

```

taken from http://en.wikipedia.org/wiki/Linear\_interpolation

However, it seems that im getting a problem when destX and startX is the same value, so you get division by zero.

Is there a better way of getting coordinates along a line when knowing the start and endpoint of the line?

# Answer
represent the distance you travel as a number between 0 and 1. The problem with your code is that you don't have any notion of "how far am I between the two endpoints."

```
function lerp(start, dest, dist) {
    var x = start.x * (1 - dist) + dest.x * dist;
    var y = start.y * (1 - dist) + dest.y * dist;
    return [x,y];
}

lerp(start, dest, 0) -> start
lerp(start, dest, 0.5) -> halfway in between
lerp(start, dest, 1) -> dest

```
> 4 votes

---
Tags: game-mechanics, coordinates, linear-algebra
---


title: C++ game architecture

text:
# Question
Title: C++ game architecture
I'm trying to make a game, but I'm not sure of the best way to set up the main loop and classes. For *really* small games, I could put *everything* in the `main()` loop, including event handling, collision checking, etc. However, for large games, that's seems like a highly inefficient way to get things done. The architecture I want is kind like the way the Minecraft coders did it (I quote Minecraft code because I've seen the source code when downloading MCP).

They have objects entity classes `EntityCow` and `EntityChicken` and they have methods like `onDeath()`, `onLivingUpdate()`; and item classes like `ItemSword` have methods like `onItemUse()`. I've never seen these methods get called directly, but apparently, they get stored in a class called `DataWatcher`, which, I think "watches" all the data (as the name implies) and calls the appropriate methods in the objects.

Is that how most games do it? If so, how is the `DataWatcher` class implemented? Any help or alternate suggestions is *really* appreciated.

# Answer
> 1 votes
There are a few different ways to implement a game. For entity classes as described above, they probably have a main loop running all of them. For example, if you have EntityCow and EntityChicken, they may be created/instantiated within a main class and are drawing their own animations and recording their own damage. Here is some pseudocode:

```
main()
{
    EntityCow cow = new EntityCow();
}

class EntityCow
{
    public EntityCow(){} //your constructor

private cow methods:
    onDeath() //cow dies - make invisible

    update() //should be constantly updated per game tick
    {
        //draw cow animations
        //check cow damage
        //call onDeath() if cow damaged enough
    }
}

```

In many cases of multiplayer and online games, the damage/animation data (etc.) is sent to a server that verifies the data. This helps to make sure that players cannot manipulate data on their own machines and also so each player is able to see the game exactly the same on their own machines. So to answer your question, most larger games have an overall game loop running individual classes that either update themselves or are updated by a server by sending their data to the server so the data can be verified and then used. It is possible with MC's DataWatcher class that it is acting as their server in this case to verify all incoming data and is taking control over each Entity's actions . That means that the above private cow methods are actually public to the DataWatcher class which then calls them. In that case, update would not call OnDeath(), DataWatcher would.

---
Tags: c++, architecture
---


title: How should I do AABB::contains?

text:
# Question
Title: How should I do AABB::contains?
Should an AABB "contain" a point when the point is:

* Exclusive: Only exactly inside the aabb
* Inclusive: Inside the aabb or exactly on the sides
* Almost: Inside the aabb or a little bit outside of the sides

# Answer
> 5 votes
Ultimately, it comes down to what you commonly check. To bring up a 4th alternative, I've used half-open intervals, so points belong to exactly one bounding box at a tight boundary.

```
bb.minX <= point.x < bb.maxX

```

# Answer
> 1 votes
Inclusive, because when setting up containing boxes, if an object passes over the line it will be checked twice where your other methods would, and could easily not check a collision, or check too many and do a lot of extra work.

---
Tags: aabb
---


title: xna orbit camera troubles

text:
# Question
Title: xna orbit camera troubles
I have a `Model` named `cube` to which I load in `LoadContent()`: `cube = Content.Load<Model>("untitled");`.

In the `Draw` Method I call `DrawModel`:

```
    private void DrawModel(Model m, Matrix world)
    {
        foreach (ModelMesh mesh in m.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.EnableDefaultLighting();
                effect.View = camera.View;
                effect.Projection = camera.Projection;
                effect.World = world;
            }
            mesh.Draw();
        }
    }

```

`camera` is of the `Camera` type, a class I've setup. Right now it is instantiated in the initialization section with the graphics aspect ratio and the translation (world) vector of the model, and the Draw loop calls the `camera.UpdateCamera();` before drawing the models.

```
class Camera
{
    #region Fields
    private Matrix view; // View Matrix for Camera
    private Matrix projection; // Projection Matrix for Camera
    private Vector3 position; // Position of Camera
    private Vector3 target; // Point camera is "aimed" at
    private float aspectRatio; //Aspect Ratio for projection
    private float speed; //Speed of camera
    private Vector3 camup = Vector3.Up;
    #endregion

    #region Accessors
    /// <summary>
    /// View Matrix of the Camera -- Read Only
    /// </summary>
    public Matrix View
    {
        get { return view; }
    }
    /// <summary>
    /// Projection Matrix of the Camera -- Read Only
    /// </summary>
    public Matrix Projection
    {
        get { return projection; }
    }
    #endregion

    /// <summary>
    /// Creates a new Camera.
    /// </summary>
    /// <param name="AspectRatio">Aspect Ratio to use for the projection.</param>
    /// <param name="Position">Target coord to aim camera at.</param>
    public Camera(float AspectRatio, Vector3 Target)
    {
        target = Target;
        aspectRatio = AspectRatio;
        ResetCamera();
    }

    private void Rotate(Vector3 Axis, float Amount)
    {
        position = Vector3.Transform(position - target, Matrix.CreateFromAxisAngle(Axis, Amount)) + target;
    }

    /// <summary>
    /// Resets Default Values of the Camera
    /// </summary>
    private void ResetCamera()
    {
        speed = 0.05f;
        position = target + new Vector3(0f, 20f, 20f);
        projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, 0.5f, 100f);
        CalculateViewMatrix();
    }

    /// <summary>
    /// Updates the Camera.  Should be first thing done in Draw loop
    /// </summary>
    public void UpdateCamera()
    {
        Rotate(Vector3.Right, speed);
        CalculateViewMatrix();
    }

    /// <summary>
    /// Calculates the View Matrix for the camera
    /// </summary>
    private void CalculateViewMatrix()
    {
        view = Matrix.CreateLookAt(position,target, camup);
    }

```

I'm trying to create the camera so that it can orbit the center of the model. For a test I am calling `Rotate(Vector3.Right, speed);` but it rotates almost right but gets to a point where it "flips." If I rotate along a different axis `Rotate(Vector3.Up, speed);` everything seems OK in that direction.

So I guess, can someone tell me what I'm not accounting for in the above code I wrote? Or point me to an example of an orbiting camera that can be fixed on an arbitrary point?

# Answer
> 1 votes
It appears you might be rotating around Vector3.Right to give your camera the freedom to change pitch.

As you pitch(orbit) around your object, getting to the very top, if you then pitch some more, your camera would be upside down as it follows the orbit path. But since you have Vector3.Up (camup) as the 3rd param in your createlookat method, it is being told to always stay right side up relative to Vector3.Up. So instead of allowing the camera to proceed upside down, it flips it over as it continues the orbit path.

Most games limit the max pitch to somewhere between +89 & -89 degrees to keep the flip from happening.

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


# Question
Title: How can I locate empty space next to polygon regions?
Let's say I have the following area in a top-down map:

The circle is the player, the black square is an obstacle, and the grey polygons with red borders are walk-able areas that will be used as a navigation mesh for enemies. Obstacles and grey polygons are always convex.

The grey regions were defined using an algorithm when the world was generated at runtime.

Notice the little white column. I need to figure out where any empty space like this is, if at all, after the algorithm builds the grey regions, so that I can fill the space with another region.

Basically what I'm hoping for is an algorithm that can detect empty space next to a polygon.

# Answer
> 1 votes
Do you specifically need rectangles for walkable areas?

I ask as you could reverse this - take a 2D grid of boolean values and mark all grid squares as walkable (true) and then check all points on your polygons to find the grid squares they inhabit, and mark those squares as unwalkable (false).

This will produce a 'mask' of walkable areas, but the mask will be as grainy as your grid. If you're wanting a pixel-perfect solution then you may want to investigate kd-trees.

---
Tags: algorithm, path-finding, navmesh
---


# Question
Title: Java Slick2d - Mouse picking how to take into account camera
When I move it it obviously changes the viewport so my mouse picking is off.

My camera is just a float x and y and I use g.translate(-cam.cameraX+400, -cam.cameraY+300); to translate the graphics. I have the numbers hard coded just for testing purposes.

How would I take into account the camera so my mouse picking works correctly.

```
double mousetileX = Math.floor((double)mouseX/tiles.tileWidth);
    double mousetileY = Math.floor((double)mouseY/tiles.tileHeight);

    double playertileX = Math.floor(playerX/tiles.tileWidth);
    double playertileY = Math.floor(playerY/tiles.tileHeight);

    double lengthX = Math.abs((float)playertileX - mousetileX);
    double lengthY = Math.abs((float)playertileY - mousetileY);
    double distance = Math.sqrt((lengthX*lengthX)+(lengthY*lengthY));

    if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON) && distance < 4) {
        if(tiles.map[(int)mousetileX][(int)mousetileY] == 1) {
            tiles.map[(int)mousetileX][(int)mousetileY] = 0;
        }
    }

```

That is my mouse picking code

# Answer
To get back to world-space, you need to reverse your translation from graphics. Think of graphics-space as U and V instead of X and Y:

```
u = x + (400 - cameraX); // X coord in graphics space
v = y + (300 - cameraY); // Y coord in graphics space

```

So to reverse this, rearrange for x and y:

```
x = u - (400 - cameraX);
y = v - (300 - cameraY);

```
> 1 votes

---
Tags: java, camera, mouse, picking
---


# Question
Title: Deferred rendering with both Clockwise and CounterClockwise culling
I have a deferred rendering system that works well with objects that appear solid and drawn using CounterClockwise culling.

I have a problem with Clockwise culled objects that are supposed to represent hollow that display their inside faces only.

The image below shows a CounterClockwise culled object (left) Clockwise culled object (right).

Deferred Rendering CullMode http://rhysperkins.com/XNA/CullModeDeferred.png

The Clockwise culled object faces display what would be displayed on the CounterClockwise face. How can I get the lighting to light the inner faces for Clockwise culled objects and continue lighting the outer CounterClockwise faces as normal?

My lighting method is below

```
    private void DeferredLighting(GameTime gameTime)
    {
        // Set the render target for the lights
        game.GraphicsDevice.SetRenderTarget(lightMap);

        // Clear the render target to (0, 0, 0, 0)
        game.GraphicsDevice.Clear(Color.Transparent);

        // Set the render states
        game.GraphicsDevice.BlendState = BlendState.Additive;
        game.GraphicsDevice.DepthStencilState = DepthStencilState.None;
        game.GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;

        // Set sampler state to Point as the Surface type requires it in XNA 4.0
        game.GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp;

        // Set the camera properties for all lights
        BaseLight.SetCameraProperties(game.ActiveCamera);

        // Draw the lights
        int numLights = lights.Count;

        for (int i = 0; i < numLights; ++i)
        {
            if (lights[i].Diffuse.W > 0f)
            {
                lights[i].Render(gameTime, ref normalMap, ref depthMap, ref sgrMap);
            }
        }

        // Resolve the render target
        game.GraphicsDevice.SetRenderTarget(null);
    }

```

I have tried adjusting the render states but no combination works for both objects.

# Answer
> 3 votes
My guess is that when you draw the inside-out objects into your G-buffer, you have to reverse the normal vectors. If you don't do this, it will have the effect of making the faces look like they're lit from behind. You can do this using the `VFACE` semantic in the pixel shader (see MSDN); it will be +1.0 for front-facing and -1.0 for back-facing primitives, so multiplying your normal by it should have the desired effect.

---
Tags: xna, lighting, culling
---


# Question
Title: How to implement the rag doll physics in OpenGL?
I'm wondering, having a human model made in blender, how can you make it so that at some point (when the human "dies") the body follows the rag doll physics in OpenGL? I tried looking for some tutorials but I can't found one that fits my requests. Specifically how do you make rag doll physics in OpenGl (and if needed using Blender)?

# Answer
> 3 votes
Look into Bullet Physics.

It's a good free library for 3D physics, and the demo code it ships with all uses OpenGL. Not that the physics and graphics API have anything to do with each other, but it might help you grasp the relationship to see code youre familiar with.

---
Tags: physics, blender
---


# Question
Title: HTML5 Canvas Converting between cartesian and isometric coordinates
I'm having issues wrapping my head around the Cartesian to Isometric coordinate conversion in HTML5 canvas. As I understand it, the process is two fold:

(1) Scale down the y-axis by 0.5, i.e. **ctx.scale(1,0.5);** or **ctx.setTransform(1,0,0,0.5,0,0);** This supposedly produces the following matrix:

```
[x; y] x [1, 0; 0, 0.5]

```

(2) Rotate the context by 45 degrees, i.e. **ctx.rotate(Math.PI/4);** This should produce the following matrix:

```
[x; y] x [cos(45), -sin(45); sin(45), cos(45)]

```

This (somehow) results in the final matrix of ctx.setTransform(**2,-1,1,0.5,0,0**); which I cannot seem to understand... How is this matrix derived? I cannot seem to produce this matrix by multiplying the scaling and rotation matrices produced earlier...

Also, if I write out the equation for the final transformation matrix, I get:

```
newX = 2x + y
newY = -x + y/2

```

But this doesn't seem to be correct. For example, the following code draws an isometric tile at cartesian coordinates (500, 100).

```
ctx.setTransform(2,-1,1,0.5,0,0);
ctx.fillRect(500, 100, width*2, height);

```

When I check the result on the screen, the actual coordinates are (285, 215) which do not satisfy the equations I produced earlier... So what is going on here? I would be very grateful if you could:

(1) Help me understand how the final isometric transformation matrix is derived;

(2) Help me produce the correct equation for finding the on-screen coordinates of an isometric projection.

Many thanks and kind regards

# Answer
> 4 votes
The issue you have is that you're not taking into account the effect of the translation of the square away from the origin.

**ctx.rotate** and **ctx.scale** both work relative to the top left of the canvas, at co-ordinates (0, 0). What this means is when you rotate your top left corner at (500, 100), it will move 45 degrees in an arc around from there. when it is scaled, it will just scale these corner positions, not the size of the rectangle around the corners.

When you want to scale and rotate the square, you need to choose the anchor point on the square around which you rotate and undo the translation first. For example, here's an example using the top-left corner:

jsfiddle.net/9atht/1/

```
ctx.translate(500, 100);
ctx.scale(1, 0.5);
ctx.rotate(Math.PI/4);
ctx.translate(-500, -100);
ctx.fillRect(500,100,20,20);

```

Note how the transforms are loaded in reverse - the order these are applied is bottom to top.

Clearly it's a bit fiddly to constantly undo then re-do the translation, so a slightly better way is to do your transformations around zero then move it out to where you want it:

jsfiddle.net/auVrK/

```
ctx.translate(500, 100);
ctx.scale(1, 0.5);
ctx.rotate(Math.PI/4);
ctx.fillRect(0, 0, 20, 20);

```

Clearly again here the top-left corner in both is the same. If we want the middle of each square to be in the same place (and generally you do since it's the easiest way of thinking about it), we draw our square so the middle of it is initially at zero:

http://jsfiddle.net/hfjuG/

```
ctx.translate(500, 100);
ctx.scale(1, 0.5);
ctx.rotate(Math.PI/4);
ctx.fillRect(-10, -10, 20, 20);

```

With each tile you draw you'll need to translate relative to the last one you drew:

http://jsfiddle.net/fZTuF/

```
ctx.fillStyle="yellow";
ctx.translate(20, 0);
ctx.fillRect(-10, -10, 20, 20);

```

On the plus side, you can work in your 'world' space to do this. On the down side, you still need to draw from the furthest to the nearest, so you'll have to work diagonally across your map. :)

Last, but not least: I have no idea where on earth you got that transformation matrix from. I work it out to be:

```
0.707  -0.707    *    1  0     =    0.707  -0.3535
0.707   0.707         0  0.5        0.707   0.3535

```

which, when you put these into ctx.setTransform (along with the translation X and Y in the last two parameters) yields the correct result:

jsfiddle.net/3ugzy/1/

But only works if the tile is centred at the origin. This is because if not, the offset from the origin also gets factored in to the transform and it goes slightly wonky.

Hope that massive example helps! Sorry about the lack of hyperlinks, but I've kept the important ones in and de-linked the others to keep the spam police happy.

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


# Question
Title: Java - Tile engine changing number in array not changing texture
I draw my map from a txt file. Would I have to write to the text file to notice the changes I made? Right now it changes the number in the array but the tile texture doesn't change. Do I have to do more than just change the number in the array?

```
public class Tiles {

public Image[] tiles = new Image[5];

public int[][] map = new int[64][64];

private Image grass, dirt, fence, mound;

private SpriteSheet tileSheet;

public int tileWidth = 32;
public int tileHeight = 32;

Player player = new Player();

public void init() throws IOException, SlickException {
    tileSheet = new SpriteSheet("assets/tiles.png", tileWidth, tileHeight);

    grass = tileSheet.getSprite(0, 0);
    dirt = tileSheet.getSprite(7, 7);
    fence = tileSheet.getSprite(2, 0);
    mound = tileSheet.getSprite(2, 6);
    tiles[0] = grass;
    tiles[1] = dirt;
    tiles[2] = fence;
    tiles[3] = mound;

    int x=0, y=0;
BufferedReader in = new BufferedReader(new FileReader("assets/map.dat"));
String line;
while ((line = in.readLine()) != null) {
        String[] values = line.split(",");
    for (String str : values) {
            int str_int = Integer.parseInt(str);
            map[x][y]=str_int;
            //System.out.print(map[x][y] + " ");
            y=y+1;
        }
//System.out.println("");
x=x+1;
    y = 0;
}
    in.close();
}

public void update(GameContainer gc) {

}

public void render(GameContainer gc) {
    for(int x = 0; x < map.length; x++) {
        for(int y = 0; y < map.length; y ++) {
            int textureIndex = map[y][x];
            Image texture = tiles[textureIndex];
            texture.draw(x*tileWidth,y*tileHeight);
        }
    }
}

```

**Mouse picking**

```
public void checkDistance(GameContainer gc) {
    Input input = gc.getInput();

    float mouseX = input.getMouseX();
    float mouseY = input.getMouseY();

    double mousetileX = Math.floor((double)mouseX/tiles.tileWidth);
    double mousetileY = Math.floor((double)mouseY/tiles.tileHeight);

    double playertileX = Math.floor(playerX/tiles.tileWidth);
    double playertileY = Math.floor(playerY/tiles.tileHeight);

    double lengthX = Math.abs((float)playertileX - mousetileX);
    double lengthY = Math.abs((float)playertileY - mousetileY);
    double distance = Math.sqrt((lengthX*lengthX)+(lengthY*lengthY));

    if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON) && distance < 4) {
        System.out.println("Clicked");
        if(tiles.map[(int)mousetileX][(int)mousetileY] == 1) {
            tiles.map[(int)mousetileX][(int)mousetileY] = 0;
        }
    }

    System.out.println(tiles.map[(int)mousetileX][(int)mousetileY]);
}

```

# Answer
What seems a bit strange to me is the loop where you read the file. As I understood your input file looks something like

```
1, 2, 3
4, 4, 4
4, 4, 4

```

If I read your code right you assign the X axis from the file to the y axis inyour data structure. The bit above would be translated into

```
1, 4, 4
2, 4, 4
3, 4, 4

```

Try to switch the x and y value in the loop (use y for the outer and x for the inner loop).

Otherwise, the code looks like it should render as you expect it (besides this little thing). So maybe something is wrong with the texture loading... Have you tried to rendere every terrain texture? Or maybe try to render the level with a hardcoded value. If it doesn't work like that the problem will be in the area of image loading.

Also, use x++ and y++ instead of x = x + 1 ;) Not really an issue but it is more compact and (personally) i find it easier to read.

**Edit:** In the way you load your map currently, the first array dimension is used for the y axis and the second dimension is used for the x axis.

```
int[][] tiles = new int[HEIGHT][WIDTH];

```

I would switch the dimensions so likte this:

```
int[][] tiles = new int[WIDTH][HEIGHT];

```

When I read coordinates I read the x position first and I like it, when the code is also layed out like that. If you want to change it you would have to make two things:

**1:** In the init method, you have to increment (add 1) the x value when a character is read. Increment the y value after the complete line has been read.

```
while ((line = in.readLine()) != String[] values = line.split(",");
    x = 0;
    for (String str : values) {
            int str_int = Integer.parseInt(str);
            map[x][y]=str_int;
            //System.out.print(map[x][y] + " ");
            x++;
        }
    y++;
}

```

**2:** Change the render method. The y loop needs to be outside the x loop. (I also added a bit so you can use different width and height values, but basically its best to store the value somewhere):

```
    int width = map.length;
    int height = map[0].length;
    for(int y = 0; y < height; y++) {
        for(int x = 0; x < width; x ++) {
            int textureIndex = map[y][x];
            Image texture = tiles[textureIndex];
            texture.draw(x*tileWidth,y*tileHeight);
        }
    }

```
> 1 votes

---
Tags: java, textures
---


title: How to use OpenGL's glUseProgram?

text:
# Question
Title: How to use OpenGL's glUseProgram?
While in the rendering loop, is it OK to call `glUseProgram`? Does it have a big overhead? I'm planing to use a program for each different material in the scene. I'm a real beginner with OpenGL and I'm afraid that changing the program several times for each frame it's not the best practice (although I can't think of something else).

# Answer
In the order of slow things, changing programs is more or less around the level of changing textures. It's something you have to do in order to render what you need, but for performance sake, it might be a good idea to minimize the number of changes where reasonable. This could be changing the order in which things are drawn (objects using the same shader are rendered sequentially), texture atlasing, etc.
> 2 votes

# Answer
It's more clear if you do it the way you described. For me, clarity always wins over performance. It will be easier to trace bugs if you enclose only the code that absolutely *needs* the shaders with `glUseProgram(...)`.
> 0 votes

---
Tags: opengl, opengl-es
---


title: OpenGL ES 2.0: Mixing 2D with 3D

text:
# Question
Title: OpenGL ES 2.0: Mixing 2D with 3D
Is it possible to mix 2D and 3D graphics in a single OpenGL ES 2.0 game, please?

I have plenty of 2D graphics in my game. The 2D graphics is represented by two triangular polygons (making up a rectangle) with texture on them. I use **orthographic** matrix to render the whole scene.

However, I need to add some 3D effects into my game. Threfore, I wish to use **perspective** camera to render the meshes.

Is it possible to **mix orthographic and perspective camera** in one scene? If yes, is there going to be a large performance cost for this? Is there any recommended approach to do this effectively? I wil have 90% of 2D graphics and only 10% of 3D.

Target platform is OpenGL ES 2.0 (iOS, Android). I use C++ to develop.

Thank you.

# Answer
This is easily done.

Set the view transform to orthographic for the 2D stuff, and render it. Then, before clearing the framebuffer, draw the effects with a perspective projection. The projection will only effect the geometry drawn after it, so just set the desired mode prior to drawing.

This is the same way we handle HUDs in our FPS. :)

The only performance impact is that your are changing a uniform variable (your project matrix), right? So, just try to batch things to minimize state changes--same old stuff.
> 10 votes

# Answer
There will only be a slight performance hit if you *calculate* the orthographic and perspective projection matrix each time you render to the frame buffer. I suggest caching them in a variable, calculating and storing them once in the initialization code, and then using `glLoadMatrix` to load the matrix. The rendering method would look like this in pseudo-code:

```
// Draw 3D things first
glMatrixMode(GL_PROJECTION);
glLoadMatrix(perspective_projection_matrix);
glMatrixMode(GL_MODELVIEW);
Draw3DObjects();
// Draw 2D things second
glMatrixMode(GL_PROJECTION);
glLoadMatrix(orthographics_projection_matrix);
glMatrixMode(GL_MODELVIEW);
Draw2DObjects();

```
> 1 votes

---
Tags: opengl-es
---


# Question
Title: Should the modelview and projection matrices be calculated in the shader or on the CPU?
At minimum I would have a camera with rotation and world position; projections parameters such as angle of view and perspective vs. orthographic; and meshes with scale, angle, and world position.

When rendering a mesh I am wondering if I should calculate the final transformation matrix on the CPU and pass it to my shader, or if I should calculate the transformation matrix inside my shader.

# Answer
> 7 votes
There is no reason to calculate transformation matrix in shader, it would be just waste of resources, because you would need to calculate it for every vertex and that's not good idea.

If you calculate matrix in cpu, it would cost you few instructions and `16 * float size` data transfer to GPU.

If you calculate matrix in gpu, it would cost you `few instructions` * `vertices count` and `9 * float size` transfer to GPU - position, rotation, scale.

# Answer
> 0 votes
You should most definitely calculate the matrices in client cod, since the matrices do not change on a vertex-to-vertex basis. You are essentially repeating one calculation - of which you know the answer will be the same - for every time the vertex program is run.

---
Tags: opengl, shaders, matrix
---


# Question
Title: Why isn't my lighting working properly? Are my normals messed up?
I'm relatively new to OpenGL and I am trying to draw a 3D model (loaded from a 3ds file using lib3ds) using OpenGL with lighting, but about half of it is drawn in black.

I set up the light as such:

```
glEnable(GL_LIGHTING);
glShadeModel(GL_SMOOTH);

GLfloat ambientColor[] = {0.2f, 0.2f, 0.2f, 1.0f};
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientColor);

glEnable(GL_LIGHT0);
GLfloat lightColor0[] = {1.0f, 1.0f, 1.0f, 1.0f};
GLfloat lightPos0[] = {4.0f, 0.0f, 8.0f, 0.0f};
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor0);
glLightfv(GL_LIGHT0, GL_POSITION, lightPos0);

```

The model is in a VBO and drawn using `glDrawArrays`. The normals are in a separate VBO, and the normals are calculated using `lib3ds_mesh_calculate_vertex_normals`:

```
std::vector<std::array<float, 3>> normals;
for (std::size_t i = 0; i < model->nmeshes; ++i) {
  auto& mesh = *model->meshes[i];
  std::vector<float[3]> vertex_normals(mesh.nfaces * 3);
  lib3ds_mesh_calculate_vertex_normals(&mesh, vertex_normals.data());
  for (std::size_t j = 0; j < mesh.nfaces; ++j) {
    auto& face = mesh.faces[j];
    normals.push_back(make_array(vertex_normals[j]));
  }
}
glBindBuffer(GL_ARRAY_BUFFER, normal_vbo_);
glBufferData(GL_ARRAY_BUFFER,
             normals.size() * sizeof(decltype(normals)::value_type),
             normals.data(),
             GL_STATIC_DRAW);

```

The problem isn't the vertices; the model is drawn correctly when drawing it as a wireframe. I also fixed the normals in Blender using `control``N`. What could be the problem? Should I store the normals in a different order?

# Answer
> 1 votes
Since pressing Control-N removed your problem, the normals your model had prior to you pressing Control-N were not correct. So yes, your normals *were* messed up, but your client code is most likely fine.

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


title: Opengl-es picking object

text:
# Question
Title: Opengl-es picking object
I saw a lot of picking code **opengl-es**, but nothing worked. Can someone give me what am I missing?

My **code** is (from tutorials/forums)

```
Vec3 far  = Camera.getPosition();
Vec3 near = Shared.opengl().getPickingRay(ev.getX(), ev.getY(), 0);

Vec3 direction = far.sub(near);
direction.normalize();

Log.e("direction", direction.x+" "+direction.y+" "+direction.z);

Ray mouseRay = new Ray(near, direction);

for (int n=0; n<ObjectFactory.objects.size(); n++) {
    if (ObjectFactory.objects.get(n)!=null) {
        IObject obj = ObjectFactory.objects.get(n);

         float discriminant, b;
         float radius=0.1f;

         b = -mouseRay.getOrigin().dot(mouseRay.getDirection());
         discriminant = b * b - mouseRay.getOrigin().dot(mouseRay.getOrigin()) + radius*radius;

         discriminant = FloatMath.sqrt(discriminant);

         double x1 = b - discriminant;
         double x2 = b + discriminant;

         Log.e("asd", obj.getName() + " "+discriminant+"   "+x1+" "+x2);
    }
}

```

my **camera** vectors:

```
//cam
Vec3 position   =new Vec3(-obj.getPosX()+x, obj.getPosZ()-0.3f, obj.getPosY()+z);
Vec3 direction  =new Vec3(-obj.getPosX(),   obj.getPosZ(), obj.getPosY());
Vec3 up         =new Vec3(0.0f, -1.0f, 0.0f);
Camera.set(position, direction, up);

```

and my **picking** code:

```
public Vec3 getPickingRay(float mouseX, float mouseY, float mouseZ) {

    int[] viewport      = getViewport();
    float[] modelview   = getModelView();
    float[] projection  = getProjection();

    float winX, winY;
    float[] position    = new float[4];

    winX = (float)mouseX;
    winY = (float)Shared.screen.width - (float)mouseY;

    GLU.gluUnProject(winX, winY, mouseZ, modelview, 0, projection, 0, viewport, 0, position, 0);

    return new Vec3(position[0], position[1], position[2]);
}

```

My camera moving all the time in 3d space. and my actors/modells moving too. my camera is following one actor/modell and the user can move the camera on a circle on this model.

How can I change the above code to working?

# Answer
There is a much easier way of picking which requires much less processing power. You simply give each model a specific color, render it without updating the screen, check if the mouse cursor is hovering over the color in question by calling `glReadPixels` (use PBOs if you want more performance), and then clear the screen and render normally. The non-pickable objects should be black.
> 2 votes

---
Tags: opengl, mathematics, picking
---


title: How to create my first game?

text:
# Question
Title: How to create my first game?
I'm entering the world of game development. I'm comfortable with C++ and Java. I'm okay with algorithms.

**How should I start out with game development?**

I'd love to start from creating simple puzzle like games, and slowly develop into strategy games like dota and then 3D games like GTA.

Edit: I started with OpenGL and I love it a lot. Thank you all :)

# Answer
You can go two roads with game development as you have described it.

**The Hard Way - OpenGL or Direct3D**

You use the LWJGL or JOGL for Java or OpenGL with Wiggle or GLFW in C++. This method is notoriously difficult and will consume a lot of your time (upwards of 50 hours probably). However, it will pay off in the long run and you will have learned a lot.

*You will spend more time with the graphics, and less time with the game.*

**The Easy Way - Slick2D**

Here you use a high-level library that abstracts from all of the intricacies of game development. It's much easier to learn than plain OpenGL or, even worse, Direct3D. Since Slick2D is a Java library, you can generally distribute it easily to Windows, Mac, and Linux. The downside is that it isn't as flexible as OpenGL or Direct3D and you don't have as much control.

*You will spend less time with the graphics and more with the game.*
> 1 votes

# Answer
I also suggest that you take a look at slick2d. The thing is that slick2d is a library built on top of lwjgl, which basically is (or part of it is) a wrapper for open gl in java. You can start by using only the command set from slick, but when you dive a bit into the open gl materia, you can start using opengl together with slick.

First of all, don't start a big project but get comfortable with the topic. Start creating prototypes for displaying images, rotating them, handle user input etc. When you have grasped the basics start with a simple game. Try to implement a small game you know. Could be minesweeper, breakout, snake or whatever, but first of all you shouldn't start a too big project, as it ends up often in a mess (I started with slick2d about a year ago. When I look at the code I wrote then a shudder runs down my back XD). Try to complete the game and polish it (include main menu, highscores, maybe saving depending on the game, sound fx and music)..

When you completed that game start with something new, this time a bit bigger, and try to improve your skillset...

Another great tip: Hang around in forums and look for useful information... I tend to go to here and http://www.java-gaming.org and look for interesting topics, even if they aren't directly related to my current problems, I often find very useful pieces of code or explanations, which I store in a seperate folder in my bookmarks. Every now and then I go through that list and see if I can use something of it.
> 1 votes

---
Tags: puzzle, strategy
---


# Question
Title: Updating scene graph in multithreaded game
In a game with a render thread and a game logic thread the game logic thread needs to update the scene graph used by the render thread. I've read about ideas such as a queue of updates.

Can someone describe to a newbie at scene graphs what kind of interface the scene graph exports. Presumably it would be rather complicated. So then how does a queue of updates get implemented in C++ in a way that can handle the complexity of the interface of the scene graph while also being type safe and efficient. Again I'm a newbie at scene graphs and C++.

# Answer
> 4 votes
**What is a scene graph?**

A scene graph as used in videogames is defined as a tree of nodes, where each node has 1 parent or no parent. The node without a parent is called the root node, because it defines the start of the tree. Each node can also have 0 or more children.

What are they used for? Suppose you have a game where tanks are driving over terrain, shooting at each other. Each tank has a rotation and a position, compressed into a single 4x4 matrix. But what if we want to move the barrel of the tank? We want it to move *relative* to the tank, not completely independently.

So we'll split up the task: we put each tank in a separate node and add them as children to our root node. And then we add another node to each tank, a node for the barrel.

We traverse a tree from the bottom up. However, this is hard, because while a tree only has 1 root node, it can have `n` leaf nodes (nodes without children). Fortunately, the math works the other way around too.

To get the transformation for our barrel, we need to multiply the transformations of its parent, all the way up to the root node.

```
final_transform = root_transform * tank_transform * barrel_transform;

```

So what happens if we change the rotation in the `tank_transform` variable? The barrel rotates with it! This means that our barrel transformation is now *relative* to the tank transformation.

**Updating a scene graph using multiple threads**

And now to your question. You effectively want to flatten your scene graph. You would like to update your graph in steps, without those pesky dependencies on parent transformations. Well, one approach I've used in the past is to have each node contain a "dirty" flag for its transformation.

Let's say our tree looks like this in memory:

```
0 root
1 tank1
2 barrel1
3 tank2
4 barrel2

```

When can we use `barrel2`? When `tank2` has finished building its transformation matrix. When can we use `tank2`? When `root` has finished building its transformation matrix. So here's how it would work in practice. We add a flag saying if a transformation matrix is dirty or not to each node, and we give them a parent id.

```
id name     parent_id  dirty
----------------------------
0  root     -1         true
1  tank1    0          true
2  barrel1  1          true
3  tank2    0          true
4  barrel2  3          true

```

Now let's traverse the list. Check if the `dirty` flag is true. If so, check if its parent's `dirty` flag is true. If not, compute transformation matrix. If so, wait until next pass.

First pass:

```
id name     parent_id  dirty
----------------------------
0  root     -1         false
1  tank1    0          true
2  barrel1  1          true
3  tank2    0          true
4  barrel2  3          true

```

Second pass:

```
id name     parent_id  dirty
----------------------------
0  root     -1         false
1  tank1    0          false
2  barrel1  1          true
3  tank2    0          false
4  barrel2  3          true

```

Third pass:

```
id name     parent_id  dirty
----------------------------
0  root     -1         false
1  tank1    0          false
2  barrel1  1          false
3  tank2    0          false
4  barrel2  3          false

```

Why is this useful for multi-threading? Because by using multiple passes to compute the transformation matrices, *you have negated the dependency on the parent data*. However, this glosses over several problems:

* If thread 1 is writing to node 0, what will thread 2 read for node 1's parent?
* What happens when nodes point to each other as parents? (deadlock)
* How do you safely remove a node from this tree?

**Summary**

If you're not interested in a multithreaded scene graph, I would suggest just using a generic `Node` class that can have 0 or more children. Call its `Update` function with its parent's transformation matrix and you're golden.

If you want to look at some source code for that, I'd suggest looking at Ogre's scene graph implementation. It's very easy to read and understand.

---
Tags: rendering, multithreading, scene-graph
---


# Question
Title: How to take advantage of multiple core GPUs
I'm interested in developing for the new Nexus 7 tablet when it finally arrives. I've done a little OpenGL development for Android but I'm not sure what I have to do to take advantage of the 12-core GPU on the Nexus 7. Does OpenGL take advantage of the cores for you (in some/all cases); if not, how do I specify which core does what, synchronize between them etc?

# Answer
> 6 votes
GLES2 (OpenGL) pretty much forces you to use vertex buffer objects and shaders to do any rendering. That's a good thing because it means you are using the GPU correctly and keeping battery life high by keeping information off the power hungry transfer busses. You don't have to worry about using the entire GPU because those shader units automatically divide up the rendering tasks based on the geometry of your render windows.

http://developer.apple.com/library/ios/#documentation/3DDrawing/Conceptual/OpenGLES\_ProgrammingGuide/TechniquesforWorkingwithVertexData/TechniquesforWorkingwithVertexData.html

That's a link to Apple's site, but it will be the same practices for Android.

To the above who says using OpenCL kills battery life, this video speaks differently. It's a demo of the PowerVR GPU using OpenCL on the CPU, then on the GPU. It shows power consumption during the examples where they do image processing.
http://www.youtube.com/watch?v=sDrz-w1jzEU

Running benchmark apps will kill your battery, actually using OpenCL to perform tasks efficiently and quickly will keep power consumption down.

# Answer
> 0 votes
Yes, OpenGL spreads the load over all available cores on the GPU. To be more exact, the videocard driver spreads the hardware-specific implementation of the OpenGL commands over the cores. I read here that the Tegra 3 chipset by NVIDIA has 8 pixel shader units. That's not a lot compared to desktop videocards, for instance my NVIDIA GeForce GTX 560 Ti card has 384 CUDA cores.

I wouldn't worry about spreading your commands across all available cores, that's well into driver territory. Unless you're using OpenCL on Android, but that's ill-advised because it will eat up your battery like crazy.

---
Tags: android, gpu
---


title: Shaky Camera Effect 2D

text:
# Question
Title: Shaky Camera Effect 2D
The camera in my game engine can be modified by following a rectangle properties, that can be scaled, moved and even rotated. I need this effect for the shaking of the screen when a zombie attacks a character.

**How should I go about implementing this?**

# Answer
Store the logical screen position and the actual screen position in separate containers... The logical screen position is the position, where the screen should be, when no shaking happens... When shaking happens apply some offset to the logical screen position to get the actual screen position.

I made a little example (not tested and not completly implemented, but it should show how you could make the shake effect). Below I have added some thoughts about whats currently missing in my example.

```
class Viewport
{
    float xOffset = 0;
    float yOffset = 0;
    int shakeTimer = 0;

    public Vector2f actual;
    public Vector2f logical;

    //Shaking will take 200ms
    public final int SHAKE_TIME_MS = 200;

    //The screen will be moved 20 pixels forth and back
    public final int SHAKE_OFFSET = 20;

    //Indicates the shake move direction
    public boolean shakeDirection = false;

    //Indicates if the screen is currently shaking
    public boolean shaking;

    //delta is the ms passed since last update
    public void update(int delta)
    {
        if(shaking)
        {
            updateShake(delta);
        }
        else
        {
            actual.x = logical.x;
            actual.y = logical.y;
        }
    }

    private void updateShake(int delta) {
        if(shakeTimer == 0)
        {
            //If its the first run from the current shake, initialise x and y offset to 0
            xOffset = 0;
            yOffset = 0;
        }

        //Add passed milliseconds to timer... If timer exceeds configuration, shaking ends
        shakeTimer += delta;
        if(shakeTimer > SHAKE_TIME_MS)
        {
            //Shaking ends
            shakeTimer = 0;
            shaking = false;
            xOffset = 0;
            yOffset = 0;
        }
        else
        {
            applyScreenShake(delta);
        }
    }

    private void applyScreenShake(int delta) {
        //Depending on shake direction, the screen is moved either to the top left, or the bottom right
        if(shakeDirection)
        {
            xOffset -= 1.5f * delta;
            if(xOffset < -SHAKE_OFFSET)
            {
                //SWITCH DIRECTION
                xOffset = -SHAKE_OFFSET;
                shakeDirection = !shakeDirection;
            }
            yOffset = xOffset;
        }
        else
        {
            xOffset += 1.5f * delta;
            if(xOffset > SHAKE_OFFSET)
            {
                //SWITCH DIRECTION
                xOffset = SHAKE_OFFSET;
                shakeDirection = !shakeDirection;
            }
            yOffset = xOffset;
        }
        actual.x = logical.x + xOffset;
        actual.y = logical.y + yOffset;
    }
}

```

I hope this gets you going... Some things you can consider:

* Currently the screen only shakes linear to the top left and the bottom right... You could make this more interesting, by adding random move directions, as long as the x and y offset stays in a given distance.
* When the shaking ends, the x and y offset are abruptly set to 0/0... This causes the shake to end abruptly... You could smooth this out by handling the stopped case separately.
* When you want to scroll on the screen (map etc.) you have to change the logical position of the viewport.
* Your rendering logic needs to use the actual position and not the logical position as render offset.
> 6 votes

---
Tags: 2d, camera, effect
---


# Question
Title: How does sprite customization in 2D games work?
I´m working on the design of a new game concept at the moment and I would like to know how to handle a customization of sprites. (In 2D that is, hence the topic.)

This is my scenario: The player will have a tower containing 3 floors (or more). Each floor can be replaced by another "piece", i.e. a blue floor, a fire floor, a stone floor.

With the little knowledge of game development I have, creating a sprite for each possible combination is probably not a good idea, since the size of the game file will be HUGE.

So, how does developers solve this? Do you put a standard position and just replace the sprite itself? Any advice or information about this would be great.

Regards.

# Answer
> 4 votes
You don't have one sprite, you have three sprites. A "top", "middle", and "bottom" sprite. You just render all three sprites when you render the player's tower. Need to change the middle segment? Not a problem, just swap out the "middle" sprite.

There's no reason to try generating all possible sprite combinations and there's no reason to do anything fancy with color-keying or programmatic replacements.

That's roughly how something like Ultima Online worked - each "player" is a pile of a half-dozen to dozen sprites, one for each piece of equipment, and they all just get rendered together.

# Answer
> 2 votes
This could be done using colour-keying.

This would work much in the same way that green-screening works for TV - look for a particular colour and replace it. It's quite common for this to be a colour not normally used (and quite garish) like magenta.

Some SDKs (like SDL) have direct support for this, but you can easily add it to any shader that draws a sprite, just like you'd expect - look for your colour and replace it with one specified in code.

Of course, if you're dealing with more complex situations (like multiple customisations) you need multiple different colour keys. At this point, the simpler solution might be to use transparent sprites, a range for each part, and then composite them together afterwards by drawing one on top of the other.

**Edit:**

I'm going to use your example above about a character with a head, body and legs since it's a bit easier to understand. :)

Since you can both change the shape of the item (different shape heads, male/female heads) and also the hair colour (red, brown, blonde, blue...) you could have each head shape and then have the hair pixels marked in your colour key, for example all hair is magenta. Then, you can overwrite magenta with red, brown, blonde or blue.

The downside of this is that it needs to be an exact colour match, so you couldn't do shaded colour from this approach. However, if you separate the image out into a mask and the detail, you can colour-key the mask and then add semi-transparent detail on top.

This would work based on alpha blending - much in the same way that if you overlay one colour at half opacity over another, you still get some of the previous colour. This then requires that when you're developing your assets, rather than picking the colour you want you need to have a layer underneath of the 'base' colour that's going to be replaced by magenta and then you have to put a colour on top that creates the desired difference you want. In this case also, you detail will more than likely be in black and white or it won't apply nicely across all the colours. Sadly my pixel-fu isn't strong so I can't really show you an example.

In short though, it's an awful lot of work just to save a bit of memory in assets - you could probably be better served by breaking things down into smaller parts (in this case, separating the hair from the head) and then making each iteration of them.

---
Tags: 2d, sprites
---


# Question
Title: Is there any simple game that involves psychological factors?
I need to find a simple game in which several people need to interact with each other. The game should be simple for an analysis (it should be simple to describe what happens in the game, what players did). Because of the last reason, the video games are not appropriate for my purposes. I am thinking of a simple, schematic, strategic game where people can make a limited set of simple moves.

Moreover, the moves of the game should be conditioned **not only** by a pure logic (like in chess or go). The behavior in the game should depend on psychological factors, on relations between people. In more details, I think it should be a cooperation game where people make their decisions based on mutual trust. It would be nice if players can express punishment and forgiveness in the game.

Does anybody knows a game that is close to what I have described above?

**ADDED**

I need to add that I need a game where actions of players are simple and easy to formalize. Because of that I cannot use verbal games (where communication between players is important). By simple actions I understand, for example, moves on the board from one position to another one, or passing chips from one player to another one and so on.

# Answer
> 1 votes
There's Mafia, a "party game" where players are split in two teams: a few members of the Mafia who know each other and a larger group of regular people who don't know who is who. The goal of each team is to eliminate the other one.

Mafiosi kill one person at night. On the following day, people deliberate to nominate somebody who'll be killed. That's where you find psychology. The art of lying, betrayal and denunciation.

Very fun game. I especially like the werewolf variant.

# Answer
> 1 votes
Have you considered card games? Specifically something like straight poker (complete hands, no draws, no community cards). The mechanics are really simple, and all of the strategy is purely estimations of your opponents' state.

# Answer
> 1 votes
Perhaps consider Mao. Be warned that looking it up will ruin it for yourself, but in theory you could keep track of strict actions to try to draw psychological conclusions.

# Answer
> 0 votes
I've not played it myself, it might also be a bit more complex than you want, but I've a friend who likes http://www.transformice.com/

# Answer
> 0 votes
It sounds like you are asking a question about Game Theory. This weird branch of math-psychology-business contains a number of "games" that sound exactly like what you are asking for, such as the Ultimatum Game and Prisoner's Dilemma. Each player makes a very simple yes/no or numeric choice, results are compared to an outcome table, and players typically follow algorithms that are based partly on math/logic and partly on a subjective sense of fairness.

# Answer
> 0 votes
I find Galcon to be a great example of a simple game with a huge psychology factor. You have to play it for rather a while before you figure out what's really going on as far as strategy, but once you do it's fairly deep. The trade off between looking too dangerous and looking too weak is fascinating.

---
Tags: strategy
---


# Question
Title: Big level objects collision system for 2d game
I read many variants today and get some knowledge in general, so here is a steps of mine thoughts in pictures (horrible paint.net ones).

We need to develop grid system, so we check only thing near, perform simple check to cut out deep check, and at - last deep check like per-pixel collision check.

1. **Step 1** \- Let `p1`, `p2` are some sprites lets first just check with circle collision - because large distance between `p1`, `p2` this fails and of course so we don't need test more deeply. But if we have not 2, but 20 objects, why we need to even circle test something so far outside of our view.
2. **Step 2** \- Add basic column system, now we don't bother with `p2` if it's in a column far from `p1` column, so we even don't do circle test. But `p3` is in the same col, so let do circle test, which of course will fail.
3. **Step 3** \- Lets improve column system to the grid system with grid cell size just like `p1`, `p2`, `p3` collision boxes, so we cut out things much top or below `p1`. And this is all great until comes BIG OBJs which is some kind of platforms. They are much bigger then grid cell.

*Circle test for will be successful, but deep check for whole big obj will fail*

**And that the part I can't get.**

How do I store the grid position of big object? Like 4 grid coords for big object vertexes? And if one of them close to `p1` do circle check for centre of big object then a deep one if succeed? Am I do it wrong?

My possible solution:

# Answer
Personally, I think you should do away with the grid system. Since you have all circles, you should add the radii of two circles together. If the distance between two circle's center points is equal to or less than the radii calculation, you have a collision.

Other option for keeping a grid system: Instead of checking to see if another object (such as P3) is in the same row and column as your current object (P1), you should check if P3 lies within P1's grid(s) position(s) and also check to see if P3 lies within neighboring grid positions to P1, or positions surrounding them. Then if it's in the same row/column or in a neighboring one, you could check for circle collision. This all depends on how you setup your rectangles for your objects. Many people actually put their rectangles outside of the object rather than inside so that the whole circle (plus a small amount of surrounding area) will collide. This will not always result in a perfect collision, but could give you a more desirable result since other objects won't be inside your object.
> 2 votes

# Answer
This collision implementation seems backwards, in all honesty, but maybe you may have specific reasons for it.

Is there any particular reason why your first pass is to check if circles are touching? As far as I know, finding collisions between circles can be taxing because of the use of square roots.

Instead, you could use a bounding box for every object on the grid. The box dimensions are dictated by the greatest x and y dimension of an arbitrarily-oriented object.

During every frame, you check to see if there are any collisions between the bounding boxes (which shouldn't be too bad performance and complexity-wise). If there is a collision, you then perform a sub-check of two objects in question and see if the ACTUAL objects are colliding.
> 0 votes

# Answer
You should take a look at quad trees. Its a common datastructure to store spatial data in cells. When you do the collision testing, you simply test against the objects in the same cell... I use the same datastructure for rendering. I pass the rect that defines the viewport into a selection method of the tree and receive a list of cells. Now i just have to render all sprites from those nodes...

When the object spans over multiple cells ,you can add it to both cells. Just make sure to remove the duplicates ,when you use the results from the selection method. I'm currently on my phone, so I have no code examples here ,but a quick google for quadtree should help.
> 0 votes

# Answer
Big or small, if an object exceeds one pixel it could show up in multiple grid squares. You have to put it in multiple lists.
> 0 votes

---
Tags: 2d, collision-detection, platformer
---


title: Turn Based Event Algorithm

text:
# Question
Title: Turn Based Event Algorithm
I'm currently working on a small roguelike in XNA, which sees the player in a randomly generated series of dungeons fending off creeps, as you might expect. As with most roguelikes, the player makes a move, and then each of the creeps currently active on screen will make a move in turns, until all creeps have updated, and it return's to the player's go. On paper, the simple algorithm is straightforward:

Player takes turn
Turn Number increments
For each active creep, update Position
Once all active creeps have updated, allow player to take next turn

However, when it comes to actually writing this in more detail, the concept becomes a bit more tricky for me. So my question comes as this: what is the best way to handle events taking turns to trigger, where the completion of each last event triggers the next, when dealing with a large number of creeps (probably stored as an array of an enemy object), and is there an easier way to create some kind of engine that just takes all objects that need updating and chains them together so their updates follow suit?

I'm not asking for code, just algorithms and theory in the direction of objects triggering updates one after the other, in a turn based manner.

Thanks in advance.

Edited: Here's the code I currently have that is horrible :/

```
        if (player.getTurnOver() && updateWait == 0)
            {
                if (creep[creepToUpdate].getActive())
                {
                    creep[creepToUpdate].moveObject(player, map1);
                    updateWait = 10;
                }
                if (creepToUpdate < creep.Length -1)
                {
                    creepToUpdate++;
                }
                else
                {
                    creepToUpdate = 0;
                    player.setTurnOver(false);
                }
            }
            if (updateWait > 0)
            {
                updateWait--;
            }

```

# Answer
> 1 votes
Here's something I did for a similar "small roguelike", and it wound up working pretty well, and perhaps you will have success with it.

To make this clearer, I must first talk about the concept of "turns".

My Roguelike was based (loosely) upon the board game HeroQuest, which involved the typical dice rolling, moving figures, etc.

I didn't want to have my game like that. I wanted the player to move a square and I wanted the creatures to move appropriately. However, I did still want the idea of a particular amount of movement for the player equating to a differing amount of movement for the creatures.

So, I kept track of the fractional turn of the creatures. If a creature has a movement rate of 8 squares per turn, then each time he moves he increments his fractional turn by 0.125. If he moves 10 squares per turn, he increments only by 0.1.

And this can be used for any activity done by the creature. If a creature may attack 1 time per round, then when he attacks add 1 to the fractional turn. If a creature may attack 2 times per round, then add 0.5.

On the threshholds (where the fractional turn goes from a 0 point something to a 1 point something, like perhaps going from 0.95 to 1.05), then this triggers an "end of turn" event for the creature, where health recovery, mana recovery, or whatever else you want to have happen for the creature.

At any time, picking the creature to move next is quite simple. Whoever has the lowest fractional turn value gets to move next. When the player is next to move, then wait for user input. You could easily adapt a priority queue to use for this purpose, where the lowest fractional turn is the priority.

A small caveat: I had multiple areas in the game, so not everything was loaded at the same time. If everything is loaded at once, it doesn't matter what the turn values are, because less is still less, but if a player leaves an area and the creatures in it are no longer updated, when the player arrives again he will have a much larger turn value than the other creatures, and they will get a lot of opportunity to beat him to a pulp.

This is how I mitigated that: when a player leaves the area, subtract his turn value from all of the turn values of all of the creatures in it. When he arrives in an area, add his turn value to all creatures in it. This way between visits the areas have a relative value to the player that can be restored later.

---
Tags: xna, c#, turn-based
---


# Question
Title: Creating an OpenGL FPS camera: I have the position and orientation vectors, now what?
I have been struggling to create a first person camera in OpenGL ES 2.0 without using gluLookAt(). I grab the camera's orientation vectors (the way it's looking) from the current modelview matrix, and use that to calculate the new forward/backward (Z) translation value. I then calculate the strafe (X) value from the dot product of Z and Y (which is always 1.0). So, I have all the information I need to create a view matrix, but how do I do that without using gluLookAt? Almost all the examples I've seen use gluLookAt, but no such function exists in OpenGL ES 2.0. Besides, one of the moderators on cprogramming.com mentioned that gluLookAt is not appropriate for FPS cameras:

http://cboard.cprogramming.com/game-programming/135390-how-properly-move-strafe-yaw-pitch-camera-opengl-glut-using-glulookat.html

I am really confused by all the conflicting information I'm getting. I just want to create a first person camera that goes forward (W,S keys), side-to-side (A,D keys) and rotates around its center (Y axis only), Wolfenstein style.

Here's more-or-less my existing code:

```
vec4 cur_look,dir_move,dir_strafe,cam_pos;
mat4 mat_modelview,mat_rot,mat_temp;
float lr; //left/right keypress increment value
float ud; //up/down keypress increment value

//grab current camera orientation (look at) from the modelview matrix
cur_look[0] = mat_modelview[8];
cur_look[1] = mat_modelview[9];
cur_look[2] = mat_modelview[10];
cur_look[3] = mat_modelview[11];

//rotate the direction vector using the rotation matrix
mat4_identity(mat_rot);
mat4_identity(mat_temp);
mat4_rotate_Y(mat_rot,mat_temp,lr); //create rotation matrix

//multiply the current direction vector by the rotation
//matrix and place the result in dir_move
mat4_mul_vec4(dir_move, mat_rot, cur_look);

//normalize the fwd/back direction vector
vec4_norm(dir_move,dir_move);

//calculate strafe vector using cross product of Z and Y
vec4_cross(dir_strafe,dir_move,(vec4){0.0,1.0,0.0,0.0});

//normalize strafe vector
vec4_norm(dir_strafe,dir_strafe);

//detect key input

//FWD/BACK
if(key_pressed == 'w'){
    cam_pos[2] += (dir_move[2] * -INPUT_SENS_Z); //z
}
if(key_pressed == 's'){
    cam_pos[2] += (dir_move[2] * INPUT_SENS_Z); //z
}

//ROTATION
if(key_pressed == LEFT_ARROW){
    lr += INPUT_SENS_ROT;
}
if(key_pressed == RIGHT_ARROW){
    lr +=  -INPUT_SENS_ROT;
}

//build new modelview matrix
mat4_identity(mat_modelview);

//multiply modelview matrix by rotation matrix
mat4_mul(mat_modelview,mat_modelview,mat_rot);

//create translation matrix
mat4_translate(mat_tran,-cam_pos[0], 0.0, -cam_pos[2]);
//multiple modelview matrix by translation matrix
mat4_mul(mat_modelview,mat_modelview,mat_tran);

//update uniforms and draw scene using glDrawArrays()
glUniformMatrix4fv(loc_modelview, 1, GL_FALSE, mat_modelview);

```

Any help on this would be much appreciated!

# Answer
> 4 votes
It seems like you are trying to do things backwards. Here is my preferred way of creating an FPS camera:

**Store the position and orientation in client code (Euler Angles)**

Define the position and orientations along the x, y, and z axis in the client code. This would would something like this in C++:

```
float camera_x = 0.0f;
float camera_y = 0.0f;
float camera_z = 0.0f;
float pitch = 0.0f; // The rotation along the x axis
float yaw = 0.0f; // The rotation along the y axis
float roll = 0.0f; // The rotation along the z axis

```

Then apply these variables before you render your objects in 3D space by writing:

```
glLoadIdentity();
glRotatef(pitch, 1.0f, 0.0f, 0.0f);
glRotatef(yaw, 0.0f, 1.0f, 0.0f);
glRotatef(roll, 0.0f, 0.0f, 1.0f);
glTranslatef(-x, -y, -z);

```

In the input handling code I make sure that the angles are never higher than 360 degrees or lower than 0 degrees to prevent precision loss, but this is up to you.

This method is unfortunately prone to the gimbal lock issue. I myself have never experienced this problem with FPS cameras, but you should be wary of it nonetheless. If you wish to avoid this problem, try quaternions. Be warned - they are notoriously difficult to understand.

# Answer
> 2 votes
I figured out the problem. It had to do with this line:

```
if(key_pressed == 'w'){
    cam_pos[2] += (dir_move[2] * -INPUT_SENS_Z); //z
}

```

I was only adding to an individual element in the vector array. I should have been adding to the *entire array as a unit:*

```
if(key_pressed == 'w'){
    vec4_add(cam_pos,cam_pos,dir_move); //add dir_move to cam_pos
}

```

I still need to include the INPUT\_SENS\_Z value in the example to throttle the speed, but you get the idea. Thank goodness that's solved!

---
Tags: opengl, opengl-es, c
---


# Question
Title: Any significant performance cost to using BlendState.Premultiplied?
Normally I guess you'd use BlendState.AlphaBlend because normally when you load your textures through the pipeline they're already premultiplied. However, if you're loading textures at runtime from PNGs or some such, you have to loop through the pixels and premultiply them, which can take a long time if you've got a lot of textures to load.

So it looks (haven't tried it) like using BlendState.NonPremultiplied instead of BlendState.AlphaBlend should handle non-premultiplied textures and produce the same visual result, without all the startup costs. I have to wonder if there's a non-obvious cost to doing this, like a huge drop in performance or something. Anyone know?

# Answer
> 4 votes
There shouldn't be any performance cost to different blend modes. All of them are implemented in hardware and moreover, the difference between them is just which numbers get plugged into a standard blending formula.

---
Tags: xna, textures
---


# Question
Title: Adding VFACE semantic causes overlapping output semantics error
My pixel shader input is a follows

```
struct VertexShaderOut
{
    float4 Position                 : POSITION0;
    float2 TextureCoordinates       : TEXCOORD0;
    float4 PositionClone            : TEXCOORD1;        // Final position values must be cloned to be used in PS calculations
    float3 Normal                   : TEXCOORD2;
    //float3x3 TBN                  : TEXCOORD3;
    float CullFace                  : VFACE;            // A negative value faces backwards (-1), while a positive value (+1) faces the camera (requires ps_3_0)
};

```

I'm using ps\_3\_0 and I wish to utilise the VFACE semantic for correct lighting of normals depending on the cull mode.

If I add the VFACE semantic then I get the following errors:

> error X5639: dcl usage+index: position,0 has already been specified for an output register error X4504: overlapping output semantics

Why would this occur? I can't see why there would be too much data.

EDIT:

Vertex Shader:

```
VertexShaderOut VertexShaderFunction(VertexShaderIn input)
{
VertexShaderOut Output = (VertexShaderOut)0;

// 'input.Position.w' should always equal 1
input.Position.w = 1;

// [Transformation]
// • Multiplying input.Position by World, then the result by ViewProjection is fast
// • Concatenating World and ViewProjection matrices then multiplying input.Position by the result is slower
input.Position = mul(input.Position, World);
Output.Position = mul(input.Position, ViewProjection);

// [Texel To Pixel Align]
// • Half pixel offset for correct texel centering)
// • Should be done AFTER transformation
Output.Position.xy -= HalfPixelTexel.xy;

// [Texel To Pixel Align]
// • Adjust uv coordinates so they use the correct texture from the texture atlas
Output.TextureCoordinates = input.TextureCoordinates;

// [Normal]
// • Use world transform with normals to avoid problems with different coordinate systems
Output.Normal = mul(float4(input.Normal.xyz, 0), World).xyz;

//Output.TBN[0] = normalize(mul(input.Tangent, (float3x3)WorldViewIT));             // X Axis
//Output.TBN[1] = normalize(mul(input.BiTangent, (float3x3)WorldViewIT));           // Y Axis
//Output.TBN[2] = normalize(mul(input.Normal, (float3x3)WorldViewIT));              // Z Axis

// [Position Clone]
// • POSITION0 values can't be used in the pixel shader so they must be passed in via another semantic
Output.PositionClone = Output.Position;

// [VFace]
//Output.CullFace = 0;
//Output.CullFace = sign(dot(ViewInv[3].xyz - Output.Position, Output.Normal));

return Output;
}

```

Pixel Shader:

```
PixelShaderOutput PixelShaderFunction(VertexShaderOut input)
{
PixelShaderOutput output = (PixelShaderOutput)0;

// [Scale Texture Coordinates] (Page 12 - Texture Atlas Paper)
// • To access all texels of a texture of dimensions 'width' by 'height' once and only once, models need to use:
// • u-coordinates in the range [.5 / width, 1 - (.5 / width)]
// • v-coordinates in the range [.5 / height, 1- (.5 / height)]
// • This prevents bleeding of textures (like wrapping) when using an atlas

// Scaling method - Works with both quadrangles and arbitrary geometry with original uv coordinates between 0 and 1
float s = (BackBufferDim - 1.0f) / BackBufferDim;
float o = 0.5f / BackBufferDim;
input.TextureCoordinates.xy *= s;
input.TextureCoordinates.xy += o;

// Wrap coordinates in [0, 1) range (for both tiling and scrolling)
// Use 'frac(texCoord) * n' to wrap in [0, n) range
float2 texCoords0 = frac(input.TextureCoordinates.xy); //* input.NumTiles.xy);
float2 texCoords1 = frac(input.TextureCoordinates.xy); //* input.NumTiles.zw);

// Adjust uv coordinates so they use the correct texture from the texture atlas
texCoords0 = CalculateAtlasUV(texCoords0, SourceRectangle0);
texCoords1 = CalculateAtlasUV(texCoords1, SourceRectangle1);

float4 colour0 = tex2D(TextureSampler, texCoords0);
float4 colour1 = tex2D(TextureSampler, texCoords1);

// [Linear Interpolation]
// • Based on colour1 alpha (therefore colour1 takes precedence over colour0)
// • output = lerp(A, B, C);
// • output = A * (1 - C) + B * C;
float4 colour = lerp(colour0, colour1, colour1.a);

// [Flash]
// • Interpolate between final colour and flash colour based on the flash timer value
colour = lerp(colour, float4(1, 1, 1, 1), FlashAmount);

// [Colour]
output.Color = colour;

// [Tangent/Normal]
// • Get value in the range of -1 to 1
//float3 n = 2.0f * tex2D(BumpMapSampler, input.TextureCoordinates) - 1.0f;

// Multiply by the tangent matrix
//n = mul(n, input.Tangent);

// Output normal
output.Tangent.xyz = normalize(input.Normal) * 0.5f + 0.5f;
//output.Tangent *= input.CullFace;
output.Tangent.w = 1;

// [Specular, Glow, Reflection]
// • Completely optional
//output.SGR.r = tex2D(SpecularSampler, input.TextureCoordinates);
//output.SGR.g = tex2D(GlowSampler, input.TextureCoordinates);
//output.SGR.b = tex2D(ReflectionMap, input.TextureCoordinates);
//output.SGR.w = 0;

// [Depth]
// • Flip to keep accuracy away from floating point issues
output.Depth.r = 1.0f - (input.PositionClone.z / input.PositionClone.w);
output.Depth.a = 1;

return output;
}

```

# Answer
> 1 votes
Hmm, ordinarily the `POSITION0` is not part of the pixel shader input struct, nor `VFACE` part of the vertex shader output. Try removing those from the struct and adding them as a separate output parameter from the vertex shader, and input parameter to the pixel shader. It's a little weird, but perhaps internally, `VFACE` uses the same register as `POSITION0` (which would be possible because the former is only for pixel shaders and the latter only for vertex shaders).

That is, your shader prototypes might look something like:

```
struct VertexShaderOut
{
    float2 TextureCoordinates       : TEXCOORD0;
    float4 PositionClone            : TEXCOORD1;
    float3 Normal                   : TEXCOORD2;
    //float3x3 TBN                  : TEXCOORD3;
};

void VertexShaderFunction(
        VertexShaderIn input,
        VertexShaderOut output,
        float4 outPos : POSITION0)
{
    // ...code...
}

void PixelShaderFunction(
        VertexShaderOut input,
        float CullFace : VFACE)
{
    // ...code...
}

```

---
Tags: hlsl, culling
---


title: XNA content.load Dependancy

text:
# Question
Title: XNA content.load Dependancy
The project I'm building for test purposes is working fine but I have dependencies flying around everywhere due to the XNA framework.

My issue is in the content.load textures/sounds/fonts. I have them as public variables (i.e. `Texture1 = Content.load(of texture2d)("Texture1")` )

I'm passing a 'Game1' pointer into the constructor of every new class being instantiated to gain access to these variables.

**Am I missing an OOP trick that would prevent me having to pass a pointer to 'game1' to every New class?**

# Answer
> 2 votes
In my opinion the *simplest* way is just to add a public static reference to your game object, and assign it in the constructor. Has some similarities with using a singleton, but without all the restrictions:

```
public class Game1 : Game {
    public static Game1 Instance;
    public Game1() { Instance = this; }
}

```

After which you can easily access it from anywhere, such as `Game1.Instance.Texture1`.

# Answer
> 2 votes
Do you know something about Singleton pattern? You can create for example GetGameObject function in some file, where you create your game object. This function will return game object (which is created only once).

---
Tags: xna
---


# Question
Title: Inconsistent accessibility: parameter type is less accessible than method
I have a level class in which I make a new turret. I give the turret the level class as parameter. So far so good. Then in the Update function of the Turret I call a function Shoot(), which has that level parameter it got at the moment I created it.

But from that moment it gives the following error:

> **Inconsistent accessibility: parameter type 'Space\_Game.Level' is less accessible than method 'Space\_Game.GameObject.Shoot(Space\_Game.Level, string)'**

All I know it has something to do with not thr right protection level or something like that.

The level class:

```
    public Level(Game game, Viewport viewport)
    {
        _game = game;
        _viewport = viewport;
        _turret = new Turret(_game, "blue", this);
        _turret.SetPosition((_viewport.Width / 2).ToString(), (_viewport.Height / 2).ToString());
    }

```

The Turret Class:

```
        public Turret(Game game, String team, Level level)
        :base(game)
    {
        _team = team;
        _level = level;

        switch (_team)
        {
            case "blue":
                _texture = LoadResources._blue_turret.Texture;
                _rows = LoadResources._blue_turret.Rows;
                _columns = LoadResources._blue_turret.Columns;
                _maxFrameCounter = 10;
                break;
            default:
                break;
        }

        _frameCounter = 0;
        _currentFrame = 0;
        _currentFrameMultiplier = 1;
    }

    public override void Update()
    {
        base.Update();

        SetRotation();
        Shoot(_level, "turret");
    }

```

The Shoot Function (Which is in GameObject class. The Turret Class inherited the GameObject Class. (Am I saying that right?)):

```
protected void Shoot(Level level, String type)
    {
        MouseState mouse = Mouse.GetState();
        if (mouse.LeftButton == ButtonState.Pressed)
        {
            switch (_team)
            {
                case "blue":
                    switch (type)
                    {
                        case "turret":
                            TurretBullet _turretBullet = new TurretBullet(_game, _team);
                            level.AddProjectile(_turretBullet);
                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    break;
            }
        }
    }

```

# Answer
> 3 votes
What you pasted as Level class is just public constructor, you probably have something like this

```
class Level

```

when you should have

```
public class Level

```

explanation: someone could use your Turret class from their assembly, and inherit from it, at that point they could call Shoot method (because its protected, so only inherited types can call it), but they do not have access to Level class, since it was not public (therefore not avaliable in different assembly)

---
Tags: xna
---