# Question
Title: Collision detection problems - Javascript/Canvas game
**What I want to do:**

I simply want the have a 2D array to represent my game map.

I want a player sprite and I want that sprite to be able to move around my map freely using the keyboard and also have collisions with certain tiles of my map array.

I want to use very large maps so I need a viewport.

**What I have:**

I have a loop to load the tile images into an array:

```
//Loop to load tile images into an array
var mapTiles = [];

for (x = 0; x <= 256; x++) {
    var imageObj = new Image(); // new instance for each image
    imageObj.src = "images/prototype/"+x+".jpg";
    mapTiles.push(imageObj);
}

```

I have a 2D array for my game map:

```
//Array to hold map data
var board =   [
    [1,2,3,4,3,4,3,4,5,6,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    [17,18,19,20,19,20,19,20,21,22,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    [33,34,35,36,35,36,35,36,37,38,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    [49,50,51,52,51,52,51,52,53,54,1,1,1,1,1,1,1,1,1,1,1,1,1,197,198,199,1,1,1,1],
    [65,66,67,68,146,147,67,68,69,70,1,1,1,1,1,1,1,1,216,217,1,1,1,213,214,215,1,1,1,1],
    [81,82,83,161,162,163,164,84,85,86,1,1,1,1,1,1,1,1,232,233,1,1,1,229,230,231,1,1,1,1],
    [97,98,99,177,178,179,180,100,101,102,1,1,1,1,59,1,1,1,248,249,1,1,1,245,246,247,1,1,1,1],
    [1,1,238,1,1,1,1,239,240,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    [216,217,254,1,1,1,1,255,256,1,204,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    [232,233,1,1,1,117,118,1,1,1,220,1,1,119,120,1,1,1,1,1,1,1,1,1,1,1,119,120,1,1],
    [248,249,1,1,1,133,134,1,1,1,1,1,1,135,136,1,1,1,1,1,1,59,1,1,1,1,135,136,1,1],
    [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    [1,1,216,217,1,1,1,1,1,1,60,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    [1,1,232,233,1,1,1,1,1,1,1,1,1,1,1,1,1,1,204,1,1,1,1,1,1,1,1,1,1,1],
    [1,1,248,249,1,1,1,1,1,1,1,1,1,1,1,1,1,1,220,1,1,1,1,1,1,216,217,1,1,1],
    [1,1,1,1,1,1,1,1,1,1,1,1,149,150,151,1,1,1,1,1,1,1,1,1,1,232,233,1,1,1],
    [12,12,12,12,12,12,12,13,1,1,1,1,165,166,167,1,1,1,1,1,1,119,120,1,1,248,249,1,1,1],
    [28,28,28,28,28,28,28,29,1,1,1,1,181,182,183,1,1,1,1,1,1,135,136,1,1,1,1,1,1,1],
    [44,44,44,44,44,15,28,29,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    [1,1,1,1,1,27,28,29,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    [1,1,1,1,1,27,28,29,1,1,1,1,1,1,1,1,1,59,1,1,197,198,199,1,1,1,1,119,120,1],
    [1,1,1,1,1,27,28,29,1,1,216,217,1,1,1,1,1,1,1,1,213,214,215,1,1,1,1,135,136,1],
    [1,1,1,1,1,27,28,29,1,1,232,233,1,1,1,1,1,1,1,1,229,230,231,1,1,1,1,1,1,1],
    [1,1,1,1,1,27,28,29,1,1,248,249,1,1,1,1,1,1,1,1,245,246,247,1,1,1,1,1,1,1],
    [1,1,1,197,198,199,28,29,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    [1,1,1,213,214,215,28,29,1,1,1,1,1,60,1,1,1,1,204,1,1,1,1,1,1,1,1,1,1,1],
    [1,1,1,229,230,231,28,29,1,1,1,1,1,1,1,1,1,1,220,1,1,1,1,119,120,1,1,1,1,1],
    [1,1,1,245,246,247,28,29,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,135,136,1,1,60,1,1],
    [1,1,1,1,1,27,28,29,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    [1,1,1,1,1,27,28,29,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
];

```

I have my loop to place the correct tile sin the correct positions:

```
//Loop to place tiles onto screen in correct position
for (x = 0; x <= viewWidth; x++){
    for (y = 0; y <= viewHeight; y++){
        var width = 32;
        var height = 32;
        context.drawImage(mapTiles[board[y+viewY][x+viewX]],x*width, y*height);
    }
}

```

I have my player object :

```
//Place player object
    context.drawImage(playerImg, (playerX-viewX)*32,(playerY-viewY)*32, 32, 32);

```

I have my viewport setup:

```
//Set viewport pos
viewX = playerX - Math.floor(0.5 * viewWidth);
    if (viewX < 0) viewX = 0;
    if (viewX+viewWidth > worldWidth) viewX = worldWidth - viewWidth;

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

```

I have my player movement:

```
canvas.addEventListener('keydown', function(e) {
    console.log(e);
    var key = null;
    switch (e.which) {
        case 37:
            // Left
            if (playerY > 0) playerY--;
            break;
        case 38:
            // Up
            if (playerX > 0) playerX--;
            break;
        case 39:
            // Right
            if (playerY < worldWidth) playerY++;
            break;
        case 40:
            // Down
            if (playerX < worldHeight) playerX++;
            break;
    }

```

**My Problem:**

I have my map loading an it looks fine, but my player position thinks it's on a different tile to what it actually is.

So for instance, I know that if my player moves left 1 tile, the value of that tile should be 2, but if i print out the value it should be moving to (2), it comes up with a different value.

**How I've tried to solve the problem:**

I have tried swap X and Y values for the initialization of my player, for when my map prints.

If I swap the X and Y values in this part of my code:

```
context.drawImage(mapTiles[board[y+viewY][x+viewX]],x*width, y*height);

```

The map doesnt get draw correctly at all and tiles are placed all in random positions or orientations

If I swap the X and Y values for my player in this line :

```
context.drawImage(playerImg, (playerX-viewX)*32,(playerY-viewY)*32, 32, 32);

```

The players movements are inversed, so up and down keys move my player left and right viceversa.

**My question:**

Where am I going wrong in my code, and how do I solve it so I have my map looking like it should and my player moving as it should as well as my player returning the correct tileID it is standing on or moving too.

**ALSO**

Here is a link to my whole code:

prototype

# Answer
> 2 votes
This code....

```
switch (e.which) {
        case 37:
            // Left
            if (playerY > 0) playerY--;
            break;
        case 38:
            // Up
            if (playerX > 0) playerX--;
            break;
        case 39:
            // Right
            if (playerY < worldWidth) playerY++;
            break;
        case 40:
            // Down
            if (playerX < worldHeight) playerX++;
            break;
    }

```

Should be:

```
     switch (e.which) {
        case 37:
            // Left
            if (playerX > 0) playerX--;
            break;
        case 38:
            // Up
            if (playerY > 0) playerY--;
            break;
        case 39:
            // Right
            if (playerX < worldWidth) playerX++;
            break;
        case 40:
            // Down
            if (playerY < worldHeight) playerY++;
            break;
    }

```

You got Up and Down mixed up with Left and right (And I'm assuming your comment are correct here), also worldHeight and worldWidth have been corrected.

I see no code that enquires what tile the player is currently under so unable to fix anything related to that part of the question.

The following should work:

```
 function getPlayerTile(x, y) {
     return board[y][x];
 }

 console.log(getPlayerTile(playerX, playerY));

```

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


# Question
Title: Algorithms for rainfall + river creation in procedurally generated terrain
I've recently become fascinated by the things that can be done with procedurally terrain and have started experimenting with world building a bit. I'd like to be able to make worlds something like Dwarf fortress with biomes created from meshing together various maps.

So first step has been done. Using the diamond-square algorithm I've created some nice hieghtmaps. Next step is I would like to add some water features and have them somewhat realistically generated with rainfall. I've read about a few different approaches such as starting at the high points of the map, and "stepping" down to the lowest neighboring point, pooling/eroding as it works its way down to sea level.

Are there any documented algorithms with this or are they more off the cuff?

Would love any advice/thoughts.

# Answer
> 41 votes
Amit Patel, a user of this site, has created a wonderful resource of information about random world generation that will certainly be of use to you.

Further there are some great questions/answers about procedural generation on this site.

Road / river generation on 2d grid map

Procedural world generation oriented on gameplay features

How can I generate random lakes and rivers in my game?

Random map generation

# Answer
> 37 votes
Back when I experimented with this type of thing (late 1990s), I read some papers and books to learn about water flow, but I didn't keep a record of which ones I looked at. I ended up doing my own thing because I wanted to handle erosion. I wanted rivers to produce canyons and floodplains. I wanted dam reservoirs to fill up with sediment. I wanted rivers to produce effects like meandering and oxbow lakes. I wanted canals for irrigation and water diversion. I wanted floods to damage farms and houses in floodplains.

I kept some notes (links) in the Geography section of this page. There's a Jos Stam paper that is a must-read. Unfortunately I never organized the notes. Also unfortunately, the game was for OS/2 so I can't easily give you a runnable executable to play with. And also unfortunately, my code is terrible, but if you want to take a look, see water.cpp in the source code (zip).

Things I played with in my simulation (not all realistic):

* Areas near rivers have moist soil; areas far from rivers have dry soil. Moisture affected vegetation. Vegetation slows water flow.
* Rain creates water in all places, some of the time. It then flows downhill. Then it evaporates and is absorbed by the ground. The rain carves out river channels.
* Springs create water all the time, but only in a few locations. The springs keep the river channels filled. I didn't simulate rock layers or groundwater flow; I just placed springs randomly on mountains.
* Flowing water has momentum. If I remember right, this was important for making rivers meander.
* Fast moving water picks up sediment; slow moving water deposits sediment ahead of it. This carves out river valleys.
* During initial map creation I accelerated the water flow and erosion; during gameplay it ran at normal speed.

Overall, my experience was that all of this was quite *fun* to play with, but it took lots of heuristics and tweaking to make it work. I never got to a point where I could say that river creation felt natural and inevitable without tweaking. It was so much fun (both as a programmer and as a player) that I spent years on it, and never finished the rest of the game. :)

# Answer
> 1 votes
Most of the implementations I've seen have either been combining a "river map" (using a narrow band from Perlin noise or some similar approach) or the "raindrop" method you mention.

Here are a few jump-off points:

---
Tags: maps, procedural-generation, terrain, world-design
---


title: Sprites rendering blurry with velocity

text:
# Question
Title: Sprites rendering blurry with velocity
After adding velocity to my game, I feel like my textures are twitching. I thought it was just my eyes, until I finally captured it in a screenshot:

The one on the left is what renders in my game; the one on the right is the original sprite, pasted over. (This is a screenshot from Photoshop, zoomed in 6x.)

Notice the edges are aliasing -- it looks almost like sub-pixel rendering. In fact, if I had not forced my sprites (which have position and velocity as ints) to draw using integer values, I would swear that MonoGame is drawing with floating point values. But it isn't.

What could be the cause of these things appearing blurry? It doesn't happen without velocity applied.

