title: Concatenate variable name

text:
# Question
Title: Concatenate variable name
I am hoping to save lines of code by concatenating a counter ( 0 to 9 ) with the first part of a variable name (num) to identify num0, num1, num2, etc in a loop using XNA. Can I do this ?

# Answer
It's a bit hard to be sure without more context, but it sounds like you should be using an array rather than many individual variables. For example:

```
int[] numbers = { 2, 4, 6, 8, 10 };       // Create an array of 5 integers
for (int i = 0; i < numbers.Length; i++)
{
    // The square brackets allow you to access individual elements by index
    System.Console.WriteLine(numbers[i]);
}

```

However, if your loop is simply iterating over all the elements in your array, it would be cleaner to use the `foreach` statement:

```
foreach (int num in numbers)
{
    System.Console.WriteLine(num);
}

```

If this is new to you, I'd suggest reading up on C# arrays. Here are a couple of links to get you started: http://msdn.microsoft.com/en-us/library/9b9dty7d.aspx and http://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx
> 5 votes

---
Tags: xna
---


title: Color Picking Troubles - LWJGL/OpenGL

text:
# Question
Title: Color Picking Troubles - LWJGL/OpenGL
I'm attempting to check which object the user is hovering over. While everything seems to be just how I'd think it should be, I'm not able to get the correct color due to the second time I draw (without picking colors). Here is my rendering code:

```
public void render() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    camera.applyTranslations();

    scene.pick();

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    camera.applyTranslations();

    scene.render();
}

```

And here is what gets called on each block/tile on "scene.pick()":

```
public void pick() {
    glColor3ub((byte) pickingColor.x, (byte) pickingColor.y, (byte) pickingColor.z);
    draw();

    glReadBuffer(GL_FRONT);
    ByteBuffer buffer = BufferUtils.createByteBuffer(4);
    glReadPixels(Mouse.getX(), Mouse.getY(), 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

    int r = buffer.get(0) & 0xFF;
    int g = buffer.get(1) & 0xFF;
    int b = buffer.get(2) & 0xFF;

    if(r == pickingColor.x && g == pickingColor.y && b == pickingColor.z) {
        hovered = true;
    } else {
        hovered = false;
    }
}

```

I believe the problem is that in the method of each tile/block called by scene.pick(), it is reading the color from the regular drawing state, after that method is called somehow. I believe this because when I remove the "glReadBuffer(GL\_FRONT)" line from the pick method, it seems to almost fix it, but then it will also select blocks behind the one you are hovering as it is not only looking at the front.

If you have any ideas of what to do, please be sure to reply!/

EDIT: Adding scene.render(), tile.render(), and tile.draw()

scene.render:

```
public void render() {
    for(int x = 0; x < tiles.length; x++) {
        for(int z = 0; z < tiles.length; z++) {
            tiles[x][z].render();
        }
    }
}

```

tile.render:

```
public void render() {
    glColor3f(color.x, color.y, color.z);
    draw();
    if(hovered) {
        glColor3f(1, 1, 1);
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
        draw();
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    }
}

```

tile.draw:

```
public void draw() {
    float x = position.x, y = position.y, z = position.z;

    //Top
    glBegin(GL_QUADS);
    glVertex3f(x, y + size, z);
    glVertex3f(x + size, y + size, z);
    glVertex3f(x + size, y + size, z + size);
    glVertex3f(x, y + size, z + size);
    glEnd();

    //Left
    glBegin(GL_QUADS);
    glVertex3f(x, y, z);
    glVertex3f(x + size, y, z);
    glVertex3f(x + size, y + size, z);
    glVertex3f(x, y + size, z);
    glEnd();

    //Right
    glBegin(GL_QUADS);
    glVertex3f(x + size, y, z);
    glVertex3f(x + size, y + size, z);
    glVertex3f(x + size, y + size, z + size);
    glVertex3f(x + size, y, z + size);
    glEnd();

```

}

(The game is like an isometric game. That's why I only draw 3 faces.)

# Answer
> 2 votes
It is hard to say exactly what is broken, but I can make a few suggestions.

1. Generally, the front buffer is what is currently shown, and drawing calls that are being processed are drawn to the back buffer. Once the entire scene is rendered, the back buffer is copied to the front buffer. Therefore I think that you should read from the back buffer, because the front buffer will always contain the final scene, where you have drawn over the colors you want to pick from. (i.e. change your call for glReadBuffer(GL\_FRONT) to glReadBuffer(GL\_BACK)).
2. Antialiasing (multisampling and supersampling) and transparency must be disabled for color picking to work. The colors you are picking from encode object IDs, and it does not make sense to blend IDs.
3. Make sure that the drawing calls are flushed before reading. This may be implied by the pixel reading commands, and may not. It may be good to add an explicit flush command to make sure for debugging at least.

---
Tags: opengl, rendering, lwjgl, color, picking
---


# Question
Title: How to Handle frame rates and synchronizing screen repaints
I would first off say sorry if the title is worded incorrectly.

Okay now let me give the scenario

I'm creating a 2 player fighting game, An average battle will include a Map (moving/still) and 2 characters (which are rendered by redrawing a varying amount of sprites one after the other).

Now at the moment I have a single game loop limiting me to a set number of frames per second (using Java):

```
Timer timer = new Timer(0, new AbstractAction() {

    @Override
    public void actionPerformed(ActionEvent e) {
        long beginTime; //The time when the cycle begun
        long timeDiff; //The time it took for the cycle to execute
        int sleepTime; //ms to sleep (< 0 if we're behind)
        int fps = 1000 / 40;

        beginTime = System.nanoTime() / 1000000;

        //execute loop to update check collisions and draw
        gameLoop();

        //Calculate how long did the cycle take
        timeDiff = System.nanoTime() / 1000000 - beginTime;

        //Calculate sleep time
        sleepTime = fps - (int) (timeDiff);

        if (sleepTime > 0) {//If sleepTime > 0 we're OK
                ((Timer)e.getSource()).setDelay(sleepTime);
        }
    }
});
timer.start();

```

in `gameLoop()` characters are drawn to the screen ( a character holds an array of images which consists of their current sprites) every `gameLoop()` call will change the characters current sprite to the next and loop if the end is reached.

But as you can imagine if a sprite is only 3 images in length than calling `gameLoop()` 40 times will cause the characters movement to be drawn 40/3=13 times. This causes a few minor anomilies in the sprited for some charcters

So my question is how would I go about delivering a set amount of frames per second in when I have 2 characters on screen with varying amount of sprites?

# Answer
It may not be a direct answer to your question, but it is my advice ;)