To be precise, my `SpriteComponent` class has a `Vector2 Position` field. When I call `Draw`, I essentially use `new Vector2((int)Math.Round(this.Position.X), (int)Math.Round(this.Position.Y))` for the position.

I had a bug before where even stationary objects would jitter -- that was due to me using the straight `Position` vector and not rounding the values to `ints`. If I use `Floor`/`Ceiling` instead of round, the sprite sinks/hovers (one pixel difference either way) but still draws blurry.

# Answer
Well, this is embarrassing.

It turns out that **I was not drawing using integer positions, but float positions.** Archy pointed me down the right path with his comment `@ashes999 did you debug this call and checked this.X, this.Y and this.origin?`

As soon as I added a trace statement, I noticed that nothing traced out. It turns out that my `SpriteComponent` class correctly used integer values, but my `SpriteSheetComponent` still used float values from the raw `Vector2 Position`.

Although I didn't try texture filtering and clamping, I was suspicious that these were not the correct change, because I was drawing a 2D image at the same width and height as the source image (no scaling).
> 3 votes

# Answer
XNA uses DirectX9 which uses the center of the pixel as its location. This is noticeable when using the Vector2 based overloads of the draw class. I believe that subtracting (.5, .5) should fix your problem.

More info here.
> 2 votes

# Answer
Rendering doesn't know anything about your velocity, so either the position, size or anything else your pass along to SpriteBatch.Draw is different or the error was present before you added velocity. How do you call SpriteBatch.Draw exactly?

Did you debug this call and checked this.X, this.Y and this.origin? What is this.origin set to? There is basically no way the render result with velocity is different when this Draw call is the same.
> 2 votes

# Answer
The problem is likely that texture filtering is turned on. If you're not sure what that means, consider a situation where you have a image that is 2 pixels wide: The first pixel is black, the second pixel is white. If you zoom in on this texture, if texture filtering is on, you will see that it gets blurry and that the area between the black and white pixel uses a gradient gray color.

A classic example of games with and without filtering are Super Mario 64 which had filtering while Doom did not.

When you don't use velocity, your Sprite is likely positioned so that the center of the texture is at the sample point that XNA (or whatever underlying api is being used) is grabbing the color. When you move with a float velocity, then the position of your Sprite changes, thus the sample point may not line up directly with the center of a pixel, so the end result is that a color that is an average of the nearest pixels is being used to render.

You can verify that filtering is turned on by simply rendering your Sprite really large on screen. If it's blurry, then that's the issue.

If you must have pixel-perfect accuracy in rendering, you will want to have a float value for position stored off somewhere, but use integer values for the position of the object you are rendering...or of course you could just turn off filtering if your game doesn't need it.

You may also want to read this.
> 1 votes

# Answer
Try setting your SamplerState to SamplerState.PointClamp in the SpriteBatch.Begin call.
> 1 votes

---
Tags: xna, graphics, monogame
---


# Question
Title: Loading Texture2D is extremly slow on XBOX360
I have ~100 sprites for each level im my XNA game. On windows it takes ~2 seconds to load them all. Unfortunately on XBOX360 it takes ~30-60 seconds. Am i doing something wrong? Essentially the loading code ist just like this:

```
Texture2D sprite1 = levelContent.Load<Texture2D>("images/level_1/my_sprite_1");
...
Texture2D sprite100 = levelContent.Load<Texture2D>("images/level_1/my_sprite_100");

```

(i use an own content manager for each level to release all level-specific textures at once) Of course i can reduse the ammount of sprites using a spritesheet, but it's extremly painfull for me now. Do i have a better option? And just curious - why is there such huge difference in image loading time?

# Answer
Seek times are a big problem on xbox. Combining all files into an archive to remove directory indexing helps a little bit. Either combine them into a sprite sheet or combine then into a single binary file which you read in one chunk and seperate in memory.

My experience is mostly from the DVD drive of the xbox, but the hdd is very slow too. At least on the DVD the Xbox does additional seeks for checking the directory index, which often take more time than the actual data reading. Reducing the number of files will give you the biggest benefit thought. As you have level based resources you can basically reduce it to one file which should give you a very fast load time.

XnaZip looks pretty promising and includes a section about getting it to run on xbox too. I didn't check the license, you should do that. I looked into it for a minute and it looks like you can modify it easily to load a complete file into memory and than seperating it in memory. You should do that, zip each level into a single file, load it in one chunk and than seperate the textures in memory.
> 2 votes

# Answer
File I/O is extremely slow on Xbox. You have to refactorize your code and start using spritesheets if you want decent load times. And it would be even better if you compress those atlases with DXT texture compression so their size is smaller.
> 4 votes

---
Tags: xna, sprites, xbox360
---


# Question
Title: Should Chinese text be grid aligned in game dialogs?
Title says it all, should I have my text using a variable width font, or fixed width. I didn't know if it is easier to read if its aligned on a grid?

# Answer
If you want to do it the old-fashioned way, then yes, you can use it in a grid. But if you want to use any kind of variable or half-width characters, like writing 5 instead of ５, then you'll need to get off the grid. The characters are all the same width anyway so if you're not using any non-Asian characters then it should align by itself. I don't think having it not on a grid would make any difference in readability.

As a demonstration:

> 你好，我是中国人１２３|
>
> １２３４５６７８你好！|

Versus:

> 你好，我是中国人123|
>
> 12345678你好！|

The question of whether it *should* be in a grid is really up to you. If you're dealing with presenting data, like a statistics screen, then using a fixed width for all characters could make things easier. If you're just printing lines of text, on the other hand, it makes much less of a difference and you can choose freely, as you can find both ways in use.
> 4 votes

---
Tags: text, localization
---


title: Custom Fonts in cocos2d

text:
# Question
Title: Custom Fonts in cocos2d
I have tried Hiero but it has **NEVER** worked for me. Is there an alternative application for creating fonts for cocos2d?

Thanks

# Answer
Glyph Designer is pretty good. It's easy to use and the results are nice, they do a good job with options for outlines, shadows and gradients and the fonts look good enough that I have come to prefer using bitmap fonts generated by Glyph Designer over TTF fonts even in places with static text that are not performance-sensitive.

It has a few annoyances, like you can't simultaneously export a normal and retina asset, so you have to manually export twice to support both. It would also benefit from command-line automation, as I would often like to generate a set of sizes from a given set of parameters, and that means manually moving the size slider and exporting from the GUI, which is tedious. But it gets the job done with good results.
> 2 votes

# Answer
It's late in the day, but 71Squared has now released a command line app for Glyph Designer that allows you generate your font assets as part of your build process and also specify the size you would like, so you can automatically generate SD/HD output as required by your project.

http://www.71squared.com/en/article/1979/introducing-glyph-designer-command-line-gdcl
> 3 votes

---
Tags: cocos2d-iphone, cocos2d, fonts
---


# Question
Title: Move Camera Freely Around Object While Looking at It
I've got a 3D model loaded (a planet) and I have a camera that I want to allow the user to move freely around it. I have no problem getting the camera to orbit the planet around either the x or y axis. My problem is when I try to move the camera on a different axis I have no idea how to go about doing it. I am using OpenGL on Android with the libGDX library. I want the camera to orbit the planet in the direction that the user swipes their finger on the screen.

# Answer
You basically want the camera to walk around on a sphere. And you want the camera to look at the center of the planet while doing it.

Or rotate the camera around it's target. Or implement an arcball camera.
> 7 votes

# Answer
If you want to save some processing power and it won't mess with the rest of your game, you can also rotate the planet in the opposite direction and leave the camera at one point. :)
> 2 votes

---
Tags: opengl, java, android, libgdx
---


# Question
Title: Understanding math used to determine if vector is clockwise / counterclockwise from your vector
I'm reading Programming Game AI by Example by Mat Buckland. In the Math & Physics primer chapter there's a listing of the declaration of a class used to represent 2D vectors.

This class contains a method called Sign. It's implementation is as follows

```
//------------------------ Sign ------------------------------------------
//
//  returns positive if v2 is clockwise of this vector,
//  minus if anticlockwise (Y axis pointing down, X axis to right)
//------------------------------------------------------------------------
enum {clockwise = 1, anticlockwise = -1};

inline int Vector2D::Sign(const Vector2D& v2)const
{
  if (y*v2.x > x*v2.y)
  {
    return anticlockwise;
  }
  else
  {
    return clockwise;
  }
}

```

Can someone explain the vector rules that make this hold true?

What do the values of y\*v2.x and x\*v2.y that are being compared actually represent?

I'd like to have a solid understanding of why this works rather than just accepting that it does without figuring it out. I feel like it's something really obvious that I'm just not catching on to.

Thanks for your help.

# Answer
> 15 votes
Let's first discuss the dot product. **A**·**B** is a measure of **A**'s component in the direction of **B** or vice versa; of the magnitudes of both vectors as well as their similarity in direction. Vectors pointing in the same direction have a dot product equal to the product of their lengths, perpendicular vectors have a dot product of zero. Turn the vectors even further apart, and the dot product becomes negative. Though normally defined as *(x,y)·(u,v) = xu + yv*, it has the property: ***A****·**B** = A B cos θ*, where θ is the angle between the two vectors.

The sign of this product can be used to determine whether a vector **B** partly points in the same or opposing direction of a reference vector **A**, i.e. if **A**·**B** is positive, the angle is less than 90° (or greater than -90°). It doesn't tell us if the vector points left or right with respect to the reference. Below is a graphical description. Blue vectors **B** would yield a positive **A**·**B**, red vectors a negative.

We do have this information we want if we carry out the dot product of **B** and a different reference vector: **A** rotated ninety degrees clockwise (we'll call it **A'**). Once again, in blue vectors **B** that would yield a positive **A'**·**B**, negative values in red.

Note that in a coordinate system with the x-axis pointing right and the y-axis pointing down, we can rotate a vector 90° clockwise as *(x,y)' = (-y,x)*, ergo: ***A'****·**B** = (x,y)'·(u,v) = (-y,x)·(u,v) = -yu + xv*. This number is positive (**B** is clockwise of **A**) if *x v \> y u*. Those are exactly the two values your code is comparing.

---
Tags: mathematics, vector
---


title: Problem rendering VBO

text:
# Question
Title: Problem rendering VBO
I'm developing a game engine using OpenTK. I'm trying to get to grips with the use of VBO's. I've run into some trouble because somehow it doesn't render correctly. Thus far I've used immediate mode to render a test object, a test cube with a texture.

```
namespace SharpEngine.Utility.Mesh
{
    using System;
    using System.Collections.Generic;
    using OpenTK;
    using OpenTK.Graphics;
    using OpenTK.Graphics.OpenGL;
    using SharpEngine.Utility;
    using System.Drawing;

    public class ImmediateFaceBasedCube : IMesh
    {

        private IList<Face> faces = new List<Face>();

        public ImmediateFaceBasedCube()
        {
            IList<Vector3> allVertices = new List<Vector3>();
            //rechtsbovenvoor
            allVertices.Add(new Vector3(1.0f, 1.0f, 1.0f)); //0
            //rechtsbovenachter
            allVertices.Add(new Vector3(1.0f, 1.0f, -1.0f)); //1
            //linksbovenachter
            allVertices.Add(new Vector3(-1.0f, 1.0f, -1.0f)); //2
            //linksbovenvoor
            allVertices.Add(new Vector3(-1.0f, 1.0f, 1.0f)); //3
            //rechtsondervoor
            allVertices.Add(new Vector3(1.0f, -1.0f, 1.0f)); //4
            //rechtsonderachter
            allVertices.Add(new Vector3(1.0f, -1.0f, -1.0f)); //5
            //linksonderachter
            allVertices.Add(new Vector3(-1.0f, -1.0f, -1.0f)); //6
            //linksondervoor
            allVertices.Add(new Vector3(-1.0f, -1.0f, 1.0f)); //7

            IList<Vector2> textureCoordinates = new List<Vector2>();

            textureCoordinates.Add(new Vector2(0, 0));                      //AA - 0
            textureCoordinates.Add(new Vector2(0, 0.3333333f));             //AB - 1
            textureCoordinates.Add(new Vector2(0, 0.6666666f));             //AC - 2
            textureCoordinates.Add(new Vector2(0, 1));                      //AD - 3
            textureCoordinates.Add(new Vector2(0.3333333f, 0));             //BA - 4
            textureCoordinates.Add(new Vector2(0.3333333f, 0.3333333f));    //BB - 5
            textureCoordinates.Add(new Vector2(0.3333333f, 0.6666666f));    //BC - 6
            textureCoordinates.Add(new Vector2(0.3333333f, 1));             //BD - 7
            textureCoordinates.Add(new Vector2(0.6666666f, 0));             //CA - 8
            textureCoordinates.Add(new Vector2(0.6666666f, 0.3333333f));    //CB - 9
            textureCoordinates.Add(new Vector2(0.6666666f, 0.6666666f));    //CC -10
            textureCoordinates.Add(new Vector2(0.6666666f, 1));             //CD -11
            textureCoordinates.Add(new Vector2(1, 0));                      //DA -12
            textureCoordinates.Add(new Vector2(1, 0.3333333f));             //DB -13
            textureCoordinates.Add(new Vector2(1, 0.6666666f));             //DC -14
            textureCoordinates.Add(new Vector2(1, 1));                      //DD -15

            Vector3 copy1 = new Vector3(-2.0f, -2.5f, -3.5f);

            IList<Vector3> normals = new List<Vector3>();
            normals.Add(new Vector3(0, 1.0f, 0)); //0
            normals.Add(new Vector3(0, 0, 1.0f)); //1
            normals.Add(new Vector3(1.0f, 0, 0)); //2
            normals.Add(new Vector3(0, 0, -1.0f)); //3
            normals.Add(new Vector3(-1.0f, 0, 0)); //4
            normals.Add(new Vector3(0, -1.0f, 0)); //5

            //todo: move vertex normal and texture data to datastructure
            //todo: VBO based rendering

            //top face
            //1
            IList<VertexData> verticesT1 = new List<VertexData>();

            VertexData T1a = new VertexData();
            T1a.Normal = normals[0];
            T1a.TexCoord = textureCoordinates[5];
            T1a.Position = allVertices[3];
            verticesT1.Add(T1a);
            VertexData T1b = new VertexData();
            T1b.Normal = normals[0];
            T1b.TexCoord = textureCoordinates[9];
            T1b.Position = allVertices[0];
            verticesT1.Add(T1b);
            VertexData T1c = new VertexData();
            T1c.Normal = normals[0];
            T1c.TexCoord = textureCoordinates[10];
            T1c.Position = allVertices[1];
            verticesT1.Add(T1c);
            Face F1 = new Face(verticesT1);
            faces.Add(F1);

            //2
            IList<VertexData> verticesT2 = new List<VertexData>();
            VertexData T2a = new VertexData();
            T2a.Normal = normals[0];
            T2a.TexCoord = textureCoordinates[10];
            T2a.Position = allVertices[1];
            verticesT2.Add(T2a);
            VertexData T2b = new VertexData();
            T2b.Normal = normals[0];
            T2b.TexCoord = textureCoordinates[6];
            T2b.Position = allVertices[2];
            verticesT2.Add(T2b);
            VertexData T2c = new VertexData();
            T2c.Normal = normals[0];
            T2c.TexCoord = textureCoordinates[5];
            T2c.Position = allVertices[3];
            verticesT2.Add(T2c);
            Face F2 = new Face(verticesT2);
            faces.Add(F2);

            //front face
            //3
            IList<VertexData> verticesT3 = new List<VertexData>();
            VertexData T3a = new VertexData();
            T3a.Normal = normals[1];
            T3a.TexCoord = textureCoordinates[1];
            T3a.Position = allVertices[3];
            verticesT3.Add(T3a);
            VertexData T3b = new VertexData();
            T3b.Normal = normals[1];
            T3b.TexCoord = textureCoordinates[0];
            T3b.Position = allVertices[7];
            verticesT3.Add(T3b);
            VertexData T3c = new VertexData();
            T3c.Normal = normals[1];
            T3c.TexCoord = textureCoordinates[5];
            T3c.Position = allVertices[0];
            verticesT3.Add(T3c);
            Face F3 = new Face(verticesT3);
            faces.Add(F3);

            //4
            IList<VertexData> verticesT4 = new List<VertexData>();
            VertexData T4a = new VertexData();
            T4a.Normal = normals[1];
            T4a.TexCoord = textureCoordinates[5];
            T4a.Position = allVertices[0];
            verticesT4.Add(T4a);
            VertexData T4b = new VertexData();
            T4b.Normal = normals[1];
            T4b.TexCoord = textureCoordinates[0];
            T4b.Position = allVertices[7];
            verticesT4.Add(T4b);
            VertexData T4c = new VertexData();
            T4c.Normal = normals[1];
            T4c.TexCoord = textureCoordinates[4];
            T4c.Position = allVertices[4];
            verticesT4.Add(T4c);
            Face F4 = new Face(verticesT4);
            faces.Add(F4);

            //right face
            //5
            IList<VertexData> verticesT5 = new List<VertexData>();
            VertexData T5a = new VertexData();
            T5a.Normal = normals[2];
            T5a.TexCoord = textureCoordinates[2];
            T5a.Position = allVertices[0];
            verticesT5.Add(T5a);
            VertexData T5b = new VertexData();
            T5b.Normal = normals[2];
            T5b.TexCoord = textureCoordinates[1];
            T5b.Position = allVertices[4];
            verticesT5.Add(T5b);
            VertexData T5c = new VertexData();
            T5c.Normal = normals[2];
            T5c.TexCoord = textureCoordinates[6];
            T5c.Position = allVertices[1];
            verticesT5.Add(T5c);
            Face F5 = new Face(verticesT5);
            faces.Add(F5);

            //6
            IList<VertexData> verticesT6 = new List<VertexData>();
            VertexData T6a = new VertexData();
            T6a.Normal = normals[2];
            T6a.TexCoord = textureCoordinates[1];
            T6a.Position = allVertices[4];
            verticesT6.Add(T6a);
            VertexData T6b = new VertexData();
            T6b.Normal = normals[2];
            T6b.TexCoord = textureCoordinates[5];
            T6b.Position = allVertices[5];
            verticesT6.Add(T6b);
            VertexData T6c = new VertexData();
            T6c.Normal = normals[2];
            T6c.TexCoord = textureCoordinates[6];
            T6c.Position = allVertices[1];
            verticesT6.Add(T6c);
            Face F6 = new Face(verticesT6);
            faces.Add(F6);

            //back face
            //7
            IList<VertexData> verticesT7 = new List<VertexData>();
            VertexData T7a = new VertexData();
            T7a.Normal = normals[3];
            T7a.TexCoord = textureCoordinates[4];
            T7a.Position = allVertices[5];
            verticesT7.Add(T7a);
            VertexData T7b = new VertexData();
            T7b.Normal = normals[3];
            T7b.TexCoord = textureCoordinates[9];
            T7b.Position = allVertices[2];
            verticesT7.Add(T7b);
            VertexData T7c = new VertexData();
            T7c.Normal = normals[3];
            T7c.TexCoord = textureCoordinates[5];
            T7c.Position = allVertices[1];
            verticesT7.Add(T7c);
            Face F7 = new Face(verticesT7);
            faces.Add(F7);
            //8
            IList<VertexData> verticesT8 = new List<VertexData>();
            VertexData T8a = new VertexData();
            T8a.Normal = normals[3];
            T8a.TexCoord = textureCoordinates[9];
            T8a.Position = allVertices[2];
            verticesT8.Add(T8a);
            VertexData T8b = new VertexData();
            T8b.Normal = normals[3];
            T8b.TexCoord = textureCoordinates[4];
            T8b.Position = allVertices[5];
            verticesT8.Add(T8b);
            VertexData T8c = new VertexData();
            T8c.Normal = normals[3];
            T8c.TexCoord = textureCoordinates[8];
            T8c.Position = allVertices[6];
            verticesT8.Add(T8c);
            Face F8 = new Face(verticesT8);
            faces.Add(F8);

            //left face
            //9
            IList<VertexData> verticesT9 = new List<VertexData>();
            VertexData T9a = new VertexData();
            T9a.Normal = normals[4];
            T9a.TexCoord = textureCoordinates[8];
            T9a.Position = allVertices[6];
            verticesT9.Add(T9a);
            VertexData T9b = new VertexData();
            T9b.Normal = normals[4];
            T9b.TexCoord = textureCoordinates[13];
            T9b.Position = allVertices[3];
            verticesT9.Add(T9b);
            VertexData T9c = new VertexData();
            T9c.Normal = normals[4];
            T9c.TexCoord = textureCoordinates[9];
            T9c.Position = allVertices[2];
            verticesT9.Add(T9c);
            Face F9 = new Face(verticesT9);
            faces.Add(F9);
            //10
            IList<VertexData> verticesT10 = new List<VertexData>();
            VertexData T10a = new VertexData();
            T10a.Normal = normals[4];
            T10a.TexCoord = textureCoordinates[8];
            T10a.Position = allVertices[6];
            verticesT10.Add(T10a);
            VertexData T10b = new VertexData();
            T10b.Normal = normals[4];
            T10b.TexCoord = textureCoordinates[12];
            T10b.Position = allVertices[7];
            verticesT10.Add(T10b);
            VertexData T10c = new VertexData();
            T10c.Normal = normals[4];
            T10c.TexCoord = textureCoordinates[13];
            T10c.Position = allVertices[3];
            verticesT10.Add(T10c);
            Face F10 = new Face(verticesT10);
            faces.Add(F10);

            //bottom face
            //11
            IList<VertexData> verticesT11 = new List<VertexData>();
            VertexData T11a = new VertexData();
            T11a.Normal = normals[5];
            T11a.TexCoord = textureCoordinates[10];
            T11a.Position = allVertices[7];
            verticesT11.Add(T11a);
            VertexData T11b = new VertexData();
            T11b.Normal = normals[5];
            T11b.TexCoord = textureCoordinates[9];
            T11b.Position = allVertices[6];
            verticesT11.Add(T11b);
            VertexData T11c = new VertexData();
            T11c.Normal = normals[5];
            T11c.TexCoord = textureCoordinates[14];
            T11c.Position = allVertices[4];
            verticesT11.Add(T11c);
            Face F11 = new Face(verticesT11);
            faces.Add(F11);
            //12
            IList<VertexData> verticesT12 = new List<VertexData>();
            VertexData T12a = new VertexData();
            T12a.Normal = normals[5];
            T12a.TexCoord = textureCoordinates[13];
            T12a.Position = allVertices[5];
            verticesT12.Add(T12a);
            VertexData T12b = new VertexData();
            T12b.Normal = normals[5];
            T12b.TexCoord = textureCoordinates[14];
            T12b.Position = allVertices[4];
            verticesT12.Add(T12b);
            VertexData T12c = new VertexData();
            T12c.Normal = normals[5];
            T12c.TexCoord = textureCoordinates[9];
            T12c.Position = allVertices[6];
            verticesT12.Add(T12c);
            Face F12 = new Face(verticesT12);
            faces.Add(F12);
        }

        public void draw()
        {
            GL.Begin(BeginMode.Triangles);

            foreach (Face  face in faces)
            {
                foreach (VertexData datapoint in face.verticesWithTexCoords)
                {
                    GL.Normal3(datapoint.Normal);
                    GL.TexCoord2(datapoint.TexCoord);
                    GL.Vertex3(datapoint.Position);
                }
            }
            GL.End();
        }

    }
}

```