Do not move your sprites based on the number of frames, but do it based on wall-clock time. Why? Oh well, it is very easy for a game to have a variable frame-rate, so, imagine your character is jumping from platform to platform, and the PC lags for some reason. If his movement is based on frame-rate, he could slow down in middle jump and die :( Prepare to be murdered by the player on the next day.

So, the idea behind a time based game logic is: no matter the amount of FPS the game is currently running, the results will be the same for the user, with the only variation the screen being "janky" :P

This post (Link!!!) may help implement a time based game logic o/

Hope it was helpful and sorry if it was not the answer you seek...

Edit: There is a question in this sites FAQ regarding this, very interesting read: When should I use a fixed or variable time step?
> 8 votes

# Answer
You might want to consider using a variable frame rate. This way, you can cap the framerate at whatever the monitor's refresh rate is without changing the speed of the game.

AranHase has a valid point about glitches resulting from variable frame rates, but you can avoid this by skipping the update loop if the time between the current and previous frame is too high.
> 5 votes

# Answer
You're using Sleep calls to control your framerate - this is a BAD idea and you should get a proper timer in as mentioned in the other responses; I'll elaborate some on use of Sleep for this.

The big problem with Sleep is that on most platforms it only guarantees a *minimum* time to sleep for - the actual time spent in a Sleep may be longer than that. This is true even if you use Sleep with a high resolution timer.

There are plenty of questions and answers on this site relating to this; see https://gamedev.stackexchange.com/search?q=sleep and see especially http://www.altdevblogaday.com/2012/06/05/in-praise-of-idleness/ for a more in-depth discussion on the evilness of Sleep (among other things).

So the main thing to expect if using Sleep is framerate anomalies galore.

What Sleep is *great* for is reducing CPU usage, and if that goal is more important to you than an even framerate, then by all means go for it, but not before considering if you have more appropriate solutions available.
> 1 votes

---
Tags: java, sprites, spritesheet, frame-rate
---


# Question
Title: Adding Vertices to a dynamic mesh via Method Call
I have a C# Struct with a static method, "Get Shape" which populates a List with the vertices of a polyhedron.

Method Signature:

```
public static void GetShape(Block b, int x, int y, int z,
                                List<Vector3> vertices, List<int> triangles,
                                List<Vector2> uvs, List<Vector2> uv2s)

```

Adding directly to the `vertices` list (via `vertices.Add(vector3)` ), the code works as expected, and the new polyhedron appears when I trigger the method. However, I want to do some processing on the vertices I'm adding (a rotation), and the most sensible way I can think to do that is by creating a separate list of Vector3s, and then combining the lists when I'm done.

However,

`vertices.AddRange(newVerts)` does not add the shape to the mesh, nor does a foreach loop with `verts.Add(vertices[i])`. And this is before I've added in any of the processing!

I have a feeling this might stem from passing the list of vertices in as a parameter, rather than returning a list and then adding to the vertices in the calling object, but since I'm filling 4 lists, I was trying to avoid having to create a data struct to return all four at once.

Any ideas? The *working* version of the method is reprinted below, in full:

```
public static void GetShape(Block b, int x, int y, int z,
                            List<Vector3> vertices, List<int> triangles,
                            List<Vector2> uvs, List<Vector2> uv2s)
{
    //List<Vector3> vertices = new List<Vector3>();

    int l_blockShape = b.blockShape;
    int l_blockType  = b.blockType;
    //CheckFace checks if the block is empty
    //if this block is empty, don't draw anything.

    int vertexIndex;

    //only y faces need to be hidden.
    //if((l_blockShape & BlockShape.NegZFace) == BlockShape.NegZFace)
    {
        vertexIndex = vertices.Count;
        //top left, top right, bottom right, bottom left
        vertices.Add(new Vector3(x+.2f, y + 1, z+.2f));
        vertices.Add(new Vector3(x+.8f, y + 1, z+.2f));
        vertices.Add(new Vector3(x+.8f, y , z+.2f));
        vertices.Add(new Vector3(x+.2f, y , z+.2f));

        // first triangle for the face
        triangles.Add(vertexIndex);
        triangles.Add(vertexIndex+1);
        triangles.Add(vertexIndex+3);

        // second triangle for the face
        triangles.Add(vertexIndex+1);
        triangles.Add(vertexIndex+2);
        triangles.Add(vertexIndex+3);

        //UVs for the face
        uvs.Add( new Vector2(0,1));
        uvs.Add( new Vector2(1,1));
        uvs.Add( new Vector2(1,0));
        uvs.Add( new Vector2(0,0));

        //UV2s (lightmapping?)
        uv2s.Add( new Vector2(0,1));
        uv2s.Add( new Vector2(1,1));
        uv2s.Add( new Vector2(1,0));
        uv2s.Add( new Vector2(0,0));
    }

    //XY Z+1 face
    //if((l_blockShape & BlockShape.PosZFace) == BlockShape.PosZFace)
    {
        vertexIndex = vertices.Count;
        //top left, top right, bottom right, bottom left
        vertices.Add(new Vector3(x+.8f, y + 1, z+.8f));
        vertices.Add(new Vector3(x+.2f, y + 1, z+.8f));
        vertices.Add(new Vector3(x+.2f, y , z+.8f));
        vertices.Add(new Vector3(x+.8f, y , z+.8f));

        // first triangle for the face
        triangles.Add(vertexIndex);
        triangles.Add(vertexIndex+1);
        triangles.Add(vertexIndex+3);

        // second triangle for the face
        triangles.Add(vertexIndex+1);
        triangles.Add(vertexIndex+2);
        triangles.Add(vertexIndex+3);

        //UVs for the face
        uvs.Add( new Vector2(0,1));
        uvs.Add( new Vector2(1,1));
        uvs.Add( new Vector2(1,0));
        uvs.Add( new Vector2(0,0));

        //UV2s (lightmapping?)
        uv2s.Add( new Vector2(0,1));
        uv2s.Add( new Vector2(1,1));
        uv2s.Add( new Vector2(1,0));
        uv2s.Add( new Vector2(0,0));
    }

    //ZY face
    //if((l_blockShape & BlockShape.NegXFace) == BlockShape.NegXFace)
    {
        vertexIndex = vertices.Count;
        //top left, top right, bottom right, bottom left
        vertices.Add(new Vector3(x+.2f, y + 1, z+.8f));
        vertices.Add(new Vector3(x+.2f, y + 1, z+.2f));
        vertices.Add(new Vector3(x+.2f, y , z+.2f));
        vertices.Add(new Vector3(x+.2f, y , z+.8f));

        // first triangle for the face
        triangles.Add(vertexIndex);
        triangles.Add(vertexIndex+1);
        triangles.Add(vertexIndex+3);

        // second triangle for the face
        triangles.Add(vertexIndex+1);
        triangles.Add(vertexIndex+2);
        triangles.Add(vertexIndex+3);

        //UVs for the face
        uvs.Add( new Vector2(0,1));
        uvs.Add( new Vector2(1,1));
        uvs.Add( new Vector2(1,0));
        uvs.Add( new Vector2(0,0));

        //UV2s (lightmapping?)
        uv2s.Add( new Vector2(0,1));
        uv2s.Add( new Vector2(1,1));
        uv2s.Add( new Vector2(1,0));
        uv2s.Add( new Vector2(0,0));
    }

    //ZY X+1 face
//  if((l_blockShape & BlockShape.PosXFace) == BlockShape.PosXFace)
    {
        vertexIndex = vertices.Count;
        //top left, top right, bottom right, bottom left
        vertices.Add(new Vector3(x+.8f, y + 1, z+.2f));
        vertices.Add(new Vector3(x+.8f, y + 1, z+.8f));
        vertices.Add(new Vector3(x+.8f, y , z+.8f));
        vertices.Add(new Vector3(x+.8f, y , z+.2f));

        // first triangle for the face
        triangles.Add(vertexIndex);
        triangles.Add(vertexIndex+1);
        triangles.Add(vertexIndex+3);

        // second triangle for the face
        triangles.Add(vertexIndex+1);
        triangles.Add(vertexIndex+2);
        triangles.Add(vertexIndex+3);

        //UVs for the face
        uvs.Add( new Vector2(0,1));
        uvs.Add( new Vector2(1,1));
        uvs.Add( new Vector2(1,0));
        uvs.Add( new Vector2(0,0));

        //UV2s (lightmapping?)
        uv2s.Add( new Vector2(0,1));
        uv2s.Add( new Vector2(1,1));
        uv2s.Add( new Vector2(1,0));
        uv2s.Add( new Vector2(0,0));
    }

    //ZX face
    if((l_blockShape & BlockShape.NegYFace) == BlockShape.NegYFace)
    {
        vertexIndex = vertices.Count;
        //top left, top right, bottom right, bottom left
        vertices.Add(new Vector3(x+.8f, y , z+.8f));
        vertices.Add(new Vector3(x+.8f, y , z+.2f));
        vertices.Add(new Vector3(x+.2f, y , z+.2f));
        vertices.Add(new Vector3(x+.2f, y , z+.8f));

        // first triangle for the face
        triangles.Add(vertexIndex+3);
        triangles.Add(vertexIndex+1);
        triangles.Add(vertexIndex);

        // second triangle for the face
        triangles.Add(vertexIndex+3);
        triangles.Add(vertexIndex+2);
        triangles.Add(vertexIndex+1);

        //UVs for the face
        uvs.Add( new Vector2(0,1));
        uvs.Add( new Vector2(1,1));
        uvs.Add( new Vector2(1,0));
        uvs.Add( new Vector2(0,0));

        //UV2s (lightmapping?)
        uv2s.Add( new Vector2(0,1));
        uv2s.Add( new Vector2(1,1));
        uv2s.Add( new Vector2(1,0));
        uv2s.Add( new Vector2(0,0));
    }

    //ZX + 1 face
    if((l_blockShape & BlockShape.PosYFace) == BlockShape.PosYFace)
    {
        vertexIndex = vertices.Count;
        //top left, top right, bottom right, bottom left

        vertices.Add(new Vector3(x+.8f, y+1 , z+.2f));
        vertices.Add(new Vector3(x+.8f, y+1 , z+.8f));
        vertices.Add(new Vector3(x+.2f, y+1 , z+.8f));
        vertices.Add(new Vector3(x+.2f, y+1 , z+.2f));

        // first triangle for the face
        triangles.Add(vertexIndex+3);
        triangles.Add(vertexIndex+1);
        triangles.Add(vertexIndex);

        // second triangle for the face
        triangles.Add(vertexIndex+3);
        triangles.Add(vertexIndex+2);
        triangles.Add(vertexIndex+1);

        //UVs for the face
        uvs.Add( new Vector2(0,1));
        uvs.Add( new Vector2(1,1));
        uvs.Add( new Vector2(1,0));
        uvs.Add( new Vector2(0,0));

        //UV2s (lightmapping?)
        uv2s.Add( new Vector2(0,1));
        uv2s.Add( new Vector2(1,1));
        uv2s.Add( new Vector2(1,0));
        uv2s.Add( new Vector2(0,0));
    }
}

```

# Answer
> 0 votes
So after more experimentation, I found out what was wrong. TOAOGG is, unfortunately, wrong - the lists were being passed appropriately (else the posted code wouldn't have worked). Instead, the problem is here:

```
    vertexIndex = vertices.Count;

```

and also here:

```
    // first triangle for the face
    triangles.Add(vertexIndex);
    triangles.Add(vertexIndex+1);
    triangles.Add(vertexIndex+3);

    // second triangle for the face
    triangles.Add(vertexIndex+1);
    triangles.Add(vertexIndex+2);
    triangles.Add(vertexIndex+3);

```

The vertices were always being added correctly, but their associated triangles were not pointing to them correctly. Here is the correct code (assuming input parameter verts):

```
int parentIndex = verts.Count;
vertexIndex = vertices.Count;

// first triangle for the face
   triangles.Add(parentIndex+vertexIndex);
   triangles.Add(parentIndex+vertexIndex+1);
   triangles.Add(parentIndex+vertexIndex+3);

// second triangle for the face
   triangles.Add(parentIndex+vertexIndex+1);
   triangles.Add(parentIndex+vertexIndex+2);
   triangles.Add(parentIndex+vertexIndex+3);

```

So... lesson learned. Keep your triangles between the proper vertices!

# Answer
> 1 votes
I'm not sure if I got the question correct but is it correct, that you want to edit the vertices you passed as a parameter to the function after calling the function?

Maybe call by reference could help. You could try

---

```
public static void GetShape(Block b, int x, int y, int z,
                        ref List<Vector3> vertices, ref List<int> triangles,
                        ref List<Vector2> uvs, ref List<Vector2> uv2s)

```

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


# Question
Title: Making a Photo Hunt Game using Javascript and HTML5
I am looking for a way to make a photo hunt game using HTML5 and Javascript. Where should I start after the images. And How would I make clickable areas on the image, using javascript? If you know of any examples that would help or are willing to help let me know, please. Thank You

# Answer
> 0 votes
To create Photo Hunt Game using Javascript and HTML5, You should have good knowledge on

**hidden object**

**tag map**

**How to preload image**

**Further, You have to choose a better JavaScript Library or Game Engine to develop you game**

---
Tags: javascript, html5, browser-based-games
---


# Question
Title: Re-sizing the form without scaling the GUI
I am writing a turn based strategy game in C#. My GUI implementation consists of class that extends Form containing a class that extends Panel. When I render the GUI I draw to the paint method in the panel.

I am trying to figure out what is the best way for handling form re-size events. I know I want a minimum window size, but I would prefer to not have a maximum or a set size.

Ideally the GUI would reveal more/less of the map as the user changes the window size. I would like to avoid scaling the graphics if at all possible.

What is the best way to handle re-size events?

# Answer
> 0 votes
The best way I know of would be to redraw your screen on resize and determine the number of map tiles to draw based on the current width and height of your form. Just make sure you anchor your display panel to all sides of the form (which forces it to scale with the form)

```
private void MapForm_Resize(object sender, EventArgs args)
{
    Draw();
}

private void Draw()
{
    // you said you used a panel to display stuff
    // The +1 is incase you have a partial tile that needs to be displayed,
    // this is really only needed if you glide the camera rather than snapping.
    int tilesInXDirection = 1 + displayPanel.width  / tileWidth;
    int tilesInYDirection = 1 + displayPanel.height / tileHeight;

    for (int x; x < tilesInXDirection ; x++)
    {
        for (int y; y < tilesInYDirection ; y++)
        {
            // Draw your tiles based on current location
        }
    }
}

```

# Answer
> 0 votes
Well in C#, use the built in events system and then when the panel is resized simply loop through all of the controls and adjust based on parameters that you want

---
Tags: c#, windows-forms
---


title: Making A Game Manager C#

text:
# Question
Title: Making A Game Manager C#
Is it possible to make a game manager like steam (without the downloads just something that lists your games) in C#?

I'm just not sure what the .NET framework can do.

# Answer
Yes, of course it's possible. You can do just as much with C# as you can do with any other language (which is just about anything).

Most programming languages you find will be Turing complete, which effectively means you can always do with one what you can do with another. The only real difference is the way you can approach those problems with the given language, and what libraries are available. Since C# and the .NET framework have a tremendous variety of libraries available, there are not many limits there.
> 4 votes

---
Tags: c#
---


title: C# XNA Make rendered screen a texture2d

text:
# Question
Title: C# XNA Make rendered screen a texture2d
I am working on a cool little city generator which makes cities in the isometric perspective. However, a problem arose where if the grid size was over a certain limit it would have awful lag. I found the main problem to be in the draw method. So I took the precautionary step of rendering only items that were onscreen. This fixed the lag but, not by much.

The idea I have is to render the frame once and take a snapshot. Then, display that as a texture2d on screen. This way I don't have to render 1,000,000 objects every frame since they don't change anyways.

TL;DR - I want to

1. Take a snapshot of an already rendered frame
2. Turn it into a Texture2D
3. Render that to the screen instead of all the objects.

Any help appreciated.

# Answer
> 3 votes
Another method would be using `RenderTargets` which would basically consist of these steps

1. Create a render target A
2. Set A on the device
3. Render everything you want
4. Unset A
5. You can now use A as a texture (render targets inherit from Texture2D).

The advantage of this is that it works on the Xbox 360 and Windows Phone as well (the screenshot approach by Marton doesn't).

You can find a small tutorial I found that explains the steps more in detail here

# Answer
> 0 votes
1. Take a snapshot with the `GraphicsDevice.GetBackBufferData` method.
2. Load the resulting data into a `Texture2D` with the `Texture2D.SetData` method.
3. Render the Texture2D.

Example: Taking a screenshot using XNA 4.0

---
Tags: xna
---


# Question
Title: How can I tell whether an object is moving CW or CCW around a connected path?
Lets say we have a jagged shape:

And two creatures moving along it's outline.

Then we smooth the shape completely by pulling the corners out.

We get this:

It is easy to see now that Orange is moving CW and green CCW. How can I tell in which direction they are moving without smoothing out the shape?

New image

# Answer
Draw a line to infinity and count how many times you cross the shape (even or odd), not counting the segment where the creature lies. Then check whether the creature is going left or right of that line.

In this example, we cross the shape twice (so even) and we go to the left. The result is immediate from this table:

```
   # Crosses | even  | odd
  Direction  |       |
-------------+-------+------
    left     | CCW   |  CW
    right    |  CW   | CCW

```

In pseudocode:

```
x, y = position of creature
vx, vy = direction of creature movement
crossings = 0
for each x1, y1, x2, y2 in shape segments:
    if (x1 < x and x <= x2) or (x2 < x and x <= x1):
        if y - y1 > (x - x1) * (y2 - y1) / (x2 - x1):
            ++crossings
if (crossings & 1) == (vx < 0):
    return CW
else
    return CCW

```
> 27 votes

# Answer
It depends on what information you have available from your shape data structure, but a creature moving CW along the outline of a shape will always have the inside of the shape on its right, and a creature moving CCW will have the inside of the shape on its left.
> 5 votes

# Answer
1. Calculate the center point of your shape.
2. Pick the most distant edge of your shape from the center.
* *(Picking the most distant edge ensures that you don't start from an inverted, concave part of the shape, which would result in getting the clockwise/anticlockwise determination backward for the whole shape)*
3. Determine which direction along that edge is clockwise
    * *(A simple implementation of this would involve comparing the angles from the center of the shape to each end of the selected edge. The sign of the difference between the angles will tell your clockwise vs. counter-clockwise)*
4. Iterate over all the edges of the shape, starting from the edge you picked in step 2, building a list of edges. For each edge, store its two vertices in clockwise order.
* *(If your shape isn't changing over time, then you can store this edge list for later use, so you don't have to do the first four steps every frame)*
    * *(you may already have an edge list. If so, you can store this clockwise vertex order in that same list.)*
5. To determine whether an entity is moving clockwise or anticlockwise:
    * Determine which edge the entity is moving along.
    * Do a dot product of the entity's direction of movement against the vector from that edge's clockwise start-\>end vertices which you determined back in step 4.
    * If the result of the dot product is a value greater than zero, the entity is moving clockwise. Less than zero means anticlockwise.
> 4 votes

# Answer
You need to know which way round the polygon is defined, which way the vertices go round it.

If you don't know this, you can work it out by calculating the area of the polygon:

```
float Polygon::area() {
    float result = 0.0f;

    for(int a = 0; a < vertexCount; a ++) {
        int b = (a+1) % vertexCount;
        result += vertices[a].x * vertices[b].y;
        result -= vertices[a].y * vertices[b].x;
    }

    return result * .5f;
}

```

The **sign** of the result (positive or negative) will tell you whether it is clockwise or anticlockwise. You need to try this to see which way round it is for you because it depends on your coordinate system.

If the shape is clockwise:

* A creature going **forward** round the shape is going **clockwise**, and
* A creature going **backward** round the shape is going **anticlockwise**.

If the shape is anticlockwise:

* A creature going **forward** round the shape is going **anticlockwise**, and
* A creature going **backward** round the shape is going **clockwise**.
> 2 votes

# Answer
It seems Trevor already covered this question, but here is my solution:

1. compute the area your shape covers, meaning

```
area = 0
foreach (edge in shape)
    area += edge.begin.x * edge.end.y - edge.begin.y * edge.end.x

```
2. using area computed as above you can easily tell if the shape itself is clockwise or not. it's clockwise only if area is below zero.
3. check if object(s) is(are) moving the same way as vertices are order or in the opposite direction.
> 0 votes

---
Tags: geometry
---


# Question
Title: Moving camera, or camera with discrete "screens"?
I'm making a game with a friend, but having trouble deciding on a camera style.

The basic idea for the game, is having a randomly generated 2-dimensional world, with settlements in it. These settlements would have access to different resources, and it would be the job of the player to create bridges and ladders and links between these villages so they can trade. The player would advance personally by getting better gear, fighting monsters and looking for materials in the world, in order to craft and trade them at the settlements.

My friend wants to use an old-style camera, where the world is split into a discrete number of screens that the player moves between. Similar to early Zelda dungeons, or Knytt Stories. This is opposite to me, as I want a standard camera that follows the player around as I feel the split-screen style camera limits the game.

Can anyone argue the case either way? We've hit a massive roadblock here and can't seem to get past it.

# Answer
Within this genre (and this is true of most other currently popular genres as well), the camera is the most important thing defining what happens in your game.

A freely scrolling camera is good for selling a wide sense of space, and making everything feel continuous. Challenges involve enemies attacking from off-screen, and players missing features of the world which you'd intended for them to discover, just because the player happened to wander a little too far to one side or the other.

Fixed cameras are good for ensuring a consistent play experience. When correctly corralled, you can ensure that every player will see the same screens, and the same features of the world. Which means that players won't miss things the same way that they can in freely scrolling worlds. Fixed cameras are good for delivering bite-sized individual challenges (as in individual rooms in Zelda), where monsters from one room can't interfere with the desired challenge of other rooms. Fixed cameras are also conducive to having a chunky "grid" layout, which makes it really easy to show players a map of what they have and haven't explored yet, which can be a lot harder to communicate when you have a freely scrolling camera. Cons of fixed cameras is that you have to constrain enemies within the view of the fixed cameras (players will consider it unfair to be attacked by enemies they can't see), and that you really need to standardise on a single aspect ratio for your game, so you can be sure that everyone sees the same things from each camera, no matter whether their screens are 4:3 or 16:9. (ie: letterboxing or pillarboxing will be required, in full-screen modes)

If your game is about exploration and/or collecting things, you probably want a fixed camera. If you want the game to be about solving puzzles, you probably want a fixed camera. If your game is about quick reflex challenges, you probably want a fixed camera. If your game is more procedural (enemies are smarter and can chase the player over long distances), then a scrolling camera is what you want. If you don't want to carefully design individual encounters, a scrolling camera is what you want.

Either sort of camera will work. But depending on which sort of camera you make, different types of game mechanics will be more or less effective. So decide what you want the player to do in your game, and then pick the style of camera that's most appropriate for the game you're making.
> 4 votes

# Answer
I think it comes down to personal opinion, mostly. If you want a specific type of gameplay, that might influence your choice as well. Say, if you wanted the story to be split up in small segments, you might want the "split-screen" style. Or for a game like Binding of Isaac, where each room is a fight.

From what you describe, it seems like you want the gameplay to be pretty continuous. I would probably go with the camera following the player, but as I said, this really comes down to opinion.
> 1 votes

# Answer
Personally I would prefer the dynamic camera:

If your game-world (and therefore the position of your settlements and resource-points) is generated randomly, you will probably end up having two things that you want to watch at the same time on two different screens. With discrete screens, you now have to constantly run back and forth if you want to keep an eye on both things. With a scrolling camera you could move to the half way point and see them both.

What are your friend's reasons for wanting discrete screens?

Is it because they're easier to implement? - That might be true, but a smoothly scrolling camera is worth the effort. It can add a lot of juice to your game. And you have a nice forum here where you can ask for help :-)

Is it because you wouldn't need resources for more than one screen at a time? - Consider splitting your game-world up in tiles and only render enough of them to fill the screen.

Is it personal preference? - How about a compromise: Place focus-points at places of the map that are of interest (for example your randomly placed settlements) and make the camera smoothly snap to them if the player gets close. Otherwise make it follow the player.

Here's an example of what I mean: http://www.youtube.com/watch?v=aAKwZt3aXQM
> 1 votes

# Answer
The choice between a discrete set of screens and a continuously moving camera is really a question of level design and core gameplay more than it is camera style.

By having your camera move discretely between screens you are partitioning your world into many small arenas - while the player is able to move freely around within the arena, moving to another arena or screen is a more deliberate action that would normally be associated with some sort of minor significance, for example

* Monsters may be spawned at the point where you enter the area, and typically would not be able to follow you to the next arena
* The game might save or reset the arena when you enter an arena, for example VVVVV resets all destroyed platforms whenever you leave and enter an arena which also allows some very clever puzzles
* Often the edge of the screen represents a boundary in the game (e.g. a wall if indoors or a cliff face if outdoors)
* Discrete screens also give a more "Retro" feel for your game
* Moving to another arena often provides sense of progress and accomplishment for the player

Conversely by using a continuous camera you are creating one continuous flowing world as opposed to a discrete set of interconnected places.

* This is likely to give the player a greater sense of freedom
* Enimies might be able to follow the player indefinitely

Of all the games I can think of those with discrete screens are typically more puzzle based (e.g. the early Zelda games and VVVVV), wheras those with continuously moving cameras are more action / RPG based (e.g. Cave Story and Terraria). You could also use a hybrid approach where certain parts of the world are partitioned into discrete screens while other parts have a continuously moving camera, again VVVVV uses this with great effect in a couple of sections of the game.

Although many early games had discrete screens largely for technical reasons I wouldn't say that discrete screens are any worse (or better) than a continuous camera, they simply give a different feel to the game (and allow for some interesting gameplay mechanics).

Essentially its all down to your level design and gameplay. You should talk to your friend to ask what he had in mind with regard to these discrete screens - unless you are going to use these discrete screens for some sort of gameplay mechanic it sounds like you would probably be better off with a continuously moving camera.
> 1 votes

---
Tags: 2d, game-design, camera
---


# Question
Title: Is It More Efficient To Make Games In Languages I Like?
Is it more "efficient" to develop games with languages you're good with and like best rather then the "best" language?

For example: I like C# (It's My First Language) and I'm really good at it and used to how it works. I'm not as good with C++; I'm kinda slow at it because I don't prefer how the systems work, like I think int a\[\] is not as good as int\[\] a.

Would it be better to go with what I know best or what's the "best" available?

# Answer
There isn't really a "best" language to use for game development. What goes into the consideration of a language is what your target platform is, what criteria your architecture must meet, and, yes, what your preference is.

For example, if you are developing for an Apple product, you might benefit from using Objective-C. If speed is paramount (perhaps you're doing something incredibly CPU-intensive, or even GPU-intensive and use some third-party library) then C++ is probably necessary. If you want to get something up and running as fast as you can, and would like to iterate quickly, then a scripting language is the way to go.

As far as workflow is concerned, things would indeed move faster if you choose a framework which is based in a language you are familiar with. That's not to say you shouldn't shy away from a challenge and learn the ins and outs of an entirely new language :) (but that's just my opinion).

To sum up: it depends on what your goals and requirements are, but if you're just starting out, I'd recommend using something you're familiar with.
> 3 votes

# Answer
Depends on what you like. Assembly would be a horribly inefficient language. PHP won't apply well to non-website games, C won't work well with browser games.

Generally, languages like C, C++, C#, Java are good mid-level languages that can create almost any kind of game well. Go as high level as you can, then move lower level when you need to optimize.

I'd recommend you decide exactly the requirements for the game first, then figure out if your language of choice can handle it. Chances are someone made an engine that does do it.
> 2 votes

# Answer
Read this answer first. It's about Java, but most points should apply to C# as well. You are asking two different question: first if it is more efficient to use favorite language and second is it better to go with it. Neither question has a direct answer.

## Is it more efficient to use my preferred language?

In my own experience if you don't run into bad obstacles, I would say yes. You can produce code faster and with less bugs. You have familiar toolchain and you can probably reuse more of your existing code. On the other hand there is a risk of running into problems which are not solved very well in your preferred language and you might end up spending quite a lot of time with the issue. Available libraries and platform integration such as installation process are examples of these kind of problems. You should try to research any potential issues beforehand to ensure that they won't cause big problems later on.

## Should I use my preferred language?

This really depends what you are doing, what are your goals and what is your team. Are you aiming to finish a commercial high-quality game? Are you making a game just for fun? Are you doing this on your own or are other programmers involved or how possible is it that others will join? What new do you want to learn while making the game? Do you want to be a little bit exotic in the choice of language? And also is your preferred language proven to be good enough for making high quality games? C# and many others have been, but not all languages have.

If you are doing this just for your own pleasure, choose what you like the most. I chose Java as I like it more than C++ and I've been very happy with the choice. It makes the development fun and you can better consentrate on actually programming the game.
> 2 votes

# Answer
It's always more efficient in terms of speedy development time to work in the languages that you are most familiar with, but there are frequently reasons to use other languages

* To learn another language
* Features of another language, for example, using Objective-C to target iOS
* Your team is using something else

I generally recommend using the best language for the target result, even if you are not the best at it, since you will get better with experience, and also important, when you get stuck on things, when you ask for help, you don't receive the reply "I don't know, I always use $other\_language!". However, if I am writing a quick-and-dirty program for myself, I'll usually write it with whatever seems easiest and quickest. It depends on how nice you want the result, and how much pain it is to do it the nonstandard way.

A random comment: if you are using C++, I recommend using std::vector (or any of the other containers) over int a\[\].
> 1 votes

# Answer
Programming languages are, in a sense, just tools. Use the one you're most proficient with and the one that makes the most sense for your project.

You obviously don't want to write a video game in COBOL. While you obviously can program anything in any programming language, it's more painful in some than others.

But yea. C# should be fine. Depending on the codebase (engines like Panda3D or the Dreaded engine -- the later formerly known as the id tech 4 CDK -- are written in C++, despite what language people code their games in) you should get performance close to or exactly the same as some of the fastest C++ game engines.
> 0 votes

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


title: Where to start? (3D Modeling)

text:
# Question
Title: Where to start? (3D Modeling)
I'm looking for a good resource to start learning 3d modeling. I'm looking for something that starts with the basics (e.g. terminology; what are *quads*, *triangles* etc.) before/while going into the actual modeling. Book, website, video, anything will do. I'm only concerned with the quality of the tutorials, how thorough they are. I have experience with texturing, level design and so on - but I've never created anything more than simple shapes/editing existing assets.

# Answer
> 8 votes
Check out some of these Blender tutorials by David Ward.

# Answer
> 3 votes
Learn theory before practice. Make sure you know what translate, rotate, scale, local, world, vertex, face, edge, UV, texture, specular, rendering, rigging etc means. Also make sure you understand the differences between various display modes (it took me a while to understand the difference between textured and untextured, especially in the start where you only use colors. This looks like a good glossary ( http://en.wikibooks.org/wiki/Blender\_3D:\_Noob\_to\_Pro/Glossary )

Do not look up tutorials like rigging before you have mastered an interface. I suggest going with a simple program first to understand the basics (like sketchup) then move up to a more full-featured software like Maya (avoid Blender to start with...many people will encourage you to learn Blender, but the fact is that if you learn Blender first, all the others will be difficult. Blender has a unique interface, very unlimited, whereas more "standard" packages are more rigid. Rigidness should not exist, but it is a standard.)

Learn standard Keyboard shortcuts (yes, they exist!) like W for move, E for rotate and R for scale...learn regular commands and what they do, like extrude, cut, soften, merge.

Then go for easy projects starting with Architecture tutorials (they are easier for beginners, mostly primitives), like a simple building. Then go for larger scale Arch tutorials like a city or a house with windows and a porch etc.

Then move to organic modelling, like face, hands, animals etc.

Then you can move to UVmapping, texturing, rigging, physics, particles, sfx etc! Good luck!

# Answer
> 2 votes
If you run through the Blender Noob to Pro series, you'll have a good foundation.

If you download the free 1-month trial of Maya, the Getting Started Guide is included, and will also provide a good foundation.

At the very least, one or both of those will give you the terminology you need to craft useful search phrases to find the rest of the topics you're searching for.

# Answer
> 2 votes
Well, I recommend you to seek for a professional in your environment or if not, try searching for a person on the Net. Actually, talking and learning face to face gave me a lot.

# Answer
> 2 votes
Check BlenderCookie for very good quality tutorials. From here you will find beginners tutorials to professional courses.

# Answer
> 1 votes
Just about any intro to 3D book will go over basics of terminology, so you should start by deciding which software you want to learn on. Despite the nearly religious fervor a lot of 3D artists have all the different options (3ds max, Maya, Blender, etc.) are about equally good for learning on, so just pick whichever is most convenient for you (eg. your school's computers already have it installed) and then go to the bookstore to get an intro book for that software.

Eventually you'll want to branch out in your learning and look at other tools, but from the very beginning you gotta pick one.

# Answer
> 1 votes
Take a peek at some of these tutorials by Neal Hirsig, all are short and concise video tutorials for 3d modeling in Blender, for an absolute beginner to Blender and likely to modeling. If you're unsure of a function or attribute name, just search Wikipedia for it-- learning the difference between a quad and a tri takes all of a few minutes at most.

# Answer
> 1 votes
I'am a beginner too. You can start here. It's got Autodesk 3ds Max and Unreal Development Kit (beginner to advance).

---
Tags: 3d
---


# Question
Title: OpenGLES GLSL Shader attributes always bound to 0
So I have a very simple vertex shader as follows

```
#version 120
attribute vec3 position;
attribute vec3 inColor;
uniform mat4 mvp;
varying vec3 fragColor;

void main(void){
    fragColor = inColor;
    gl_Position = mvp * vec4(position, 1.0);
}

```

Which I load, as well as the fragment shader:

```
#version 120
varying vec3 fragColor;

void main(void) {
    gl_FragColor = vec4(fragColor,1.0);
}

```

Which I then load, compile, and link to my shader program. I check for link status using

```
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &shaderSuccess);

```

which returns GL\_TRUE so I think its ok. However, when I query the active attributes and uniforms using

```
#ifdef DEBUG
        int totalAttributes = -1;
        glGetProgramiv(shaderProgram, GL_ACTIVE_ATTRIBUTES, &totalAttributes);
        for(int i=0; i<totalAttributes; ++i)  {
            int name_len=-1, num=-1;
            GLenum type = GL_ZERO;
            char name[100];
            glGetActiveAttrib(shaderProgram, GLuint(i), sizeof(name)-1,
                               &name_len, &num, &type, name );
            name[name_len] = 0;
            GLuint location = glGetAttribLocation(shaderProgram, name);
            fprintf(stderr, "Attribute %s is bound at %d\n", name, location);
        }
        int totalUniforms = -1;
        glGetProgramiv(shaderProgram, GL_ACTIVE_UNIFORMS, &totalUniforms);
        for(int i=0; i<totalUniforms; ++i)  {
            int name_len=-1, num=-1;
            GLenum type = GL_ZERO;
            char name[100];
            glGetActiveUniform(shaderProgram, GLuint(i), sizeof(name)-1,
                              &name_len, &num, &type, name );
            name[name_len] = 0;
            GLuint location = glGetUniformLocation(shaderProgram, name);
            fprintf(stderr, "Uniform %s is bound at %d\n", name, location);
        }
#endif

```

I get:

> Attribute inColor is bound at 0
>
> Attribute position is bound at 1
>
> Uniform mvp is bound at 0

Which leads to failure when trying to use the shader to render the objects. I have tried switching the order of declaration of position & inColor, but still, only position is bound with the other two giving 0

Can someone please explain why this is happening? Thanks

# Answer
> 2 votes
0 is a valid location index, with -1 being the signifier of an error; see: http://www.opengl.org/sdk/docs/man/xhtml/glGetUniformLocation.xml and http://www.opengl.org/sdk/docs/man/xhtml/glGetAttribLocation.xml.

If you support GL\_ARB\_explicit\_attrib\_location or GLSL 330+ I'd strongly recommend that you switch over to using "layout(location=" syntax for your VS input; this resolves a lot of confusion surrounding attrib locations. Unfortunately explicit uniform locations are GL4.3 only so they're not going to be a realistic option just yet.

Not sure how much of that is available on ES though.

If you're still getting rendering errors despite this then I'd suggest that the cause of your errors is most likely elsewhere. Some description of the errors as well as some more code (your glVertexAttribPointer calls would be particularly useful) would be needed to further diagnose.

---
Tags: c++, opengl, opengl-es, glsl, graphics-programming
---


# Question
Title: SDL2 with OpenGL -- weird results, what's wrong?
I'm porting an app to iOS, and therefore need to upgrade it to SDL2 from SDL1.2 (so far I'm testing it as an on OS X desktop app only). However, when running the code with SDL2, I'm getting weird results as shown on the second image below (the first image is how it looks with SDL, correctly). The single changeset that causes this is this one, do you see something obviously wrong there, or does SDL2 have some OpenGL nuances I'm unaware of? My SDL is based on the latest from HG.

**Update:** another question about the iOS port of the same project is here.

**Update 2:** this is now also on the SDL newsgroup: http://thread.gmane.org/gmane.comp.lib.sdl/58026

**Update 3:** I tried using Regal for portable OpenGL, the not-so-good result is on the third screenshot, produced merely by replacing

```
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>

```

with

```
#include "GL/Regal.h"
#include "GL/RegalGLU.h"

```

# Answer
> 7 votes
Heres your problem notice I comment out the surface = SDL\_Get... it was giving some weird results. Also you forgot to create the OpenGL context. Let me know if you have any other issues.

```
SDLWindow::SDLWindow(int width, int height, double axisLen, const std::string &caption)
:m_fov(axisLen)
,m_width(0)
,m_height(0)
,m_fps(0)
,m_idxSnapshot(0)
,m_camPos(0, 0, 2)
,m_camLookAt(0, 0, 0)
,m_camOrient(0, 1, 0)
,surface(NULL)
,m_texStar(0)
,m_bRunning(true)
{
SDL_GLContext ctx;

if (SDL_Init(SDL_INIT_VIDEO) < 0)
    throw std::runtime_error(SDL_GetError());
atexit(SDL_Quit);

SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 0 );
SDL_GL_SetAttribute( SDL_GL_RETAINED_BACKING, 1 );

 if ((window = SDL_CreateWindow(caption.c_str(), SDL_WINDOWPOS_CENTERED,
 SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN |
 SDL_WINDOW_BORDERLESS)) == NULL)
    throw std::runtime_error(SDL_GetError());

/*if ((surface = SDL_GetWindowSurface(window)) == NULL)
    throw std::runtime_error(SDL_GetError());*/

m_width = width;
m_height = height;

ctx = SDL_GL_CreateContext(window);

InitGL();
}

```

---
Tags: opengl, sdl, macos, porting
---


# Question
Title: Collision Detection Game Design and Architecture
I've reading some articles about collision detection. My question here is about ideas on the design for it.

Baically I have a C++ game that has a main loop with entities with an update method. Based on keyboard input, these characters updates their positions.

My question is not about how to detect collisions, it's about getting ideas in which is the best way to implement this. The game has a main character but also enemies that have to collide between them, so I'm not sure where to make all the iterations for checking collisions and if the right way is to check everything against everything.

Thanks in advance.

# Answer
Depends a bit how in depth you want to go. For simplicity I would suggest either a Observer Pattern for a CollisionDetector class or a simple Aggregation (the CollisionDetector has a reference to the world which contains everything)

Basically you would have to check everything against everything. In an optimization you could use a Sweep and Prune approach to reduce computation effort. If your game is simple and has not too many actors you can skip that though.

A simple implementation would look something like this:

```
class CollisionDetector:
  void Update():
    for gameobject in world:
      for otherGameobject in world:
        if gameobject == otherGameobject: continue

        collision = GetCollision(gameobject, otherGameobject)
        if collision:
          gameobject.Collide(collision)
          otherGameobject.Collide(collision)

```

of course the different collision detection approaches and the collision response need to depend on the colliding game objects.
> 10 votes

# Answer
Well. It's a matter of figuring out if:

1. There is no chance that these two objects collided
2. You don't need to know.

For 1, it's mostly a matter of distance. You'll still need to compare the positions of two objects, but if they're far from each other, you can safely assume that they're not colliding, thus saving a few calculations.

2 depends on your game. Like, if you're only calculating collision between enemies in order to not render them on top of each other, then you probably don't care about collision between enemies that are outside the screen.

You may also be able to completely ignore certain groups of objects - like, if you know that an entire, distinguished group of enemies are in the opposite end of the game world, you could just ignore those until the player gets closer - maybe even leave them out of your update loop, because they're *very* far away.
> 1 votes

# Answer
This will check each object against each other object once:

```
Object objects[];
for(i=0;i<objects.length;i++)
{
    for(j=i+1;j<objects.length;j++)
    {
        //check for collision between objects[i] and objects[j]
    }
}

```
> 0 votes

---
Tags: collision-detection, game-design, architecture, collision-resolution
---


# Question
Title: A methodology for creating simple sprite games (without programming technology)
Do you know a manual for creating simple sprite games (without programming technology)?

The manual should contain answers to questions like "How to invent the rules", "How to create a very attractive game", "How to force a user to play constantly".

# Answer
I don't think you'll find a real answer to your first two questions- "How to come up with rules" and "How to create a very attractive game" are all things that are going to change based on a lot of factors- who you're marketing to, what the goal of the game is, etc.

"How to force a user to play constantly"- I'm assuming that you're not actually meaning "force". Depending on what sort of game you're trying to build, the following articles could be of help:

http://www.video-game-addiction.org/what-makes-games-addictive.html http://www.gamingbus.com/2011/07/27/video-game-addiction-part-two-what-makes-games-addicting/

These two articles are written purposefully vague, because the answer will depend on what you're trying to accomplish.

This is my first-ever answer, I hope it's helpful!
> 3 votes

# Answer
http://www.amazon.com/Game-Design-Secrets-Fourth-Edition/dp/B000IQN4M2/ref=sr\_1\_2?ie=UTF8&qid=1352390875&sr=8-2&keywords=Game+Design+Marc+Saltzman

Still my favourite.

It goes into a lot of detail about how industry legends like Al Lowe design their puzzles or how the textures for Myst were made.

Definitely a great read.

Disclaimer: My opinion is based on an earlier edition from 1999. I don't know much about the newer editions.
> 1 votes

---
Tags: game-design, sprites, flash
---


title: Where can i get the openal sdk for c++?

text:
# Question
Title: Where can i get the openal sdk for c++?
The OpenAL site I'm looking at is a crappy outdated and broken sharepoint portal and the SDK in the downloads section give me a 500 html code when i request it.

http://connect.creativelabs.com/openal/Downloads/OpenAL11CoreSDK.zip

I found an OpenAL SDK on a softpedia and it has headers but not alu.h or alut.h which the tutorials I'm looking at apparently require for loading wavs etc.

What am I missing? Is OpenAL dead or something?

# Answer
http://kcat.strangesoft.net/openal.html is the OpenAL Soft library, which is what you use on almost every platform besides Windows by default anyway. It doesn't expose the hardware-accelerated EAX extensions, but not a lot of people use those. If the Creative Windows SDK doesn't come back online shortly, OpenAL Soft is the only real option remaining.

Not that this is an answer to your question, but... you might consider just using FMOD or Wwise. They are free for hobbyist usage and very reasonably priced for commercial usage, they have a bazillion and one more features than any version of OpenAL, have a much cleaner and less error-prone API, and have designed-oriented tools and support rather than being purely a low-level sound abstraction API.

While I don't know if OpenAL is dead on Creative's site permanently or it's just a hiccup, I really wouldn't be surprised if it was dead. It's very very rarely used in the industry commercially, and is decreasingly used in the indie/hobby scenes from what I've seen. The only platform that really stresses use of OpenAL anymore is Linux. Windows has its own API, iOS and OS X have their own APIs, the consoles have their APIs, and even Android prefers OpenSL over OpenAL. And of course, FMOD/Wwise abstract all those away and give you a single unified high-level API.
> 11 votes

# Answer
Try using the way back machine for the site on october 2, 2010

http://web.archive.org/web/20101002103140/http://connect.creativelabs.com/openal/downloads/forms/allitems.aspx
> 4 votes

---
Tags: openal
---


# Question
Title: Why do my 512x512 bitmaps look jaggy on Android OpenGL?
This is sort of driving me nuts, I've googled and googled and tried everything I can think of, but my sprites still look super blurry and super jaggy. Example:

Here: https://docs.google.com/open?id=0Bx9Gbwnv9Hd2TmpiZkFycUNmRTA

If you click through to the actual full size image you should see what I mean, it's like it's taking and average of every 5\*5 pixels or something, the background looks really blurry and blocky, but the ball is the worst. The clouds look all right for some reason, probably because they're mostly transparent.

I know the pngs aren't top notch themselves but hey, I'm no artist!

I would imagine it's a problem with either:

a. How the pngs are made

example sprite (512x512): https://docs.google.com/open?id=0Bx9Gbwnv9Hd2a2RRQlJiQTFJUEE

b. How my Matrices work

This is the relevant parts of the renderer:

```
public void onDrawFrame(GL10 unused) {
if(world != null) {
    dt = System.currentTimeMillis() - endTime;

    world.update( (float) dt);

    // Redraw background color
    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

    Matrix.setIdentityM(mvMatrix, 0);
    Matrix.translateM(mvMatrix, 0, 0f, 0f, 0f);

    world.draw(mvMatrix, mProjMatrix);

        endTime = System.currentTimeMillis();
} else {
    Log.d(TAG, "There is no world....");
}
}

public void onSurfaceChanged(GL10 unused, int width, int height) {
    GLES20.glViewport(0, 0, width, height);

Matrix.orthoM(mProjMatrix, 0, 0, width /2, 0, height /2, -1.f, 1.f);
}

```

And this is what each Quad does when draw is called:

```
public void draw(float[] mvMatrix, float[] pMatrix) {
Matrix.setIdentityM(mMatrix, 0);
Matrix.setIdentityM(mvMatrix, 0);

Matrix.translateM(mMatrix, 0, xPos, yPos, 0.f);
Matrix.multiplyMM(mvMatrix, 0, mvMatrix, 0, mMatrix, 0);
Matrix.scaleM(mvMatrix, 0, scale, scale, 0f);
Matrix.rotateM(mvMatrix, 0, angle, 0f, 0f, -1f);

GLES20.glUseProgram(mProgram);

posAttr = GLES20.glGetAttribLocation(mProgram, "vPosition");
texAttr = GLES20.glGetAttribLocation(mProgram, "aTexCo");
uSampler = GLES20.glGetUniformLocation(mProgram, "uSampler");
int alphaHandle = GLES20.glGetUniformLocation(mProgram, "alpha");

GLES20.glVertexAttribPointer(posAttr, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, 0, vertexBuffer);
GLES20.glVertexAttribPointer(texAttr, 2, GLES20.GL_FLOAT, false, 0, texCoBuffer);

GLES20.glEnableVertexAttribArray(posAttr);
GLES20.glEnableVertexAttribArray(texAttr);

GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture);
GLES20.glUniform1i(uSampler, 0);
GLES20.glUniform1f(alphaHandle, alpha);

mMVMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVMatrix");
mPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uPMatrix");

GLES20.glUniformMatrix4fv(mMVMatrixHandle, 1, false, mvMatrix, 0);
GLES20.glUniformMatrix4fv(mPMatrixHandle, 1, false, pMatrix, 0);

GLES20.glDrawElements(GLES20.GL_TRIANGLE_STRIP, 4, GLES20.GL_UNSIGNED_SHORT, indicesBuffer);

GLES20.glDisableVertexAttribArray(posAttr);
GLES20.glDisableVertexAttribArray(texAttr);

GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
}

```

c. How my texture loading/blending/shaders setup works

Here is the renderer setup:

```
 public void onSurfaceCreated(GL10 unused, EGLConfig config) {
    // Set the background frame color
    GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
GLES20.glDepthMask(false);

GLES20.glBlendFunc(GLES20.GL_ONE, GLES20.GL_ONE_MINUS_SRC_ALPHA);

GLES20.glEnable(GLES20.GL_BLEND);
GLES20.glEnable(GLES20.GL_DITHER);
}

```

Here is the vertex shader:

```
    attribute vec4 vPosition;
attribute vec2 aTexCo;
varying vec2 vTexCo;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;

void main() {
  gl_Position = uPMatrix * uMVMatrix * vPosition;
  vTexCo = aTexCo;
}

```

And here's the fragment shader:

```
    precision mediump float;
uniform sampler2D uSampler;
uniform vec4 vColor;
varying vec2 vTexCo;
varying float alpha;
void main() {
    vec4 color = texture2D(uSampler, vec2(vTexCo));

    gl_FragColor = color;
    if(gl_FragColor.a == 0.0) {
        "discard;
    }
}

```

This is how textures are loaded:

```
    private int loadTexture(int rescource) {
int[] texture = new int[1];
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inScaled = false;

Bitmap temp = BitmapFactory.decodeResource(context.getResources(), rescource, opts);

GLES20.glGenTextures(1, texture, 0);
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture[0]);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, temp, 0);
GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
temp.recycle();

return texture[0];
}

```

I'm sure I'm doing about 20,000 things wrong, so I'm really sorry if the problem is blindingly obvious...

The test device is a Galaxy Note, running a JellyBean custom ROM, if that matters at all. So the screen resolution is 1280x800, which means... The background is 1024x1024, so yeah it might be a *little* blurry, but shouldn't be made of lego.

Thank you so much, any answer at all would be appreciated.

# Answer
You are taking a 512x512 image and smooshing it into an area approximately 120x120 pixels. Thus, you should expect that each pixel is about the average of a 5x5 block. You're using linear texture filtering so that would be expected.

It might be better to use unscaled images if you're going to reduce the resolution by such a large amount. You can control the quality easily since what you see is what you get. Aside from that it will load faster and run faster on phones. A 512x512 image requires an immense amount of memory bandwidth to draw compared to say 128x128 (16x as much, in fact) which is a performance killer on mobile GPUs.
> 5 votes

---
Tags: android, textures, opengl-es2
---


title: rotating spheres

text:
# Question
Title: rotating spheres
I want to continuously rotate 2 spheres, however the rotation does not seem to work.

Here is my code:

```
float angle = 0.0f;

void light(){
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_LIGHT1);

    // Create light components
    GLfloat positionlight1[] = { 9.0, 5.0, 1.0, 0.0 };
    GLfloat positionlight2[] = {0.2,2.5,1.3,0.0};
    GLfloat light_ambient1[] = { 0.0, 0.0, 1.0, 1.0};
    GLfloat light_diffuse[] = { 1.0, 1.0, 1.0, 1.0 };

    glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient1);
    glLightfv(GL_LIGHT1, GL_DIFFUSE, light_diffuse);
    glLightfv(GL_LIGHT0, GL_POSITION, positionlight1);
    glLightfv(GL_LIGHT1, GL_POSITION, positionlight2);

}

void changeSize(int w, int h) {

    if (h==0) // Prevent A Divide By Zero By
    {
        h=1; // Making Height Equal One
    }

    glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
    glLoadIdentity(); // Reset The Projection Matrix
    glViewport(0,0,w,h);// Reset The Current Viewport
    // Calculate The Aspect Ratio Of The Window
    gluPerspective(45.0f,(GLfloat)w/(GLfloat)h,0.1f,100.0f);

    glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix // Reset The Modelview Matrix
}

void renderScene(void) {

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glPushMatrix(); //set where to start the current object

    glTranslatef(0.0,1.2,-6);
    glRotatef(angle,0,1.2,-6);
    glutSolidSphere(1,50,50);

    glPopMatrix(); //end the current object transformations
    glPushMatrix(); //set where to start the current object

    glTranslatef(0.0,-2,-6);
    glRotatef(angle,0,-2,-6);
    glutSolidSphere(0.5,50,50);

    glPopMatrix(); //end the current object transformations

    angle=+0.1;
    glutSwapBuffers();
}

int main(int argc, char **argv) {

    // init GLUT and create window
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
    glutInitWindowPosition(100,100);
    glutInitWindowSize(500,500);
    glutCreateWindow("Hello World");
    // register callbacks
    light();
    glutDisplayFunc(renderScene);
    glutReshapeFunc(changeSize);
    glutIdleFunc(renderScene);

    // enter GLUT event processing loop
    glutMainLoop();

    return 1;
}

Graphicstest::Graphicstest(void)
{
}

```

In the renderscene where i draw,translate and rotate my 2 spheres. It does not seem to rotate the spheres continuously. What am i doing wrong?

# Answer
> 7 votes
The problem is this:

```
angle=+0.1;

```

You have your addition assignment the wrong way around. It should be:

```
angle += 0.1f;

```

When you fix that, it might rotate weirdly. That'll probably be because you're setting it to rotate around two axes (rather than one) in your glRotatef() function:

```
glRotatef(angle,0,-2,-6);

```

The last three digits correspond to the axis you want it to rotate around. So if you want to rotate just around the x-axis, you'd do:

```
glRotatef(angle, 1.0f, 0.0f, 0.0f);

```

Hope this helps (and is correct, heh). It might be an idea to look into the maths library glm (if you don't already know about it). Helps a lot with stuff like this.

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


# Question
Title: Android loading screens blocking, good practice?
I've noticed many (if not all) android games don't support the "back" button functionality during their loading screens. Which leads to some frustrating moments when a user accidentally starts up the game and has to wait for the long loading stage to end in order to close it.

So my questions are:

1) Why is that ? Is there a good reason to avoid something like asynchronous loading (or some other solution to this problem) in android games ?

2) If there is no good reason not to support this functionality, what would be the best way to accomplish it ?

# Answer
> 1 votes
One possible reason for a game to not support the back button when the game is loading is due to the nature of Android. When your application first starts you have one thread the UI thread. This thread is responsible for button input, rendering the GUI and handling the GUI logic. if you then try to load data on this thread in a non-asynchronous manner you will block the thread and freeze the applications UI. This means that all buttons would become unresponsive as that is handled on the blocked thread. Blocking the UI thread in this manner goes against good design principles for the Android platform.

1. There is no good reason to avoid asynchronous loading, in fact to follow the Android guidelines you should use async-loading and threading to not block the UI thread.
2. What you would want to do is handle your data loading on a separate thread. If you are making a game with OpenGL ES 2.0 you would more then likely have the UI Thread, the OpenGL thread and a GameLogic thread. You just need to make sure to manage what can be done on each thread. You can load basic game data in the GameLogic thread but you cannot do any OpenGL or Android UI initialization you will have to queue those events on the respective thread. Managing all of this can be quite complex to keep track of at times. And there may be times you need to block the UI thread for a short while to load something that can only be created on that thread. If you want to exit early you need to terminate whatever threads are running and then shutdown cleanly.

For more information on threading on Android: http://developer.android.com/guide/components/processes-and-threads.html

# Answer
> -1 votes
This sounds like user error to me. The home button is always available to exit the game.

---
Tags: android
---


# Question
Title: How can I test if a point lies between two parallel lines?
In the game I'm designing there is a blast that shoots out from an origin point towards the direction of the mouse. The width of this blast is always going to be the same.

Along the bottom of the screen (what's currently) squares move about which should be effected by the blast that the player controls.

Currently I am trying to work out a way to discover if the corners of these squares are within the blast's two bounding lines. I thought the best way to do this would be to rotate the corners of the square around an origin point as if the blast were completely horizontal and see if the Y values of the corners were less than or equal to the width of the blast which would mean that they lie within the effected region, but I can't work out

# Answer
> 11 votes
The point is between the 2 parallel lines if it's one side of one line and the other side of the other line (providing the lines point in the same direction).

You can use the top answer from this question at stackoverflow to work out which side of a line (defined by 2 points on it) a point lies on.

---

An alternative method would be to calculate the distance from point to a middle line and comparing that to half the thickness of your blast.

# Answer
> 2 votes
This is how I do it (with an additional check whether or not the planes provided are actually parallel. The Plane objects contain the plane equation in this form: Ax + By + Cz + D = 0, which you can easily generate from 3 given points, or from a point and a normal (see this page if you're unsure about the math: http://paulbourke.net/geometry/pointlineplane/)

```
bool isPointBetweenParallelPlanes(const vec3 point, const Plane a, const Plane b){
// test if planes are parallel
vec3 cross = a.normal CROSS b.normal;
assert((a.normal CROSS b.normal) == vec3(0,0,0) && "These planes should be parallel.");
return ((a.normal DOT point) + a.D) * ((b.normal DOT point) + b.D) < 0.0;
}

```

---
Tags: collision-detection, linear-algebra
---


# Question
Title: Where can i find tutoral for Designing building in 3dsmax
I have searched various tutorials for 3ds max. They only show simple house apartment and that too not compelete.

Is there any online company which have tutorial set for complete building design from start to finih so that i can get idea how to model complete bulding

# Answer
> 1 votes
There is this tutorial for basic building :

http://www.free3dtutorials.com/modeling-and-texturing-a-building-in-3dsmax-2009.php

For a more complex building, you have this one in 2 parts :

http://www.free3dtutorials.com/modeling-a-high-definition-building-part-1.php

http://www.free3dtutorials.com/modeling-a-high-definition-building-part-2.php

As for the interior you can find many tutorial that explain how to design them :

http://www.cgarchitect.com/resources/tutorials/smoke3d/tutorial13.asp

http://cg.tutsplus.com/tutorials/autodesk-3d-studio-max/modelling-and-rendering-an-interior-scene-in-3ds-max/

# Answer
> 1 votes
This is a great Tut for you, from floor plan to complete walls and furnishings:

http://youtu.be/9prgBEXRX6Y

Have fun

---
Tags: architecture, 3dsmax
---


title: 2D Game Help In XNA

text:
# Question
Title: 2D Game Help In XNA
I'm making a game in XNA called The Adventure Of The Very Hairy Princess Fairy. The game is a "Sidescroller/Platformer" like mario but there is a problem. How do I attach a weapon to the player texture and add animations so it looks like the player is holding the gun and It's not a floating image in front of the player? The player can kill with things like chainsaws playing as a very hairy princess fairy.

# Answer
> 2 votes
I'm assuming you are using the PSK, correct?

If you are, one thing to do would be to add another animation to the player class. Have an animation for the weapon, with states for idle and attacking. draw them right after you do your player. If you don't want the weapon to show up when you aren't attacking, leave the idle animation as a blank canvas.

Another option is to just add an animation to the player for attacking directly. Add a bool, isAttacking, and when it is true, play the attack animation.

---
Tags: xna, c#, game-mechanics, game-loop
---


title: How do I protect my game's IP?

text:
# Question
Title: How do I protect my game's IP?
I have developed a game and I'm not sure what the best way to protect it is. Any information would be appreciated. The game works a lot like darts same strategy but with a different board and different projectiles.

# Answer
Asking how to protect your games IP is a bit like asking how to protect your games copyright. It is the IP that protects your game. And it may differ in many countries.

As a rule of thumb, if you create a game, the music, game graphic and story is yours because you made it.

Wikipedia article on IP : *"Intellectual property (IP) refers to creations of the mind for which exclusive rights are recognized in law. Under intellectual property law, owners are granted certain exclusive rights to a variety of intangible assets, such as musical, literary, and artistic works; discoveries and inventions; and words, phrases, symbols, and designs. Common types of intellectual property rights include copyright, trademarks, patents, industrial design rights and in some jurisdictions trade secrets."*

Your Ideas will most likely not be protected, you can go through the hassle and patten it if you have invented something completely new. You can also register your art, music, and code for copyright to give you an extra legal edge.

**I aint no Lawyer!** Like the previous post suggest, ask a lawyer if you want to be sure, not a gaming programming website. That is the gaming equivalence of asking Yahoo.Answers instead of a doctor if you have cancer.
> 2 votes

# Answer
The short answer to this is that you should look into copyrighting or patenting any unique names or tech that you are using. Names and tech are probably the most "protectible" (for lack of a better term) when it comes to video game IPs. The game mechanics you are using get a little more complicated. From here, I am using information that I have gathered over time, and am referencing this question as support, but I must be clear:

**This is not legal advice.**

Now, game mechanics themselves cannot be copyrighted, and it's unlikely that patents on them will be approved. So, legal action regarding a re-used or "stolen" mechanic will not hold up in court. However, the exchange between Nimblebit and Zynga regarding Tiny Tower and Dream Heights made me aware that the *expression* of the game mechanic is a matter that can be taken to court. This makes sense when you consider that several versions of the original "Bingo" exist, but all of them have different art-styles, reward systems, twists on gameplay, etc.

That said, what you really should do before moving forward is **seek legal advice from a lawyer specializing in intellectual property laws.**
> 0 votes

---
Tags: legal
---


# Question
Title: Creating a retro-style palette swapping effect in OpenGL
I'm working on a Megaman-like game where I need to change the color of certain pixels at runtime. ***For reference****: in Megaman when you change your selected weapon then main character's palette changes to reflect the selected weapon. Not all of the sprite's colors change, only certain ones do*.

This kind of effect was common and quite easy to do on the NES since the programmer had access to the palette and the logical mapping between pixels and palette indices. On modern hardware, though, this is a bit more challenging because the concept of palettes is not the same.

All of my textures are 32-bit and do not use palettes.

There are two ways I know of to achieve the effect I want, but I'm curious if there are better ways to achieve this effect easily. The two options I know of are:

1. Use a shader and write some GLSL to perform the "palette swapping" behavior.
2. If shaders are not available (say, because the graphics card doesn't support them) then it is possible to clone the "original" textures and generate different versions with the color changes pre-applied.

Ideally I would like to use a shader since it seems straightforward and requires little additional work opposed to the duplicated-texture method. I worry that duplicating textures just to change a color in them is wasting VRAM -- should I not worry about that?

**Edit**: I ended up using the accepted answer's technique and here is my shader for reference.

```
uniform sampler2D texture;
uniform sampler2D colorTable;
uniform float paletteIndex;

void main()
{
        vec2 pos = gl_TexCoord[0].xy;
        vec4 color = texture2D(texture, pos);
        vec2 index = vec2(color.r + paletteIndex, 0);
        vec4 indexedColor = texture2D(colorTable, index);
        gl_FragColor = indexedColor;
}

```

Both textures are 32-bit, one texture is used as lookup table containing several palettes which are all the same size (in my case 6 colors). I use the source pixel's red channel as an index to the color table. This worked like a charm for achieving Megaman-like palette swapping!

# Answer
> 43 votes
I wouldn't worry about wasting VRAM for a few character textures.

To me using your **option 2.** (with different textures or different UV offsets if that fits) is the way to go: more flexible, data-driven, less impact on the code, less bugs, less worries.

---

This put aside, if you start to accumulate tons of characters with tons of sprite animations in memory, maybe you could start using **what's recommended by OpenGL**, do-it-yourself palettes:

> ### Paletted textures
>
> Support for the EXT\_paletted\_texture extension has been dropped by the major GL vendors. If you really need paletted textures on new hardware, you may use shaders to achieve that effect.
>
> Shader example:
>
> ```
> //Fragment shader
> #version 110
> uniform sampler2D ColorTable;     //256 x 1 pixels
> uniform sampler2D MyIndexTexture;
> varying vec2 TexCoord0;
>
> void main()
> {
>   //What color do we want to index?
>   vec4 myindex = texture2D(MyIndexTexture, TexCoord0);
>   //Do a dependency texture read
>   vec4 texel = texture2D(ColorTable, myindex.xy);
>   gl_FragColor = texel;   //Output the color
> }
>
> ```

This is simply sampling in `ColorTable` (a palette in RGBA8), using `MyIndexTexture` (an 8 bits square texture in indexed colors). Just reproduces the way retro-style palettes work.

---

The above-quoted example uses two `sampler2D`, where it could actually use one **`sampler1D`** \+ one `sampler2D`. I suspect this is for compatibility reasons (no one-dimensional textures in OpenGL ES)... But nevermind, for desktop OpenGL this can be simplified to:

```
uniform sampler1D Palette;             // A palette of 256 colors
uniform sampler2D IndexedColorTexture; // A texture using indexed color
varying vec2 TexCoord0;                // UVs

void main()
{
    // Pick up a color index
    vec4 index = texture2D(IndexedColorTexture, TexCoord0);
    // Retrieve the actual color from the palette
    vec4 texel = texture1D(Palette, index.x);
    gl_FragColor = texel;   //Output the color
}

```

`Palette` is a one-dimensional texture of "real" colors (e.g. `GL_RGBA8`), and `IndexedColorTexture` is a two-dimensional textures of indexed colors (typically `GL_R8`, which gives you 256 indices). To create those, there are several authoring tools and image file formats out there that support paletted images, it should be doable to find the one that fits your needs.

# Answer
> 10 votes
There are 2 ways I can think to do this.

# Way #1: GL\_MODULATE

You can make the sprite in shades of gray, and `GL_MODULATE` the texture when it is drawn with a single solid color.

For example,

This doesn't allow you much flexibility however, basically you can only go lighter and darker of the same shade.

# Way #2: `if` statementing (bad for performance)

Another thing you could do is color your textures with some key values involving R, G and B. SO for example, the first color is (1,0,0), the 2nd color is (0,1,0), the 3rd color is (0,0,1).

You declare a couple of uniforms like

```
uniform float4 color1 ;
uniform float4 color2 ;
uniform float4 color3 ;

```

Then in the shader, the final pixel color is something like

```
float4 pixelColor = texel.r*color1 + texel.g*color2 + texel.b*color3 ;

```

`color1`, `color2`, `color3`, are uniforms so they can be set before the shader runs (depending on what "suit" megaman is in), then the shader simply does the rest.

You could also use `if` statements if you needed more colors, but you would have to be the equality checks work correctly (textures are usually `R8G8B8` between 0 and 255 each in the texture file, but in the shader, you have rgba floats)

# Way #3: Just redundantly store the different colored images in the sprite map

This may be the easiest way, if you're not insanely trying to conserve memory

# Answer
> 6 votes
I'd use shaders. If you don't want to use them (or can't) I'd go with one texture (or part of a texture) per color and use clean white only. This will allow you to tint the texture (e.g. through `glColor()`) without you having to worry about creating additional textures for colors. You can even swap colors on the run without additional texture work.

# Answer
> 3 votes
"Not all of the sprite's colors change, only certain ones do."

Old games did palette tricks because that was all they had. These days, you can use multiple textures and combine them in various ways.

You can create a separate grayscale mask texture which you use to decide which pixels will change color. White areas in the texture receieve the full color modification, and black areas remain unchanged.

In shader languague:

```
vec3 baseColor = texture(BaseSampler, att_TexCoord).rgb;
float amount = texture(MaskSampler, att_TexCoord).r;
vec3 color = mix(baseColor, baseColor * ModulationColor, amount);

```

Or you can use fixed-function multi-texturing with various texture combiner modes.

There are obviously many different ways you can go about this; you can put masks for different colors in each of the RGB channels, or modulate the colors by tint shifting in an HSV colorspace.

Another, perhaps simpler, option is to simply draw the sprite using a separate texture for each component. One texture for the hair, one for the armor, one for the boots, etc. Each one color tintable separately.

# Answer
> 2 votes
Firstly it's generally referred to as cycling (pallet cycling), so that might help your Google-fu.

This will depend on exactly what effects you want to produce and if you are dealing with static 2D content or dynamic 3D stuff (ie do you just want to deal with spites/textures, or render a whole 3D scene then pallet swap that). Also if you are limiting yourself to a number of colours or using full colour.

A more complete approach, using shaders, would be to actually produce colour indexed images with a pallet texture. Make a texture but instead of having colours, have a colour the represents an index to lookup then have another texture of colours that is the plate. For example red could be the textures t coordinate, and green could be the s coordinate. Use a shader to do the lookup. And Animate/Modify the colours of that pallet texture. This would be quite close to the retro effect but would only work for static 2D content such as sprites or textures. If you doing genuine retro graphics then you might be able to produce actual indexed colour sprites and write something to import them and the pallets.

You will also want to work out if you are going to use a 'global' pallet. Like how old hardware would work, less memory for pallets as you only need one but harder to produce your artwork for as you have to synchronize the pallet across all the images) or give each image it's own pallet. That would give you more flexibility but use more memory. Of course you could do both, also you could only use pallets for the things you are colour cycling. Also work out to what extent you wan't to limit your colors to, old games would use 256 colors for example. If you are using a texture then you will be getting the number of pixels so a 256\*256 will give you

If you just want a cheap fake effect, such as flowing water, you could create a 2nd texture that contain a greyscale mask the area you want to be modified, then use the masted textures modify the hue/saturation/brightness by the amount in the greyscale mask texture. You could be even lazier and just change the hue/brightness/saturation of anything in a colour range.

If you did need it in full 3D you could try generating the indexed image on the fly but it would be slow as you would have to look up the pallet, you would also likely be limited in the range of colours.

Otherwise you could just fake it in the shader, if color == swapping color, swap it. That would be slow and would only work with a limited number of swapping colors but shouldn't stress any of today hardware, particularly if you just dealing with 2D graphics and you can always mark which sprites have colour swapping and use a different shader.

Otherwise really fake them, make a bunch of animated textures for each state.

Here is a great demo of pallet cycling done in HTML5.

# Answer
> 0 votes
I believe ifs are fast enough for the color space \[0...1\] to be divided into two:

```
if (color.r > 0.5) {
   color.r = (color.r-0.5) * uniform_r + uniform_base_r;
} else {
  color.r *=2.0;
} // this could be vectorised for all colors

```

In this way color values between 0 and 0.5 are reserved for normal color values; and 0.5 - 1.0 are reserved for "modulated" values, where 0.5..1.0 maps to any range selected by the user.

Only the color resolution is truncated from 256 values per pixel to 128 values.

Probably one can use builtin functions like max(color-0.5f,0.0f) to remove the ifs completely (trading them to multiplications by zero or one...).

---
Tags: opengl, textures, palette
---


# Question
Title: If I project a sphere in 3D will it be a circle?
Assuming I have infinite vertices to represent the sphere, if I project the sphere from any position/scale in 3D to 2D, will it be a circle?

I know it will not be a circle on the screen, because of scaling and different resolutions. But do field of view and aspect ratio effect the results?

Edit: Sorry yes, I am talking about perspective projection. Seems the answer is no then, perspective will distort the sphere. Thanks!

# Answer
If we're talking about *any* projection, this is quite obviously not the case. After all, Cahill's Butterfly is a valid projection of a sphere onto a 2D surface:

Non-uniform parallel projections will also tend to distort the shape. Perspective projections on the other hand won't distort the shape as long as the projection surface has zero curvature (that is, it's "flat" in respect to the space embedding it).
> 13 votes

# Answer
In a perspective projection, not necessarily - in fact, the further the sphere is from center of projection, the more distorted it will be. Example: old picture of a distorted sphere.
> 18 votes

---
Tags: 3d, projection
---


# Question
Title: How reimport a package in UDK with command line?
sometimes ago, I saw a command to re-import a UDK package content without opening the UDK Editor. (Especially, it was used for reimporting a Flash package in a scaleform tutorial, but it doesn't matter now )

It's very useful, because every time I change my .swf file, I should open the heavy UDK and just press re-import.

So, can anyone give me that solution again ?

# Answer
I found the solution For packages containing `.swf files` here :

> **gfximport Commandlet**
>
> To improve iteration time, the gfximport commandlet, run from your Unreal Engine 3 executable (e.g UDKLift.exe) allows for content importing and reimporting without loading Unreal Editor. The commandlet assumes that content has been arranged in the manner described above.
>
> In order to import a file, you must run gfximport commandlet while specifying relative paths to all of the .SWF files within the GameDir\Flash directory that you wish to import separated by spaces.

`UDKLift.exe gfximport [path_1] [path_2] [path_3]`

> In order to re-import files that are already imported into UE3, simply run the commandlet with no arguments.

`UDKLift.exe gfximport`

> The commandlet will reimport all the SwfMovies for which the .SWF file on disk is newer than the one imported.
>
> Example:
>
> Suppose you want to import these files.
>
> ```
> C:\UDK\UDK-2010-07\UDKGame\Flash\UI\MainMenu.swf
> C:\UDK\UDK-2010-07\UDKGame\Flash\UI\Resources.swf
>
> ```
>
> You would execute the following command:

`UDKLift.exe gfximport UI/MainMenu.swf UI/Resources.swf`

> They will be imported into the UI package as SwfMovie'UI.MainMenu' and SwfMovie'UI.Resources'. The package will be saved as GameDir\Content\GFx\UI.upk.
> 0 votes

---
Tags: udk
---


# Question
Title: How to display text and numbers in SFML 2.0
I want to display some text and numerical data over my OpenGL scene in SFML 2.0. I've looked at the SFML 1.6 text tutorials here. But I can't get the code to work. There is (as of yet) no text tutorial for 2.0

# Answer
A lot of the method names have changed in the transition from SFML 1.6 to 2.0. So the 1.6 tutorials will not work without modification.

First you will need to creat a font, you can do this using a .ttf file

```
//create a font
sf::Font font;

// Load it from a file
if (!font.loadFromFile("../sansation.ttf"))
    //find this file in the "pong" example in the SFML examples folder
{
    std::cout << "Error loading font\n" ;
}

```

Inside your render loop, after drawing your scene, you can add this code to render some text and numerical data:

```
//Draw scene
//.........Draw Scene stuff......

//save the openGLstate if using OpenGL
//becase text drawing may well change some OpenGL settings
window.pushGLStates();

static float frameCount=0;
frameCount++;

std::ostringstream ss; //string buffer to convert numbers to string
ss << "Hello World , frame count is: " << frameCount;// put float into string buffer

//set up text properties
sf::Text atext;
atext.setFont(font);
atext.setCharacterSize(20);
atext.setStyle(sf::Text::Bold);
atext.setColor(sf::Color::White);
atext.setPosition(0,0);

atext.setString(ss.str()); //ss.str() converts the string buffer into a regular string

//draw the string
window.draw(atext);

//restore OpenGL setting that were saved earlier
window.popGLStates();
window.display();

```
> 5 votes

---
Tags: sfml
---


# Question
Title: Calculating distance from viewer to object in a shader
Good morning,

I'm working through creating the spherical billboards technique outlined in this paper. I'm trying to create a shader that calculates the distance from the camera to all objects in the scene and stores the results in a texture. I keep getting either a completely black or white texture.

Here are my questions:

* I assume the position that's automatically sent to the vertex shader from ogre is in object space?
* The gpu interpolates the output position from the vertex shader when it sends it to the fragment shader. Does it do the same for my depth calculation or do I need to move that calculation to the fragment shader?
* Is there a way to debug shaders? I have no errors but I'm not sure I'm getting my parameters passed into the shaders correctly.

Here's my shader code:

```
void DepthVertexShader(
   float4 position : POSITION,
   uniform float4x4 worldViewProjMatrix,
   uniform float3 eyePosition,
   out float4 outPosition : POSITION,
   out float Depth
)
{
   // position is in object space
   // outPosition is in camera space
   outPosition = mul( worldViewProjMatrix, position );
   // calculate distance from camera to vertex
   Depth = length( eyePosition - position );
}

void DepthFragmentShader(
   float Depth : TEXCOORD0,
   uniform float fNear,
   uniform float fFar,
   out float4 outColor : COLOR
)
{
   // clamp output using clip planes
   float fColor = 1.0 - smoothstep( fNear, fFar, Depth );
   outColor = float4( fColor, fColor, fColor, 1.0 );
}

```

fNear is the near clip plane for the scene fFar is the far clip plane for the scene

# Answer
Yes, the position sent to the vertex shader is generally the local coordinates of the object's vertex. Your multiplication by `worldViewProjMatrix` in the vertex shader is what handles the transformation from world space to camera space to projection space, all in one shot.

The GPU will interpolate any `out` variables from your vertex shader across the face of the triangle and send them along to the fragment shader. However, if your goal is to store the depth in a texture, you will need to set the target framebuffer to the texture you want, and your fragment shader will have to write out the depth encoded into the color, something like:

```
outColor = float4(Depth);

```

As for your final question, there is sadly no easily available way to debug shaders, unless you have software similar to PIX which captures all the data running through the framebuffer (note that PIX will only work for Direct3D applications). The best advice I can offer you to debug your shader input values is to use them in your calculation of `outColor` in such a way that you can determine if they look correct. For example you could do:

```
outColor = float4(position, 1.0);

```

where `position` is output from the vertex shader as the local position of the vertex. Doing this you would expect your object to look as if it was carved out of the color cube.
> 2 votes

---
Tags: shaders, ogre, graphic-effects, cg
---


# Question
Title: Comprehension question to MVC Pattern in Game Programming
So is my assumption right?

If I use MVC in Games I will have to implement a Model,Controller,View for every kind of interaction object.

For example in an Motorbike game. My Motorbike object will have its own controller, view and model class. Or is it enough if I define a model,view and controller for the world object and just use that view for drawing my bike?!

Or am I mixing something up?

# Answer
> 4 votes
MVC doesn't mean you have to separate state, behavior and appearance everywhere. Sometimes you may and should put everything together. One uses MVC approach where multiple objects/entities/components (however you call them) are involved in exchange of data (be it really passing some value, or calling a method of another object).

So it means:

* **Model**, typically the data you would bother to put into your save files.
* **Controller**, a piece of code that is used by multiple objects (e.g. your score increases both when you pick a coin and kill an enemy) or an action of one object over another, where first can't be simply a child/parent of the second (where the parent is a single component)
* **View**, a component, something that could work without the rest, e.g. a scrollbar. It's useless without the rest, but if you put a scrollbar in a game and nothing else, it should work (you should be able to scroll it, if you initialized it with some values). This scrollbar will do all logic inside itself, e.g. calculating how pressing a button will affect slider's position, but it will also send some messages outside, like "scrolled" event with "scroll\_percentage" data.

So in your Motorbike game, you will probably want to keep some data in your component `Motorbike`, e.g. it's current rotation, keep some logic, e.g. `rotate` method, and of course the view, `draw` method. But you will probably duplicate some data (rotation) in model, so you have all important data ready on (auto)save event. Also, while your Motorbike can handle itself, you will want it to communicate with the rest of the game (collision detection for example) and you communicate different classes with notifications/events/whatever else your MVC framework uses.

---
Tags: game-design, patterns, mvc
---