Gets me this very nice picture:

The immediate mode cube renders nicely and taught me a bit on how to use OpenGL, but VBO's are the way to go. Since I read on the OpenTK forums that OpenTK has problems doing VA's or DL's, I decided to skip using those.

Now, I've tried to change this cube to a VBO by using the same vertex, normal and tc collections, and making float arrays from them by using the coordinates in combination with uint arrays which contain the index numbers from the immediate cube. (see the private functions at end of the code sample) Somehow this only renders two triangles

namespace SharpEngine.Utility.Mesh { using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using SharpEngine.Utility; using System.Drawing;

```
public class VBOFaceBasedCube : IMesh
{

    private int VerticesVBOID;
    private int VerticesVBOStride;
    private int VertexCount;
    private int ELementBufferObjectID;
    private int textureCoordinateVBOID;
    private int textureCoordinateVBOStride;
    //private int textureCoordinateArraySize;
    private int normalVBOID;
    private int normalVBOStride;

    public VBOFaceBasedCube()
    {
        IList<Vector3> allVertices = new List<Vector3>();
        //rechtsbovenvoor
        allVertices.Add(new Vector3(1.0f, 1.0f, 1.0f)); //0
        //rechtsbovenachter
        allVertices.Add(new Vector3(1.0f, 1.0f, -1.0f)); //1
        //linksbovenachter
        allVertices.Add(new Vector3(-1.0f, 1.0f, -1.0f)); //2
        //linksbovenvoor
        allVertices.Add(new Vector3(-1.0f, 1.0f, 1.0f)); //3
        //rechtsondervoor
        allVertices.Add(new Vector3(1.0f, -1.0f, 1.0f)); //4
        //rechtsonderachter
        allVertices.Add(new Vector3(1.0f, -1.0f, -1.0f)); //5
        //linksonderachter
        allVertices.Add(new Vector3(-1.0f, -1.0f, -1.0f)); //6
        //linksondervoor
        allVertices.Add(new Vector3(-1.0f, -1.0f, 1.0f)); //7

        IList<Vector2> textureCoordinates = new List<Vector2>();

        textureCoordinates.Add(new Vector2(0, 0));                      //AA - 0
        textureCoordinates.Add(new Vector2(0, 0.3333333f));             //AB - 1
        textureCoordinates.Add(new Vector2(0, 0.6666666f));             //AC - 2
        textureCoordinates.Add(new Vector2(0, 1));                      //AD - 3
        textureCoordinates.Add(new Vector2(0.3333333f, 0));             //BA - 4
        textureCoordinates.Add(new Vector2(0.3333333f, 0.3333333f));    //BB - 5
        textureCoordinates.Add(new Vector2(0.3333333f, 0.6666666f));    //BC - 6
        textureCoordinates.Add(new Vector2(0.3333333f, 1));             //BD - 7
        textureCoordinates.Add(new Vector2(0.6666666f, 0));             //CA - 8
        textureCoordinates.Add(new Vector2(0.6666666f, 0.3333333f));    //CB - 9
        textureCoordinates.Add(new Vector2(0.6666666f, 0.6666666f));    //CC -10
        textureCoordinates.Add(new Vector2(0.6666666f, 1));             //CD -11
        textureCoordinates.Add(new Vector2(1, 0));                      //DA -12
        textureCoordinates.Add(new Vector2(1, 0.3333333f));             //DB -13
        textureCoordinates.Add(new Vector2(1, 0.6666666f));             //DC -14
        textureCoordinates.Add(new Vector2(1, 1));                      //DD -15

        Vector3 copy1 = new Vector3(-2.0f, -2.5f, -3.5f);

        IList<Vector3> normals = new List<Vector3>();
        normals.Add(new Vector3(0, 1.0f, 0)); //0
        normals.Add(new Vector3(0, 0, 1.0f)); //1
        normals.Add(new Vector3(1.0f, 0, 0)); //2
        normals.Add(new Vector3(0, 0, -1.0f)); //3
        normals.Add(new Vector3(-1.0f, 0, 0)); //4
        normals.Add(new Vector3(0, -1.0f, 0)); //5

        //todo: VBO based rendering
        uint[] vertexElements = {
                            3,0,1,  //01
                            1,2,3,  //02
                            3,7,0,  //03
                            0,7,4,  //04
                            0,4,1,  //05
                            4,5,1,  //06
                            5,2,1,  //07
                            2,5,6,  //08
                            6,3,2,  //09
                            6,7,5,  //10
                            7,6,4,  //11
                            5,4,6   //12
            };
        VertexCount = vertexElements.Length;
        IList<uint> vertexElementList = new List<uint>(vertexElements);
        uint[] normalElements = {
                            0,0,0,
                            0,0,0,
                            1,1,1,
                            1,1,1,
                            2,2,2,
                            2,2,2,
                            3,3,3,
                            3,3,3,
                            4,4,4,
                            4,4,4,
                            5,5,5,
                            5,5,5
            };
        IList<uint> normalElementList = new List<uint>(normalElements);
        uint[] textureIndexArray = {
                            5,9,10,
                            10,6,5,
                            1,0,5,
                            5,0,4,
                            2,1,6,
                            1,5,6,
                            4,9,5,
                            9,4,8,
                            8,13,9,
                            8,12,13,
                            10,9,14,
                            13,14,9
            };
        //textureCoordinateArraySize = textureIndexArray.Length;
        IList<uint> textureIndexList = new List<uint>(textureIndexArray);
        LoadVBO(allVertices, normals, textureCoordinates, vertexElements, normalElementList, textureIndexList);
    }

    public void draw()
    {
        //bind vertices
        //bind elements
        //bind normals
        //bind texture coordinates

        GL.EnableClientState(ArrayCap.VertexArray);
        GL.EnableClientState(ArrayCap.NormalArray);
        GL.EnableClientState(ArrayCap.TextureCoordArray);
        GL.BindBuffer(BufferTarget.ArrayBuffer, VerticesVBOID);
        GL.VertexPointer(3, VertexPointerType.Float, VerticesVBOStride, 0);

        GL.BindBuffer(BufferTarget.ArrayBuffer, normalVBOID);
        GL.NormalPointer(NormalPointerType.Float, normalVBOStride, 0);

        GL.BindBuffer(BufferTarget.ArrayBuffer, textureCoordinateVBOID);
        GL.TexCoordPointer(2, TexCoordPointerType.Float, textureCoordinateVBOStride, 0);
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, ELementBufferObjectID);
        GL.DrawElements(BeginMode.Polygon, VertexCount, DrawElementsType.UnsignedShort, 0);
    }

    //loads a static VBO

    void LoadVBO(IList<Vector3> vertices, IList<Vector3> normals, IList<Vector2> texcoords, uint[] elements, IList<uint> normalIndices, IList<uint> texCoordIndices)
    {
        int size;

        //todo

        // To create a VBO:
        // 1) Generate the buffer handles for the vertex and element buffers.
        // 2) Bind the vertex buffer handle and upload your vertex data. Check that the buffer was uploaded correctly.
        // 3) Bind the element buffer handle and upload your element data. Check that the buffer was uploaded correctly.
        float[] verticesArray = convertVector3fListToFloatArray(vertices);
        float[] normalsArray = createFloatArrayFromListOfVector3ElementsAndIndices(normals, normalIndices);
        float[] textureCoordinateArray = createFloatArrayFromListOfVector2ElementsAndIndices(texcoords, texCoordIndices);
        GL.GenBuffers(1, out VerticesVBOID);
        GL.BindBuffer(BufferTarget.ArrayBuffer, VerticesVBOID);
        Console.WriteLine("load 1 - vertices");
        VerticesVBOStride = BlittableValueType.StrideOf(verticesArray);
        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(verticesArray.Length * sizeof(float)), verticesArray,
                      BufferUsageHint.StaticDraw);
        GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out size);
        if (verticesArray.Length * BlittableValueType.StrideOf(verticesArray) != size)
        {
            throw new ApplicationException("Vertex data not uploaded correctly");
        }
        else
        {

            Console.WriteLine("load 1 finished ok");
            size = 0;
        }

        Console.WriteLine("load 2 - elements");
        GL.GenBuffers(1, out ELementBufferObjectID);
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, ELementBufferObjectID);
        GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(elements.Length * sizeof(uint)), elements,
                      BufferUsageHint.StaticDraw);
        GL.GetBufferParameter(BufferTarget.ElementArrayBuffer, BufferParameterName.BufferSize, out size);
        if (elements.Length * sizeof(uint) != size)
        {
            throw new ApplicationException("Element data not uploaded correctly");
        }
        else
        {
            size = 0;
            Console.WriteLine("load 2 finished ok");
        }

        GL.GenBuffers(1, out normalVBOID);
        GL.BindBuffer(BufferTarget.ArrayBuffer, normalVBOID);
        Console.WriteLine("load 3 - normals");
        normalVBOStride = BlittableValueType.StrideOf(normalsArray);
        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(normalsArray.Length * sizeof(float)), normalsArray,
                      BufferUsageHint.StaticDraw);
        GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out size);
        Console.WriteLine("load 3 - pre check");
        if (normalsArray.Length * BlittableValueType.StrideOf(normalsArray) != size)
        {
            throw new ApplicationException("Normal data not uploaded correctly");
        }
        else
        {
            Console.WriteLine("load 3 finished ok");
            size = 0;
        }

        GL.GenBuffers(1, out textureCoordinateVBOID);
        GL.BindBuffer(BufferTarget.ArrayBuffer, textureCoordinateVBOID);
        Console.WriteLine("load 4- texture coordinates");
        textureCoordinateVBOStride = BlittableValueType.StrideOf(textureCoordinateArray);
        GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(textureCoordinateArray.Length * textureCoordinateVBOStride), textureCoordinateArray,
                      BufferUsageHint.StaticDraw);
        GL.GetBufferParameter(BufferTarget.ArrayBuffer, BufferParameterName.BufferSize, out size);
        if (textureCoordinateArray.Length * BlittableValueType.StrideOf(textureCoordinateArray) != size)
        {
            throw new ApplicationException("texture coordinate data not uploaded correctly");
        }
        else
        {
            Console.WriteLine("load 3 finished ok");
            size = 0;
        }
    }

    //used to convert vertex arrayss for use with VBO's
    private float[] convertVector3fListToFloatArray(IList<Vector3> input)
    {
        int arrayElementCount = input.Count * 3;
        float[] output = new float[arrayElementCount];
        int fillCount = 0;
        foreach (Vector3 v in input)
        {
            output[fillCount] = v.X;
            output[fillCount + 1] = v.Y;
            output[fillCount + 2] = v.Z;
            fillCount += 3;
        }
        return output;
    }

    //used for converting texture coordinate arrays for use with VBO's
    private float[] convertVector2List_to_floatArray(IList<Vector2> input)
    {
        int arrayElementCount = input.Count * 2;
        float[] output = new float[arrayElementCount];
        int fillCount = 0;
        foreach (Vector2 v in input)
        {
            output[fillCount] = v.X;
            output[fillCount + 1] = v.Y;
            fillCount += 2;
        }
        return output;
    }

    //used to create an array of floats from
    private float[] createFloatArrayFromListOfVector3ElementsAndIndices(IList<Vector3> inputVectors, IList<uint> indices)
    {
        int arrayElementCount = inputVectors.Count * indices.Count * 3;
        float[] output = new float[arrayElementCount];
        int fillCount = 0;
        foreach (int i in indices)
        {
            output[fillCount] = inputVectors[i].X;
            output[fillCount + 1] = inputVectors[i].Y;
            output[fillCount + 2] = inputVectors[i].Z;
            fillCount += 3;
        }
        return output;
    }

    private float[] createFloatArrayFromListOfVector2ElementsAndIndices(IList<Vector2> inputVectors, IList<uint> indices)
    {
        int arrayElementCount = inputVectors.Count * indices.Count * 2;
        float[] output = new float[arrayElementCount];
        int fillCount = 0;
        foreach (int i in indices)
        {
            output[fillCount] = inputVectors[i].X;
            output[fillCount + 1] = inputVectors[i].Y;
            fillCount += 2;
        }
        return output;
    }
}

```

}

This code will only render two triangles and they're nothing like I had in mind:

I've done some searching. In some other questions I read that, if I did something wrong, I'd get no rendering at all. Clearly, something gets sent to the GFX card, but it might be that I'm not sending the right data. I've tried altering the sequence in which the triangles are rendered by swapping some of the index numbers in the vert, tc and normal index arrays, but this doesn't seem to be of any effect. I'm slightly lost here. What am I doing wrong here?

# Answer
Common issues I've seen with VBOs usually center around the stride length and setting the correct byte offsets for the vertices, texture and normal coordinates. Make sure you're using the correct values for the stride length. It's usually easiest to set these to constants since you know they're unlikely to change.
> 1 votes

---
Tags: c#, opengl, vbo, opentk
---


# Question
Title: forward motion car physics - gradual slow
Im having trouble creating realistic car movements in xna 4. Right now i have a car going forward and hitting a terminal velocity which is fine but when i release the up key i need to the car to slow down gradually and then come to a stop. Im pretty sure this is easy code but i cant seem to get it to work

the code - update

```
if (Keyboard.GetState().IsKeyDown(Keys.Up))
            {
                double elapsedTime = gameTime.ElapsedGameTime.Milliseconds;
                CalcTotalForce();
                Acceleration = Vector2.Divide(CalcTotalForce(), MASS);
                Velocity = Vector2.Add(Velocity, Vector2.Multiply(Acceleration, (float)(elapsedTime)));
                Position = Vector2.Add(Position, Vector2.Multiply(Velocity, (float)(elapsedTime)));
            }

```

added functions

```
public Vector2 CalcTraction()
    {
        //Traction force = vector direction * engine force
        return Vector2.Multiply(forwardDirection, ENGINE_FORCE);
    }
        public Vector2 CalcDrag()
        {
            //Drag force = constdrag * velocity * speed
            return Vector2.Multiply(Vector2.Multiply(Velocity, DRAG_CONST), Velocity.Y);
        }

        public Vector2 CalcRoll()
        {
            //roll force = const roll * velocity
            return Vector2.Multiply(Velocity, ROLL_CONST);
        }

        public Vector2 CalcTotalForce()
        {
            //total force = traction + (-drag) + (-rolling)
            return Vector2.Add(CalcTraction(),
                Vector2.Add(-CalcDrag(), -CalcRoll()));
        }

```

anyone have any ideas?

# Answer
> 0 votes
The answer was simple:

Take Position out of the keyboard method and have it at the end of the update function. then add to "on key up" call a deceleration vector. i.e

```
 if (Keyboard.GetState().IsKeyDown(Keys.Up))
            {
                Acceleration = Vector2.Divide(CalcTotalForce(), MASS);
                Velocity = Vector2.Add(Velocity, Vector2.Multiply(Acceleration, (float)(elapsedTime)));
            }
            else if(Keyboard.GetState().IsKeyUp(Keys.Up))
            {
                if (Velocity.Y < 0)
                    Velocity = Vector2.Add(Velocity, Vector2.Multiply(decceleration, (float)(elapsedTime)));
            }

```

---
Tags: physics, xna-4.0
---


# Question
Title: How do I cap rendering of tiles in a 2D game with SDL?
I have some boilerplate code working, I basically have a tile based map composed of just 3 colors, and some walls and render with SDL. The tiles are in a bmp file, but each tile inside it corresponds to an internal number of the type of tile(color, or wall). I have pretty basic collision detection and it works, I can also detetc continuous presses, which allows me to move pretty much anywhere I want. I also have a moving camera, which follows the object.

The problem is that, the tile based map is bigger than the resolution, thus not all of the map can be displayed on the screen, but it's still rendered. I would like to cap it, but since this is new to me, I pretty much have no idea.

Although I cannot post all the code, as even though I am a newbie and the code pretty basic, it's already quite a few lines, I can post what I tried to do

```
void set_camera()
{
    //Center the camera over the dot
    camera.x = ( player.box.x + DOT_WIDTH / 2 ) - SCREEN_WIDTH / 2;
    camera.y = ( player.box.y + DOT_HEIGHT / 2 ) - SCREEN_HEIGHT / 2;

    //Keep the camera in bounds.
    if(camera.x < 0 )
    {
        camera.x = 0;
    }
    if(camera.y < 0 )
    {
        camera.y = 0;
    }
    if(camera.x > LEVEL_WIDTH - camera.w )
    {
        camera.x = LEVEL_WIDTH - camera.w;
    }
    if(camera.y > LEVEL_HEIGHT - camera.h )
    {
        camera.y = LEVEL_HEIGHT - camera.h;
    }
}

```

set\_camera() is the function which calculates the camera position based on the player's positions. I won't pretend I know much about it.

```
Rectangle box = {0,0,0,0};

for(int t = 0; t < TOTAL_TILES; t++)
{
    if(box.x < (camera.x - TILE_WIDTH) || box.y > (camera.y - TILE_HEIGHT))
        apply_surface(box.x - camera.x, box.y - camera.y, surface, screen, &clips[tiles[t]]);

    box.x += TILE_WIDTH;

    //If we've gone too far
    if(box.x >= LEVEL_WIDTH)
    {
        //Move back
        box.x = 0;

        //Move to the next row
        box.y += TILE_HEIGHT;
    }
}

```

This is basically my render code. The for loop loops over 192 tiles stored in an int array, each with their own unique value describing the tile type(wall or one of three possible colored tiles).

**box** is an SDL\_Rect containing the current position of the tile, which is calculated on render.

**TILE\_HEIGHT** and **TILE\_WIDTH** are of value 80.

So the cap is determined by

```
if(box.x < (camera.x - TILE_WIDTH) || box.y > (camera.y - TILE_HEIGHT))

```

However, this is just me playing with the values and see what doesn't break it. I pretty much have no idea how to calculate it.

My screen resolution is 1024/768, and the tile map is of size 1280/960.

# Answer
Rather than going through all tiles only iterate over the tiles that are visible or on screen.

I'm assuming that camera coordinates are in pixels

```
for (int y = floor(camera.y / tile_height); y < floor((camera.y + screen.h) / tile_height; y++)
    for (int x = floor(camera.x / tile_width); x < floor((camera.x + screen_width) / tile_width; x++)
        renderTile(x, y);

```
> 2 votes

# Answer
I would write your conditional as the following:

```
if(!(box.x + TILE_WIDTH < camera.x //Tile is outside screen leftwards
   || box.x > camera.x + SCREEN_WIDTH //Tile is outside screen rightwards
   || box.y + TILE_HEIGTH < camera.y //Tile is outside screen upwards
   || box.y > camera.y + SCREEN_HEIGHT)) //Tile is outside screen downwards
{
 ...
}

```
> 1 votes

---
Tags: 2d, rendering, sdl, tilemap, c
---


title: Steering evaluate fitness

text:
# Question
Title: Steering evaluate fitness
I've made a simple game with a steering model that manage a crowd of agents. I use an genetic algorithm to find the best parameters to use in my system but I need to determine a fitness for each simulation. I know it's something like that:

```
number of collisions * time to reach goal * effort

```

But I don't know how to calculate the effort, is there a special way to do that ?

Here is what I've done so far:

```
// Evaluate the distance from agents to goal
Real totalDistance(0.0);
for (unsigned i=0; i<_agents.size(); i++)
{
    totalDistance += _agents[i]->position().distance(_agents[i]->_goal->position());
}

Real totalWallsCollision(0.0);
for (unsigned i=0; i<_agents.size(); i++)
{
    for (unsigned j=0; j<walls.size(); j++)
    {
        if ( walls[j]->inside(_agents[i]->position()) )
        {
            totalCollision += 1.0;
        }
    }
}

return totalDistance + totalWallsCollision;

```

Thanks for your help.

# Answer
> 2 votes
Effort will be specific to your simulation. You could do something like the sum of the distance each agent traveled. Or the sum of all the direction changes each agent had to make. It depends on what your definition of fitness is.

For either of the two above, you can just keep a running total for each agent, then add them all up, just as you do for distance:

```
Real totalEffort(0.0)
for (unsigned i=0; i<_agents.size(); i++)
{
    totalEffort+= _agents[i]->totalEffort();
}

return totalDistance + totalWallsCollision + totalEffort;

```

You could also try keeping a running total of work, so each step of your simulation, calculate `aceleration * mass * distanceTraveled`. Where `distanceTraveled` is the distance traveled since the last update. This will give you the total work (effort) that the agent exerted.

---
Tags: steering-behaviors
---


# Question
Title: My 2D collision code does not work as expected. How do I fix it?
I have a simple 2D game with a tile-based map. I am new to game development, I followed the LazyFoo tutorials on SDL. The tiles are in a bmp file, but each tile inside it corresponds to an internal number of the type of tile(color, or wall).

The game is simple, but the code is a lot so I can only post snippets.

```
 // Player moved out of the map
if((player.box.x < 0))
    player.box.x += GetVelocity(player, 0);

if((player.box.y < 0))
    player.box.y += GetVelocity(player, 1);

if((player.box.x > (LEVEL_WIDTH - DOT_WIDTH)))
    player.box.x -= GetVelocity(player, 0);

if((player.box.y > (LEVEL_HEIGHT - DOT_HEIGHT)))
    player.box.y -= GetVelocity(player, 1);

// Now that we are here, we check for collisions
if(touches_wall(player.box))
{
    if(player.box.x < player.prev_x)
    {
        player.box.x += GetVelocity(player, 0);
    }

    if(player.box.x > player.prev_x)
    {
        player.box.x -= GetVelocity(player, 0);
    }

    if(player.box.y < player.prev_y)
    {
        player.box.y += GetVelocity(player, 1);
    }

    if(player.box.y > player.prev_y)
    {
        player.box.y -= GetVelocity(player, 1);
    }
}

player.prev_x = player.box.x;
player.prev_y = player.box.y;

```

Let me explain, `player` is a structure with the following contents

```
typedef struct {
    Rectangle box; //Player position on a map(tile or whatever).
    int prev_x, prev_y; // Previous positions
    int key_press[3]; // Stores which key was pressed/released. Limited to three keys. E.g Left,right and perhaps jump if possible in 2D

    int velX, velY; // Velocity for X and Y coordinate.

    //Health
    int health;
    bool main_character;
    uint32_t jump_ticks;
} Player;

```

And `Rectangle` is just a typedef of `SDL_Rect`. `GetVelocity` is a function that according to the second argument, returns the velocity for the X or Y axis.

This code I have basically works, however inside the `if(touches_wall(player.box))` if statement, I have 4 more. These 4 if statements are responsible for detecting collision on all 4 sides(up,down,left,right). However, they also act as a block for any other movement.

Example: I move down the object and collide with the wall, as I continue to move down and still collide with the wall, I wish to move left or right, which is indeed possible(not to mention in 3D games), but remember the 4 if statements? They are preventing me from moving anywhere. The original code on the LazyFoo Productions website has no problems, but it was written in C++, so I had to rewrite most of it to work, which is probably where the problem comes from. I also use a different method of moving, than the one in the examples.

Of course, that was just an example. I wish to be able to move no matter at which wall I collide. Before this bit of code, I had another one that had more logic in there, but it was flawed.

# Answer
> 0 votes
With your current code if you touch a wall, then if your player's current position differs from their previous position, it negates the velocity. You should probably be checking in which direction the touch occurred, and only allow that direction to be negated if the velocity is in the same direction as the wall.

You still want the player to be able to move away from the wall, so directions opposite to the wall's direction, or perpendicular to the direction of the wall should be allowed.

You will probably want to handle X and Y separately so that when the player enters a corner, you can negate both directions, if they are moving diagonally into the corner.

# Answer
> 0 votes
You aren't differentiating if they are hitting a wall in the x or y axis and just reversing their direction completely. You need to break it down into where they are touching the wall, like you did with what end of the map they moved out of.

---
Tags: collision-detection, sdl, c, collision-resolution
---


title: Clutter for game GUI

text:
# Question
Title: Clutter for game GUI
I'm pretty new to game development, having only written a simple 3d game for a class project, but I'd like to get started on a bigger project.

I'm writing an MMORPG to run in both the browser (WebGL) and natively (OpenGL ES 2). In choosing a GUI toolkit, I'm trying to find a style that work work natively and would be simple to emulate in WebGL.

I am considering using D or Go for writing my game, so interfacing with C++ libraries will be difficult, if not impossible. Of course, the language isn't the end goal here, so if using C++ will save considerable time, I'll bite the bullet and use that.

In order to reduce the amount of code I'll have to write for the browser, I'm considering using something simple like Clutter for basic abstractions, which I think will be pretty easy to emulate (layered canvases maybe?).

Does anyone have experience using Clutter for a 3d game?

**Note:**

I haven't used any game development libraries, and I only have limited experience with GUI libraries. I do have HTML+CSS experience, so maybe librocket is a viable solution?

**Edit:**

I'm also trying to be cross platform, so Linux/Mac/Windows.

# Answer
> 2 votes
I'm working with libRocket myself right now and one thing to keep it mind is that it is not an implementation of HTML5 and it uses OpenGL (via custom renderers) as opposed to WebGL. For those you'll want something like Awesomium or Berkelium. The former is not open source (free for companies making less than 100K a year if I recall).

It sounds, however, like you intend to write two separate clients for your game one javascript (WebGL) and another in some language with OpenGL bindings. In that case, if you are comfortable writing the GUI twice AntTweakBar is a nice choice. There are several other discussions on gamedev, here here is a good example.

Unsolicited suggestion - something you might consider is writing a WebGL game (perhaps using the three.js library) and then distributing it natively using Awesomium which supports WebGL as of 1.7.

# Answer
> 0 votes
I recommend you take a look to libgdx. Applications using it can run on HTML and Desktop (plus Android) and used OpenGL ES 2 with Java.

---
Tags: gui, c
---


# Question
Title: Calculate gears rotation for a realtime simulation
I'm trying to do a game with real time simulations of gears. There is a big Gear with inside a smaller gear.

I managed to draw gears with different diameters but equal size teeth, but if i try to move the smaller one inside the bigger one the movement is odd.

See the animated gif:

The biggest gear is in center C1 and the small in the center C2. I calculate C2 position in this way:

```
C2.x = C1.x + C1_RADIUS-C2_RADIUS) * cos(t);
C2.y = C1.y - C1_RADIUS-C2_RADIUS) * sin(t);

```

for t that goes from 0 to TWO\_PI in n steps.

I apply as rotation the angle t, but maybe it is wrong and i have to calculate another rotation for get a perfect joint.

### EDIT:

I am using radians for rotations and I think this is OK.

***My main problem is that I want to achieve a perfect joint between teeth like this example. My teeth are overlapping in some odd way.***

## EDIT

a **working** example can be found here: http://www.openprocessing.org/sketch/83665

# Answer
The large gear has circumference `2πR1` and the small one has circumference `2πR2`, so when the small gear has made a full circle, it has turned `R1/R2` times around itself, **minus one** time because it turned inside the large gear (it would be plus one if the gear was outside).

So when the centre of the inner gear is rotated by angle `t`, the gear itself needs to be rotated by angle `(R1/R2-1)t`.

If the values you handle are tooth counts `N1` and `N2` you can replace `R1/R2` with `N1/N2`.

There is also the issue of the initial rotation. Let `a` be the angle value `atan2(C2.y - C1.y, C2.x - C1.x)`. Apply initial rotation `a` to gear 1. If gear 2 is inside, apply rotation `a` to it, too. If gear 2 is outside, apply a `π+a+h` rotation where `h = π/(2*N2)` is the half angle of a tooth.
> 7 votes

---
Tags: physics, rotation, simulations
---


# Question
Title: Dynamic obstacles avoidance in navigation mesh system
I've built my path finding system with unreal engine, somehow the path finding part works just fine while i can't find a proper way to solve dynamic obstacles avoidance problem. My characters are walking allover the map and collide with each other while they moving. I try to steering them when collision occurs, but this doesn't work well. For example, two characters block on the road while the third one's path is right in the middle of them and he'll get stuck. Can someone tell me the most popular way of doing dynamic avoidance? Thanks a lot.

# Answer
I've never used the UDK before, but I'd solve this problem using pseudo-forcefields. Each object has a convex (most likely spherical or elliptical) forcefield that encompasses the whole object plus a few in-game meters or so of room. These forcefields may combine or affect each other depending on closeness, so that actors won't walk into a V-shaped dead end and get stuck. Now, when an actor begins to enter a forcefield, it is steered away from the center, faster if closer to the object, and won't collide.

PS: Make sure to disable or shrink the forcefield if it contains the goal point.
> 1 votes

---
Tags: path-finding, collision-avoidance, dynamic-mesh
---


# Question
Title: Texture the quad with different parts of texture
I have a 2D quad. Let say it's position is (5,10) and size is (7,11).

I want to texture it with one texture, but using three different parts of it. I want to texture the part of quad from x = 5 to x = 7 with part of texture from U = 0 to U = 0.5 (replaying it after achieving 0.5, so I will have 4 same 0.5-lenght fragments). The second one with some other part of texture (also repeating it) and third in the same style.

But, how to achieve it?

I know that:

```
float2 tc = fmod(input.TexCoord, textureCoordinates.zw - textureCoordinates.xy) + textureCoordinates.xy; //textureCoordinates.xy = fragments' offset

```

Will give me the texture part replaying.

# Answer
> 2 votes
The easiest way to do this is to break the quad into multiple smaller quads. You'll need a to input a coordinate for the texture, and the easiest way to do that is with a vertex.

---
Tags: c++, directx, hlsl, directx11
---


title: Demystifying "chunked level of detail"

text:
# Question
Title: Demystifying "chunked level of detail"
Just recently trying to make sense of implementing a chunked level of detail system in Unity. I'm going to be generating four mesh planes, each with a height map but I guess that isn't too important at the moment. I have a lot of questions after reading up about this technique, I hope this isn't too much to ask all in one go, but I would be extremely grateful for someone to help me make sense of this technique.

> **1** : I can't understand at which point down the *Chunked LOD* pipeline that the mesh gets split into chunks. Is this during the initial mesh generation, or is there a separate algorithm which does this.
>
> **2** : I understand that a Quadtree data structure is used to store the *Chunked LOD* data, I think i'm missing the point a bit, but Is the quadtree storing vertex and triangles data for each subdivision level?
>
> **3a** : How is the camera distance usually calculated. When reading up about quadtree's, Axis-aligned bounding box's are mentioned a lot. In this case would each chunk have a collision bounding box to detect the camera or player is nearby? or is there a better way of doing this? (raycast maybe?)
>
> **3b** : Do the chunks calculate the camera distance themselves?
>
> **4** : Does each chunk have the same "resolution". for example at top level the mesh will be 32x32, will each subdivided node also be 32x32. Example below:

# Answer
**1 : I can't understand at which point down the Chunked LOD pipeline that the mesh gets split into chunks. Is this during the initial mesh generation, or is there a separate algorithm which does this.**

It does not matter. For example, you can integrate the chunking into your mesh generation algorithm. You can even do this dynamically, so that lower levels are added dynamically (e.g. as player moves closer) using a plasma-like refinement algorithm. You can also generate a high-resolution mesh from artist input or elevation measurement data and aggregate it up into all the LOD chunks at asset finalization time. Or you can mix-and-match. It really depends on your application.

**2 : I understand that a Quadtree data structure is used to store the Chunked LOD data, I think i'm missing the point a bit, but Is the quadtree storing vertex and triangles data for each subdivision level?**

Not necessarily. The tree just stores information about the geometry and how to render it. This could mean having an vertex/face list at every tree node. More realistically in this day and age, you would store the handles of the meshes/instances in GPU memory.

**3a : How is the camera distance usually calculated. When reading up about quadtree's, Axis-aligned bounding box's are mentioned a lot. In this case would each chunk have a collision bounding box to detect the camera or player is nearby? or is there a better way of doing this? (raycast maybe?)**

A very cheap and easy option is to use the distance to the centre point of the chunk and then correct it. You know that this distance is always an underestimation: if the centre point is at distance `Z`, this means that half the chunk is closer than that. What we do not know however is the orientation. If we are viewing a chunk of width `w` edge-on, the closest bit of the chunk will be at distance `Z-w`. However, if we are viewing the chunk corner-first, the closest bit will be at distance `Z-sqrt(2)*w`. If you can live with this uncertainty (you almost always can), you are done. Note that you could also correct for the viewing angle using basic trigonometry.

I prefer to calculate the absolute minimum distance from the camera to the chunk to minimize artifacts. In practice, this means doing a point-square distance test. It's a bit more work then calculating distances to the centre points, but it's not like you'll do a zillion of these every frame.

If you can leverage your physics engine to do this then by all means do so, but you really want to think about it more in terms of "distance query" than "collision".

**3b : Do the chunks calculate the camera distance themselves?**

It really depends on the design of your engine. I would recommend keeping the leaves relatively light-weight though. Depending on your platform, just the call overhead of having a few thousand terrain-chunks perform their own update every frame can seriously impact performance.

**4 : Does each chunk have the same "resolution". for example at top level the mesh will be 32x32, will each subdivided node also be 32x32.**

They do not have to, but it's convenient if all chunks take up the same amount of space. Then you can do your (GPU) memory management in units of "chunks". It's also easier to remove / hide the seams between two chunks of different sizes if one resolution is a multiple of the other because they share more vertices. (e.g.: 32x32 and 64x64 is easier to manage than 32x32 and 57x57) (thanks Guiber!). If you have a good reason to vary the chunk geometry size, by all means go for it.
> 13 votes

---
Tags: terrain, level-of-detail, quadtree
---


# Question
Title: Improving SpriteBatch performance for tiles
I realize this is a variation on what has got to be a common question, but after reading several (good answers) I'm no closer to a solution here. So here's my situation:

I'm making a 2D game which has (among some other things) a tiled world, and so, drawing this world implies drawing a jillion tiles each frame (depending on resolution: it's roughly a 64x32 tile with some transparency).

Now I want the user to be able to maximize the game (or fullscreen mode, actually, as its a bit more efficient) and instead of scaling textures (bleagh) this will just allow lots and lots of tiles to be shown at once. Which is great!

But it turns out this makes upward of 2000 tiles on the screen each time, and this is framerate-limiting (I've commented out enough other parts of the game to make sure this is the bottleneck). It gets worse if I use multiple *source rectangles* on the same texture (I use a tilesheet; I believe changing textures entirely makes things worse), or if you tint the tiles, or whatever.

So, the general question is this:

> What are some general methods for improving the drawing of thousands of repetitive sprites?

Answers pertaining to XNA's SpriteBatch would be helpful but I'm equally happy with general theory. Also, any tricks pertaining to this situation in particular (drawing a tiled world efficiently) are also welcome.

I really do want to draw all of them, though, and I need the SpriteMode.BackToFront to be active, because I use the layering quite essentially.

I don't have any easily digested sample code since the method has become somewhat complicated, but no extra tiles are being "drawn," and all the drawing is inside one SpriteBatch.Begin / SpriteBatch.End call.

# Answer
> 2 votes
I'm just going over the things I found important in my game. Some of these you already addressed but I'm listing all of them for completeness.

For you I recommend changed from SpriteMode.BackToFront to SpriteMode.Deffered and having the logic of your code structured that id draws in the correct order. BackToFront/FrontToBack both scale the worst of all the sprite modes because the more items the longer the sorting takes.

The other thing I recommend is making sure that the "new" keyword is not used at all in the drawing loop for your tiles. This advice is pretty generic but without any code (seeing the loop for the tiles would be very helpful) its all I can offer.

Overall I'm more suspicious that the efficiency of how you iterate though and store your data that describes how the tile set is used is the culprit and not the actually render time.

1) XNA doesn't do culling for you so make sure you are culling off tiles that doesn't need to render.

2 ) Avoid putting things on the stack or using the new keyword at all in the loops (see how I create 1 rectangle and only shift the x,y value). Also iterating though what ever data structure holds your data in such a way that its acceded sequentially will help out the cashing and speed things up.

```
        //Init the holder
        _holder = new Rectangle(0, 0, TileWidth, TileHeight);

        //Figure out the min and max tile indices to draw
        var minX = Math.Max((int)Math.Floor((float)worldArea.Left / TileWidth), 0);
        var maxX = Math.Min((int)Math.Ceiling((float)worldArea.Right / TileWidth), Width);

        var minY = Math.Max((int)Math.Floor((float)worldArea.Top / TileHeight), 0);
        var maxY = Math.Min((int)Math.Ceiling((float)worldArea.Bottom / TileHeight), Height);

        foreach (var tileLayer in TileLayers) {
            for (var y = minY; y < maxY; y++) {
                for (var x = minX; x < maxX; x++) {

                    _holder.X = x * TileWidth;
                    _holder.Y = y * TileHeight;

                    var t = tileLayer[y * Width + x];
                    spriteBatch.Draw(
                        t.Texture,
                        _holder,
                        t.SourceRectangle,
                        Color.White,
                        0,
                        Vector2.Zero,
                        t.SpriteEffects,
                        0);
                }
            }
        }

```

3) Also make sure you are using only 1 sprite sheet for all of the tiles.

4) SpriteMode.Deferred is the fastest SpriteMode by far. Its enough of an improvident that often having multiple Begin/End pairs using SpriteMode.Deferred for layers is often faster than using sorting. I would go as far to say and to never use BackToFront or FrontToBack, needing to do so is often a result of not properly abstracting out your rendering code.

---
Tags: xna, sprites, performance
---


# Question
Title: setPosition of Sprite onUpdate in AndEngine
I am trying to get a "highlighter" circle to follow around a sprite, but I am having trouble, I thought I could use the onUpdate method that's available to me in SequenceEntityModifier but it's not working for me. Here is my code:

```
    // make sequence mod with move modifier
    SequenceEntityModifier modifier = new SequenceEntityModifier(myMovemod) {

        @Override
        protected void onModifierFinished(IEntity pItem) {
            // animation finished
            super.onModifierFinished(pItem);
        }

        public float onUpdate(float pSecondsElapsed, IEntity pItem) {

            highlighter.setPosition(player2.getX() - highlighterOffset, player2.getY() - highlighterOffset);
            return pSecondsElapsed;
        }

    };

```

When onUpdate is completely commented out, the sprite moves like I want it to, everything is ok. When I put the onUpdate in, the sprite doesn't move at all. I have a feeling that I am overriding the original onUpdate's actions?

Am I going about this the wrong way? I am new to Java, so please feel free to advise if this isn't going to work.

UPDATE: The player2 is the sprite that I'm trying to get the highlighter to follow.

# Answer
I think you're right - you are overriding `SequenceEntityModfier`'s onUpdate method. Simply call parent's onUpdate method when you are overriding it:

```
@Override
public float onUpdate(float pSecondsElapsed, IEntity pItem) {
    highlighter.setPosition(player2.getX() - highlighterOffset, player2.getY() - highlighterOffset);
    return super.onUpdate(pSecondsElapsed, pItem);
}

```

Also, it's a good idea to use the `@Override` annotation whenever applicable, because that way you'll know if you are overriding a method or not.
> 3 votes

---
Tags: java, android, sprites, andengine
---


title: Remove enemy when bullet hits enemy

text:
# Question
Title: Remove enemy when bullet hits enemy
For my education I have to make a basic game in HTML5 canvas. The game is a shooter game. When you can move left -\> right and space is shoot. When I shoot the bullets will move up. The enemy moves down. When the bullet hits the enemy the enemy has to dissapear and it will gain +1 score. But the enemy will dissapear after it comes up the screen.

Demo: http://jordikroon.nl/test.html

space = shoot + enemy shows up

This is my code:

```
            for (i=0;i<enemyX.length;i++) {

                if(enemyX[i] > canvas.height) {

                    enemyY.splice(i,1);
                    enemyX.splice(i,1);
                 } else {

                    enemyY[i] += 5;
                    moveEnemy(enemyX[i],enemyY[i]);

                 }
            }

            for (i=0;i<bulletX.length;i++) {

                if(bulletY[i] < 0) {
                    bulletY.splice(i,1);
                    bulletX.splice(i,1);
                 } else {

                    bulletY[i] -= 5;
                    moveBullet(bulletX[i],bulletY[i]);

                    for (ib=0;ib<enemyX.length;ib++) {

                      if(bulletX[i] + 50 < enemyX[ib] ||
                              enemyX[ib] + 50 < bulletX[i] ||
                               bulletY[i] + 50 < enemyY[ib] ||
                               enemyY[ib] + 50 < bulletY[i])
                        {
                            ++score;
                            enemyY.splice(i,1);
                            enemyX.splice(i,1);
                        }
                    }
                 }
            }

```

Objects:

```
        function moveBullet(posX,posY) {
            //console.log(posY);
            ctx.arc(posX, (posY-150), 10, 0 , 2 * Math.PI, false);

        }

        function moveEnemy(posX,posY) {

            ctx.rect(posX, posY, 50, 50);
            ctx.fillStyle = '#ffffff';
            ctx.fill();
        }

```

# Answer
You really need to learn to use a debugger. Being able to set a break point and pause execution of the code when it triggers is invaluable. You can see the state of the variables when execution is stopped, this allows you to easily spot errors like this.

As for removing the enemy when the bullet hits it, you can implement a simple collision detection and remove the enemy when the bullet is near enough to the enemy. A simple approach would be to loop over all the enemies and all the bullets, if distance between them is less than the sum of their two radii, then consider them collided and remove both.
> 1 votes

# Answer
```
if(bulletX[i] + 50 < enemyX[ib] ||
    enemyX[ib] + 50 < bulletX[i] ||
    bulletY[i] + 50 < enemyY[ib] ||
    enemyY[ib] + 50 < bulletY[i])

```

Should be

```
if(bulletX[i] + 50 < enemyX[ib] &&
    enemyX[ib] + 50 < bulletX[i] &&
    bulletY[i] + 50 < enemyY[ib] &&
    enemyY[ib] + 50 < bulletY[i])

```

Otherwise they just die as soon as the appear on screen
> 0 votes

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


# Question
Title: Unity3D draw call optimization : static batching VS manually draw mesh with MaterialPropertyBlock
I've read `Unity3D` draw call batching documentation.

I understood it, and I want to use it (or something similar) in order to optimize my application.

My situation is the following:

* I'm drawing hundreds of 3d buildings. Each building can be represented using a `Mesh` (or a SubMesh for each building, but I don't thing this will affect performances)
* Each building can be textured with several combinations of texture patterns(walls, windows,..). Textures are stored into an `Atlas` for optimizaztion (see Texture2d.PackTextures)
* Texture mapping and facade pattern generation is done in fragment shader. The shader can be the same (except for few values) for all buildings, so I'd like to use a `sharedMaterial` in order to optimize parameters passed to the GPU.

The main problem is that, even if I use an Atlas, share the material, and declare the objects as static to use static batching, there are few parameters(very fews, it could be just even a float I guess) that should be different for every draw call.

I don't know exactly how to manage this situation using `Unity3D`. I'm trying 2 different solutions, none of them completely implemented.

**Solution 1**

1. Build a GameObject for each building building (I don't like very much the overhead of a GameObject, anyway..)
2. Prepare each GameObject to be static batched with StaticBatchingUtility.Combine.
3. Pack all texture into an atlas
4. Assign the parent game object of combined batched objects the Material (basically the shader and the atlas)
5. Change some properties in the material before drawing an Object

The problem is the point 5. Let's say I have to assign a different id to an object before drawing it, how can I do this?

* If I use a different material for each object I can't benefit of static batching.
* If I use a sharedMaterial and I modify a material property, all GameObjects will reference the same modified variable

**Solution 2**

1. Build a Mesh for every building (sounds better, no GameObject overhead)
2. Pack all textures into an Atlas
3. Draw each mesh manually using Graphics.DrawMesh
4. Customize each DrawMesh call using a MaterialPropertyBlock

This would solve the issue related to slightly modify material properties for each draw call, but the documentation isn't clear on the following point:

Does several consecutive calls to `Graphic.DrawMesh` with a different MaterialPropertyBlock would cause a new material to be instanced?

Or Unity can understand that I'm modifying just few parameters while using the same material and is able to optimize that (in such a way that the big atlas is passed just once to the GPU)?

# Answer
> 2 votes
1. Textures are stored in vram and don't get deleted even between frames, draw calls just bind these textures to the texture units. Changing a texture has always the same cost, regardless of the texture size. Each state change is expansive. DrawMesh looks pretty good, it should sort all meshes using this material and limit the state changes to the property block and transformations. I expect it to not create a new material, it is a little bit lower than that and only set the MaterialPropertyBlock's properties in addition to the material. Still, unity's batching will no longer work which means one draw call peer subject.
2. As soon as you want to change any material properties per instance static and dynamic batching will not be possible, at least unity's batching methods look that way. Still, if you meshes contain submeshes that may use shared materials, unity should combine these at least.

I don't think unity will give you access to the low level rendering APIs to implement real hardware instancing eg using per instance vertex streams? If the amount of data is really low, you can implement your own static batching, by cloning the meshes and adding the data to each vertex, eg as color attribute, then unity's static batching should work. What a waste of memory... :-)

---
Tags: unity, shaders, optimization
---


# Question
Title: Image loaded from TGA texture isn't displayed correctly
I have a TGA texture containing this image:

The texture is 256x256. So I'm trying to load it and map it to a cube:

```
#import <OpenGL/OpenGL.h>
#import <GLUT/GLUT.h>
#import <stdlib.h>
#import <stdio.h>
#import <assert.h>

GLuint width=640, height=480;
GLuint texture;
const char* const filename= "/Users/ramy/Documents/C/OpenGL/Test/Test/texture.tga";

void init()
{

    // Initialization

    glEnable(GL_DEPTH_TEST);
    glViewport(-500, -500, 1000, 1000);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45, width/(float)height, 1, 1000);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0, 0, -100, 0, 0, 0, 0, 1, 0);

    // Texture

    char bitmap[256][256][3];
    FILE* fp=fopen(filename, "r");
    assert(fp);
    assert(fread(bitmap, 3*sizeof(char), 256*256, fp) == 256*256);
    fclose(fp);

    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 256, 256, 0, GL_RGB, GL_UNSIGNED_BYTE, bitmap);

}

void display()
{
    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, texture);
    glColor3ub(255, 255, 255);

    glBegin(GL_QUADS);
    glVertex3f(0, 0, 0);
    glTexCoord2f(0.0, 0.0);

    glVertex3f(40, 0, 0);
    glTexCoord2f(0.0, 1.0);

    glVertex3f(40, 40, 0);
    glTexCoord2f(1.0, 1.0);

    glVertex3f(0, 40, 0);
    glTexCoord2f(1.0, 0.0);

    glEnd();

    glDisable(GL_TEXTURE_2D);
    glutSwapBuffers();
}

int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
    glutInitWindowPosition(100, 100);
    glutInitWindowSize(width, height);
    glutCreateWindow(argv[0]);
    glutDisplayFunc(display);
    init();
    glutMainLoop();
    return 0;
}

```

But this is what I get when the window loads:

So just half of the image is correctly displayed, and also with different colors.Then if I resize the window I get this:

Magically the image seems to fix itself, even if the colors are wrong.Why?

# Answer
> 8 votes
Your problem is the order in which you specify your vertices and texture coordinates:

```
glVertex3f(0, 0, 0);
glTexCoord2f(0.0, 0.0);

```

should be:

```
glTexCoord2f(0.0, 0.0);
glVertex3f(0, 0, 0);

```

OpenGL is a state machine, and in immediate mode, whenever you call `glVertex3f` the vertex will take on the different attributes (color, texture coordinates, etc.) currently set. The very first vertex that you specify, you have not set texture coordinates, so it will get `(0,0)`. Then you actually call `glTexCoord2f(0.0f, 0.0f)`, and so your second vertex also has texture coordinates of `(0,0)`. This leads to the distortion.

Now, since you are not calling `glutPostRedisplay` anywhere, the `display` function will not be called until it actually needs to be, which happens to be when you resize the window. This time around, your first vertex will have the last texture coordinates that you sent through `glTexCoord2f`, namely:

```
glTexCoord2f(1.0, 0.0);

```

which you set in the *previous* call to `update`. On this frame though, each vertex gets different texture coordinates, so the texture looks normal (but it will actually be rotated).

---
Tags: opengl, textures, c
---


# Question
Title: Networking for RTS games with lockstep using UDP
Apparently from what I can gather Starcraft 2 moved to UDP in a patch. Now obviously with fps games there is no dispute that UDP is the only way to go. But with RTS games what benefits does UDP give over TCP given that the network model is lockstep?

I suppose another way to phrase this is: what features of TCP make TCP inferior compared to UDP with resend, etc. implemented in the context of rts lockstep networking model?

# Answer
> 1 votes
While UDP is bad at emulating TCP's feature-set as a whole, you could still see a potential performance benefit from picking and choosing features for different kinds of packets, e.g., one might choose to use UDP for voice chat functionality (where we really don't need things to stay in perfect lock-step anyway) and TCP for actual gameplay. Further, we could use UDP for some parts of gameplay, with some weak synchronization done through spare packets.

This would make your game even hungrier for network resources, but might have some sort of performance benefit if done right.

# Answer
> 2 votes
Because TCP **buffers** data at **both** the client (prior to sending a packet) and the remote host (remote host might not be notified a packet was received until several packets are received and combined together into a data buffer). See my article why TCP is unsuitable for games.

You hear it said, but you don't believe it until you try it (or until a major game vendor tries it then has to patch).

From the article:

> You know that when you call .send() on a TCP socket, TCP WILL NOT NECESSARILY DELIVER THE MESSAGE IMMEDIATELY! TCP has a buffer BOTH at the sender (messages might pile up for a number of seconds before actually being fired off across the net) **AND** at the recipient (messages might stock up for a number of seconds before the remote user’s TCP subsystem alerts HIM that you have sent some bytes). This is precisely what makes TCP so inappropriate for use for games: it might withhold the data from you, even if its already at your machine, as you can see here, for up to 2 seconds (or more!).

# Answer
> 0 votes
You can build a layer of redundancy on top of UDP that allows you to:

* Recover your message even if you've lost packets, using a multi datagram checksum.
* Spam the other machine you are connecting to until you receive an ack in your layer.

Both strategies will allow you to minimise the effect of the round trip travel when you are losing packets.

You also avoid getting burnt by the tcp slow start if you are regularly dropping packets due to issues other than network congestion.

---
Tags: networking, multiplayer, rts, synchronization, packet
---


# Question
Title: Assigning a different texture based on picking
I'm making a game using XNA. I have some simple objects like cube and sphere, and I would like to change the texture of one face of these objects based on picking. That is, when the cursor is over one face, it turns red. The only way I've seen to do this is to overload the content processor as here: http://xbox.create.msdn.com/en-US/education/catalog/sample/picking\_triangle

but it seems like it shouldn't be this complicated. I'm using .x models, and would like to be able to implement this for more complex models in the future beyond cubes/spheres/etc. Is this the best/only way to go about it? I'll figure that out if that's what is necessary, but it seems that there would be a simpler solution to load a different texture to a face than I've seen, I just don't know what it is.

# Answer
Triangle picking aside, generally you can only have 1 texture per draw call. (Technically, I think it's effectively one shader effect per vertex buffer. If multi-texturing occurs here then it would be done by having multiple texture samplers in the shader, or by using a texture atlas) What this means is you need to split models up into parts when you want these parts to have differing textures.
> 1 votes

# Answer
If you know the name of the texture that's highlighted, you can simply do this to first get the Texture2D:

```
public void ChangeTexture(Effect effect, string name, Texture2D newTexture, out Texture2D oldTexture)
{
    oldTexture = effect.Parameters[@name].GetValueTexture2D();
    effect.Parameters[@name].SetValue(newTexture);
}

```

then store the old texture somewhere and when the area that's highlighted is changed, you simply restore the texture the same way.
> 0 votes

---
Tags: xna, textures, picking
---


# Question
Title: Splitting a texture atlas into separate images
> **Possible Duplicate:**
> How to decompose sprite sheet

I'm doing a port of an existing game and the designer no longer has all of the original art; he only has the resulting texture atlases he used when developing for iPad. The tool I'm using won't support these files so I need to break them back out into separate PNG files.

I'm hoping someone knows of a software tool that does this. PC software would be preferred in this case, but Mac would suffice.

## Edit

To add some clarification; these texture atlases are in a simple gridded layout with even distribution and not packed. No need to tie back to descriptor files; I just need a simple animation splitter type of tool where I can tell it the size of a frame, point it to the image and from that get a set of separate images.

# Answer
Use ImageMagick.

Sample command-line parameters to split an atlas of any size named beholder.png with an 84x84 grid:

```
convert beholder.png +gravity -crop 84x84 +repage +adjoin test_%d.png

```
> 1 votes

# Answer
Manually/Automatically splitting the atlas without sprite info is hard to get right. The atlases you have should come along with a Data file that has all the sprites locations, sizes and offsets. You might try looking for it and decoding.

In the best case scenario - you need to rig your game to read the atlases and info from the original atlases format, without inbetween converting. Because atlases are much more efficient than single images (maybe you just convert the fileformat from your\_format -\> PNG, but keep the sprite data).

EDIT: After seeing you refer to evenly spaced sprites, I would suggest just writing a custom tool. 30-45min of work and you are done.
> 0 votes

---
Tags: textures, animation, image
---