# Question
Title: this.BoundingBox.Intersects(Wall[0].BoundingBox) not working properly
I seem to be having this problem a lot, I'm still learning XNA / C# and well, trying to make a classic paddle and ball game. The problem I run into (and after debugging have no answer) is that everytime I run my game and press either of the movement keys, the Paddle won't move. Debugging shows that it never gets to the movement part, but I can't understand why not?

Here's my code:

```
    // This is the If statement for checking Left movement.
    if (keyboardState.IsKeyDown(Keys.Left) || keyboardState.IsKeyDown(Keys.A))
        {
            if (!CheckCollision(walls[0]))
            {
                Location.X -= Velocity;
            }
        }

    //This is the CheckCollision(Wall wall) boolean
    public bool CheckCollision(Wall wall)
    {
        if (this.BoundingBox.Intersects(wall.BoundingBox))
        {
            return true;
        }
        return false;
    }

```

As far as I can tell there should be absolutely no problem with this, I initialize the bounding box in the constructor whenever a new instance of Walls and Paddle is created.

```
   this.BoundingBox = new Rectangle(0, 0, Sprite.Width, Sprite.Height);

```

Any idea as to why this isn't working?

I have previously succeeded with using the whole Location.X \< Wall.Location.X + Wall.Texture.Width code... But to me that seems like too much coding if a simple boolean check could be done.

# Answer
I'm not an XNA user, so this is based off of some very quick MSDN reading and general knowledge.

That constructor indicates that both bounding boxes are at the origin (0,0), which means they'll always be intersecting.

Generally you need to recalculate bounding boxes whenever an object's position changes, and of course correctly initialize the bounding boxes when the object is created.

Bounding boxes are usually stored as two vectors, a minimum position and a maximum position. XNA has a BoundingBox structure that does this. Using that, if you have the a position and a width/height, you can calculate a half vector as:

```
half = [width/2, height/2]

```

and then the min and max positions as:

```
min = position - half
max = position + half

```

If you want to keep using Rectangle, then you need to use the position instead of 0,0. Knowing that the upper-left corner of the rectangle is it's position (I think; again, not an XNA user), the "min" position is the rectangle's position:

```
half = [width/2, height/2]
min = position - half
rect = new Rectangle(min.x, min.y, width, height)

```

Of course you can just store your actual object positions as the upper-left corner and avoid the need to calculate a half-vector, but this is not ideal. A great deal of other things in game math are going to be a lot easier if your positions are centers rather than corners of bounding boxes.
> 0 votes

---
Tags: c#, 2d, collision-detection, xna-4.0
---


# Question
Title: The purpose of using invert and transpose
In openGl ES and the World of 3D - why use the invers matrix?

The thing is that I dont have any intuition to, why it is used, therefore please correct me:

As fare as I understand, it is used in shaders - and can help you to figure out the opposite direction of the normals?

Invers in ordinary numbers is like; The product of a number and its multiplicative inverse is 1. Observe that 3/5 * 5/3 = 1. In a matrix this will give you the Identity Matrix, which is the base coordinate system or the orion of the World space - right. But the invers is - some other coordinate system?

You can use the transpose(Row-major order to Column-major order) of a square matrix to find the inverted matrix, as calculating the invers is process heavy - and the transpose is giving you the inverted matrix as a bi product?

Again, I am looking for getting some intuition of this - and therefore be able to use it as intended. Thank you for any reply that will guide me in the right direction.

Regards

# Answer
> 9 votes
A matrix is used to convert a vector from one coordinate system to another (say, from coordinate system 'A' to coordinate system 'B').

The inverse of a matrix is a matrix which converts the other direction (say, from 'B' back into 'A')

In games, we commonly have a matrix which will transform positions from world-space into homogenous eye-space, since rendering all happens in homogenous eye-space. But homogenous coordinates can be difficult to work with, so some types of shaders want to convert those homogenous camera-relative coordinates back into world coordinates, so inverting the matrix allows us to easily convert those coordinates back into world-space inside the shader.

In models we often have a hierarchy, where each piece of the model has a matrix which describes how to convert from its local coordinate system (used by its own vertices), to the coordinate system used by its parent, so that you can multiply a vertex's position by that matrix to find where the vertex is relative to the parent. (And if you then multiply by the parent's matrix, and the parent's parent's matrix, and so on, you'll eventually find the vertex's absolute world position) If you invert the child-to-parent matrix, though, it allows you to go the other way; take one of the parent's vertices, multiply its position by the matrix, and the result will tell you where that position would be, expressed inside the child's coordinate system (and thus, relative to its vertices).

In a game, we normally specify matrices going just one direction; from deeply nested renderable objects, through less-deeply-nested renderable objects, through a view matrix, and finally into homogenous eye-space for rendering. Which is normally all we need, since all we normally want to do is to find world-space or render-space. But for those unusual cases where we really do want to know where a world-space point is relative to a nested object (or which direction a light is shining relative to a movable object, or etc), then inverting matrices allows us to transform vectors between coordinate systems in the opposite direction.

# Answer
> 2 votes
Trevor gave a good explanation about matrices, but since your question included "can help you to figure out the opposite direction of the normals?", I think normal matrices should be mentioned as well. Normal matrix is needed for transforming normals when the modelview matrix has more than just translation and rotation. It can be calculated from the modelview matrix with transpose of the inverse.

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


# Question
Title: How to use the float value from noise function in voxel terrain?
I'm using Unity, although this question is not really specific to that engine.

Im also using an asset from the store called Coherent Noise. It has some neat noise functionality built it.

I am using those functions to produce some noise values. I am getting a value between 0 and 1 (floats).

I have an array of blocks (for minecraft like voxel terrain) and I am confused on how to use this float value for terrain?

Do I do something like \<= 0 == Solid block etc?

I am confused on how to use the floating values that the noise functions produce to use for height values of an array of say a height of 16.

# Answer
> 3 votes
If you're using the noise for height values (2D noise), then you multiply the float value by the maximum height of your world. This will give you a height value somewhere between 0 and the maximum height of your world.

If you're using the noise to determine if a voxel is solid or not (3D noise), you can do as you suggest and pick a threshold value that defines when the breaking point is between solid/air. Since your values are from 0 to 1 you'd want to pick some small value that's greater than zero, otherwise you won't be getting any empty voxels.

The second option is going to be harder to get right. You'll need to implement the noise generation in a controlled manner. i.e. you'll want to have voxels more likely to be solid at small `y` values and more likely to be air at large `y` vaules. If it's completely random you'll have land and ground so mixed up the landscape won't resemble landscape at all. See my answer here to learn more about implementing terrain using noise as a density function.

---
Tags: unity, perlin-noise
---


# Question
Title: Are there any good guides for making mods for Minecraft?
I've been coding in Java for 5 months at work now, and having past experience with programming in other languages, modifying existing code at Uni etc. I feel like I want to get started on (read: continue learning to program by) modding with minecraft.

I know what I *need*, but not exactly how to do so. I once saw some good guides on the minecraft forum, but they all explained how to write in java, hows different classes in the code work etc. I'm more interested in how you decompile the code, write your own separate from the main 'trunk' of minecraft and then package it to install with a tool like 'Magic Loader'.

My issue with these guides is that they always relied on being in windows, but I'm primarily a linux user, and the guides on the forums only seemed to assume you were on a Windows box.

So is there a good 'walkthrough' for modding for Minecraft? Especially one where it assumes or at least allows for the fact you are in linux?

# Answer
> 3 votes
Check out MCP! That's Minecraft Coder's Pack. It takes care of all the compilation/building etc... You just need to worry about modding :)

Setup tutorials: (one of these should have you covered)
http://mcp.ocean-labs.de/index.php/Using\_MCP\_video\_collection

How to set up with Eclipse (after main setup):
http://mcp.ocean-labs.de/index.php/MCP\_Mod\_System:\_Eclipse\_Setup\_Tutorial

Some itneresting tutorials:
http://mcp.ocean-labs.de/index.php/Category:Tutorials

EDIT: Fail, you already knew about MCP! oh well, the tutorials still stand :)

# Answer
> 2 votes
If you do have some Java experience you should read the official MinecraftWiki Mods

http://www.minecraftwiki.net/wiki/Mods

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


# Question
Title: Can't load vector font in Nuclex Framework
I've been trying to get this to work for the last 2 hours and I'm not getting what I'm doing wrong...

I've added `Nuclex.TrueTypeImporter` to my references in my content and I've added `Nuclex.Fonts` & `Nuclex.Graphics` in my main project.

I've put `Arial-24-Vector.spritefon`t & `Lindsey.spritefont` in the root of my content directory.

```
_spriteFont = Content.Load<SpriteFont>("Lindsey"); // works

_testFont = Content.Load<VectorFont>("Arial-24-Vector"); // crashes

```

I get this error on the \_testFont line:

File contains `Microsoft.Xna.Framework.Graphics.SpriteFont` but trying to load as `Nuclex.Fonts.VectorFont`.

So I've searched around and by the looks of it it has something to do with the content importer & the content processor. For the content importer I have no new choices, so I leave it as it is, `Sprite Font Description - XNA Framework` for content processor and I select `Vector Font - Nuclex Framework` And then I try to run it.

```
_testFont = Content.Load<VectorFont>("Arial-24-Vector"); // crashes again

```

I get the following error

```
Error loading "Arial-24-Vector".

```

It does work if I load a sprite, so it's not a pathing problem. I've checked the samples, they do work, but I think they also use a different version of the XNA framework because in my version the "Content" class starts with a capital letter.

I'm at a loss, so I ask here.

**Edit:**

Something super weird is going on. I've just added the following two lines to a method inside `FreeTypeFontProcessor::FreeTypeFontProcessor(
 Microsoft::Xna::Framework::Content::Pipeline::Graphics::FontDescription ^fontDescription,
 FontHinter hinter`, just to check if code would even get there:

```
System::Console::WriteLine("I AM HEEREEE");
System::Console::ReadLine();

```

So, I compile it, put it in my project, I run it and... it works! What the hell?? This is weird because I've downloaded the binaries, they didn't work, I've compiled the binaries myself. didn't work either, but now I make a small change to the code and it works? \>**_**\>.

So, now I remove the two lines, compile it again and it works again. Someone care to elaborate what is going on? Probably some weird caching problem!

# Answer
> 2 votes
I had exactly same error as you. It was fixed when I cleaned solution and build it again as @Roy T. suggested.

I think that for some reason Content doesn't rebuild correctly without a clean first.

---
Tags: xna, c#, fonts
---


# Question
Title: Unity scaling instantiated GameObject at Start() doesn't "keep"
I have a very simple scenario:

* A box-like Prefab which is imported from Blender automatically (I have the .blend file in the Assets folder).
* A script that has two public GameObject fields. In one I place the above prefab, and in the other I place a terrain object (which I've created in Unity's graphical view):

public Collider terrain;

public GameObject aStarCellHighlightPrefab;
* This script is attached to the camera.

The idea is to have the Blender prefab instantiated, have the terrain set as its parent, and then scale said prefab instance up.

I first did it like this, in the Start() method:

```
void Start () {
        cursorPositionOnTerrain = new RaycastHit();
        aStarCellHighlight = (GameObject)Instantiate(aStarCellHighlightPrefab, new Vector3(300,300,300), terrain.transform.rotation);
        aStarCellHighlight.name = "cellHighlight";
        aStarCellHighlight.transform.parent = terrain.transform;
        aStarCellHighlight.transform.localScale = new Vector3(100,100,100);
    }

```

and first thought it didn't work. However later I noticed that it did in fact work, in the sense where the scale was applied right at the start, but then right after the prefab instance came back to its initial scale.

Putting the scale code in the Update() methods fixes it in the sense where now it stays scaled all the time:

```
void Update () {
     aStarCellHighlight.transform.localScale = new Vector3(100,100,100);
     //...
}

```

However I've noticed that when I run this code, the object is first displayed without the scale being applied, and it takes about 5-10 seconds for the scale to happen. During this time everything works fine (like input and logging, etc). The scene is very simple, it's not like it has a lot of stuff to load or anything (there's a Ray cast from the camera on to the terrain, but that seems to happen without such delays).

My (2 part) question is:

1. Why doesn't it take the scale transform when I do it at the beginning in the Start() method. Why do I have to keep scaling it in the Update() method?
2. Why does it take so long for the scale to "apply/show up".

==UPDATE==

As per comments, here's a detailed description of my scene:

1 camera, 1 terrain (with a bunch of brushed in deformations), 1 directional light. I also have a .blend file in my Assets folder, which is automatically imported and I get my aStarCellHighlight prefab which is a cube with a transparency/diffuse texture:

to the camera I have attached to following script, to which I've then "bound" the terrain and aStarCellHighlight in the corresponding public fields:

```
public class RTSCamera : MonoBehaviour {

    public Collider terrain;
    public GameObject aStarCellHighlightPrefab;

    private bool isCursorOnTerrain;
    private RaycastHit cursorPositionOnTerrain;
    private GameObject aStarCellHighlight;

    void Start () {
        cursorPositionOnTerrain = new RaycastHit();
        aStarCellHighlight = (GameObject)Instantiate(aStarCellHighlightPrefab, terrain.transform.position, terrain.transform.rotation);
        aStarCellHighlight.name = "cellHighlight";
        aStarCellHighlight.transform.parent = terrain.transform;
    }

    void Update () {
        trackCursorOnTerrain(false);
        placeCellHighLight();
    }

    private void trackCursorOnTerrain(bool debug) {
        Ray ray = this.camera.ScreenPointToRay(Input.mousePosition);

        isCursorOnTerrain = terrain.Raycast(ray,out cursorPositionOnTerrain, 5000);
        if(debug) {
            if(isCursorOnTerrain) {
                Debug.DrawLine (ray.origin, cursorPositionOnTerrain.point);
                Debug.Log("terrainRight="+cursorPositionOnTerrain.point.x+" terrainUp="+cursorPositionOnTerrain.point.z+" terrainAltitude="+cursorPositionOnTerrain.point.y);
            } else {
                Debug.DrawLine (ray.origin, ray.GetPoint(5000));
            }
        }
    }

    private void placeCellHighLight() {
        aStarCellHighlight.transform.localScale = new Vector3(50,50,200);
        if(isCursorOnTerrain) {
            aStarCellHighlight.transform.localPosition = cursorPositionOnTerrain.point + new Vector3(0,200,0);
        } else {
            aStarCellHighlight.transform.localPosition = Vector3.zero + new Vector3(0,200,0);
        }
    }
}

```

The script is supposed to basically draw a ray from camera's mouse cursor screen position to terrain, and then instantiate the Blender cube prefab, add is at a child of terrain, scale it to a visible size, and move it around on the terrain to where the mouse is, you know , "projecting" or whatever it is called.

when I hit play I the Blender prefab instance is created right away, it is shown as a descendat of terrain, is just not scaled properlly. Also if I move the mouse right away, the cube doesn't move with it:

Finally, if I just wait 10-20 seconds, the cube gets scaled, and now it moves with the cursor on the terrain:

Thanks for all any help!

# Answer
Well, I've solved it. I'm not very sure what was happening, but due to the fact that I've created and erased an then re-created the terrain multiple times in the scene (each time adding it to some scripts, etc), at some point something got jumbled up in Unity, probably because of this. Long story short, I created a new Unity project, copied in all my scripts and re created all the game elements and re-attached them to the scripts, and now everything works ok: I only need to scale the Blender object in the Start() method (and it stays scaled), and also it is transformed and shows up right from the start when I play the game.

Thanks you to everyone for the help, the hints they gave pointed me in the right direction.
> 1 votes

# Answer
The object you instanciate, does it have some scripts attached to it? The instanciated object doesn't run its awake()/start() until the next chance it gets and *not* when you call Instanciate(). In the following code

```
class ObjectA{
    public ObjectB anObjectPrefab;
    void Start(){
        Instanciate(anObjectPrefab);
        FunctionA();
    }
    void FunctionA() { ... }
}

class ObjectB{
    void Start(){ ... }
}

```

The execution order will be:

* ObjectA.Start()
* ObjectA.FunctionA()
* \[Possibly other objects Starts()\]
* ObjectB.Start()

So as you can see, if you are doing some scaling in ObjectB.Start() and expect that setting the scale right after the instanciation will overwrite the values, that won't work... Of course that's just one possibility, but it did happen to me a few times so that's the first thing that jump to my mind.
> 1 votes

---
Tags: unity, gameobject, transformation
---


# Question
Title: Client-Server MMOG & data structures sync when joining / playing
After reading a few articles on MMOG architecture, there is still one point on which I cannot find much information: it has to do with how you keep in sync server data on the client, when you join, and while you play. A pretty vague question, I agree. Let me refine it:

Let's say we have an MMOG virtual world subdivided into geographical cells. A player in a cell is mostly interested in what happens in the cell itself, and all the surrounding cells, not more. When joining the game for the first time, the only thing we can do is send some sort of "database dump" of the interesting cells to the client.

When playing, I guess it would be very inefficient to do the same thing regularly. I imagine the best thing to do is to send "deltas" to the client, which would allow keeping the local database in sync.

Now let's say the player moves, and arrives in another cell. Surrounding cells change, and for all the new cells the player subscribes, the same technique as used when joining the game has to be used: some sort of "database dump".

This mechanic of joining/moving in a cell-based MMOG virtual world interests me, and I was wondering if there were tried and tested techniques in this domain.

Thanks!

# Answer
> 3 votes
The phrase that you're looking for is relevancy sets. Each player has their own list of objects that they care about (That are relevant to them.) As objects are removed from this list, a message is sent down to remove it from the client. As objects get added to this list, a creation message is sent down to the object. During the course of game play as an object state changes, messages are created to update that state on all clients that consider it relevant to them.

This is a bit of a simplification as some systems use multiple messages for create. (IE: Block out a model here, details will be coming, or here's the model and textures but no RPG mechanics are sent yet.)

I probably linked it a few times before, but a paper that discusses this is Distributed Object Views and was used on an MMO I worked on awhile ago.

Rereading what you asked, one thing to note is that commonly a cell can be subdivided per client. IE: The cell may be the entire portion of the world that the process owns, but for cheat-prevention and bandwidth issues the cell may only consider objects that are within 20-40 meters to be relevant to the player. The real tricky part is what happens when the player is within 20-40 meters of a cell boundary? At that point they are seeing objects from multiple cells that are relevant to them and those other cells need to proxy their data through the cell the player is in.

---
Tags: mmo, synchronization
---


title: XNA Per-Polygon Collision Check

text:
# Question
Title: XNA Per-Polygon Collision Check
I'm working on a project in XNA for WP7 with a low-poly environment, my problem is I need to setup a working per-polygon collision check between 2 or more 3d meshes.

I've checked tons of tutorials but all of them use bounding-boxes, bounding-spheres,rays etc., but what I really need is a VERY precise way of checking if the polygons of two distinct models have intersected or not.

If you could redirect me to an example or at least give me some pointers I would be grateful.

# Answer
> 0 votes
Take a look at:

1. http://www.metanetsoftware.com/technique/tutorialA.html
2. http://www.metanetsoftware.com/technique/tutorialB.html

Also look for the term: AAOB rather than AABB.

SAT (or Separating Axis Theorem) is also a good start, it's an approach to detect and solve collisions between objects of any shape. Refer to: http://www.codezealot.org/archives/55

---
Tags: xna, collision-detection, 3d-meshes, windows-phone-7
---


# Question
Title: how to devise a scoring algorithm based on elapsed time and number of moves
I want to devise an score algo for my game. I want to award high scores to players who achieve the goal in minimum time and least number of moves.

I did this but its not going correctly:

```
var score = ((finishSeconds / moveCount).toFixed(2) * 100).toFixed(0);

```

# Answer
> 4 votes
Smaller numbers of either is better right? So how do we make sure that larger numbers make the score smaller? We divide `1` by that number. The larger the number, the smaller the parts `1` is broken into. We can change that slightly to allow for other minimums. See the example for a perfect score being calculated when the seconds elapsed is 1 and the moves taken are 1. Using this allows you to set these numbers higher and allow people to get better than perfect if they finish in fewer moves or less time than you anticipated the best to be.

```
var minimumMoves = 1;
var minimumTime = 1;
var score = ((minimumTime/finishedSeconds)*(minimumMoves/moveCount))*highestScorePossible)

```

By example, where a minimum time is 20 seconds and minimum moves is 5. The player finished in 38 seconds and 6 moves, where the highscore is 100:

```
(20/38 * 5/6) * 100 = 43.85

```

Where another player did it in 24 seconds with 5 moves:

```
(20/24 * 5/5) * 100 = 83.33

```

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


title: Importing Models from Maya to OpenGL

text:
# Question
Title: Importing Models from Maya to OpenGL
I am looking for ways to import models to my game project. I am using Maya as modelling software, and GLUT for windowing of my game. I found this great parser, it imports all the textures and normal vectors, but it is compatible with .obj files of 3dsMAX. I tried to use it with Maya obj's, and it turned out that Maya's obj files are a bit different from former one, thus it cannot parse them.

If you know any way to convert Maya obj files to 3dsMax obj files, that would be acceptable as well as a new parser for Maya obj files.

# Answer
I figured this out. It appears that I need to triangulate my model in Maya before I export it. It is working now.

I think I am going to leave this post for future reference.
> 0 votes

---
Tags: opengl, models, maya
---


# Question
Title: enemy behavior with boundary to change direction
I'm doing space shooter kind of game, the logic is to reflect the enemy if it hits the boundary. With my logic, sometimes enemy behaves like flickering instead of changing the velocity. It's like trapped in the boundary and checking for if loops. This is my code for velocity changing:

```
if(this->enemyPos.x>14)
{
   this->enemyVel.x = -this->enemyVel.x;
}

if(this->enemyPos.x<-14)
{
   this->enemyVel.x = -this->enemyVel.x;
}

```

How can I get around this? Its going out of boundary and don't know where to go and after sometimes its coming into field. I know whats the problem is, I dont know how to get around this problem.

# Answer
Your problem is that you are always toggling the enemy's velocity, even if it's already moving in the direction you want.

Say that in frame 1 the enemy is moving left and is at position -15. Your check now makes it moving right. At frame 2, it's moving right and at position -14.001, due to rounding errors, frame time differences, etc. Your check now makes it going left again.

Either set your velocity to the value you want explicitly, e.g.

```
velocity.x = abs(velocity.x); // go right
velocity.x = -abs(velocity.x); // go left

```

Or change your checks to include both position and direction of movement, e.g.

```
if (position.x < -14 && velocity.x < 0) ...

```
> 3 votes

---
Tags: c++, opengl, 2d, collision-detection, movement
---


title: Logarithmic spacing of FFT subbands

text:
# Question
Title: Logarithmic spacing of FFT subbands
I'm trying to do the examples within the GameDev.net Beat Detection article ( http://archive.gamedev.net/archive/reference/programming/features/beatdetection/index.html ) I have no issue with performing a FFT and getting the frequency data and doing most of the article. I'm running into trouble though in the section 2.B, Enhancements and beat decision factors.

in this section the author gives 3 equations numbered R10-R12 to be used to determine how many bins go into each subband:

**R10 - Linear increase of the width of the subband with its index**

**R11 - We can choose for example the width of the first subband**

**R12 - The sum of all the widths must not exceed 1024**

He says the following in the article: "Once you have equations (R11) and (R12) it is fairly easy to extract 'a' and 'b', and thus to find the law of the 'wi'. This calculus of 'a' and 'b' must be made manually and 'a' and 'b' defined as constants in the source; indeed they do not vary during the song."

However, I cannot seem to understand how these values are calculated...I'm probably missing something simple, but learning fourier analysis in a couple of weeks has left me Decimated-in-Mind and I cannot seem to see it.

# Answer
> 1 votes
All he's saying is humans are more sensitive to low frequency sound. That is, it's easier for humans to detect that there is even a difference between 65Hz and 69Hz than 2093Hz and 2097Hz.

2093Hz and 2097Hz would pretty much sound the same to a human. But 65Hz is C2 on the piano and 69Hz is C#2 -- so two completely distinct notes on a piano.

So he says "just make SMALLER bins for low frequency and BIGGER bins for high frequency"

In

```
w_i = a*i + b

```

`i` presumably indexes from 1 to #subbands you're using. For the first subband, the WIDTH is small:

```
w_1 = a + b

```

For the 7th subband, the width is nearly 7 times the width of the 1st subband

```
w_7 = 7a + b

```

He goes on to say that `a` and `b` are basically arbitrary choice depending on the size of your buffers etc. `b` is sort of a "bin size minimum" and `a` is the size that linearly scales.

If we choose `a=10` and `b=10` for example, then we get

```
w_1 = 20
w_2 = 30
w_3 = 40
...

w_32 = 330

```

`R12` states the SUM of all the bins can't exceed 1024 (buffer size), so actually that particular choice of `a` and `b` wouldn't work (a is too large). You'd have to choose `a` and `b` so that the sum of `w_1`..`w_32` is less than 1024 (unless you increase the buffer size)

# Answer
> 1 votes
R12 defines a constraint between a and b, once you've picked n (the number of subbands). For instance, with n = 32 the equation is 32\*b + 528\*a = 1024. It sounds like a and b are supposed to be integers, so ideally one would find a solution to this equation such that both a and b are integers.

However, in general such a solution won't exist (or there will only be a "trivial" solution with a = 0, which probably isn't what you want). So I suppose that a and b have to be allowed to take fractional values and you would round off the size of each subband to the nearest integer. Or maybe you could do something trickier like distributing the power of a bin into two adjacent subbands, when it falls on the edge between them.

In that case you would just have to pick a value for b and solve for the resulting a (or vice versa).

---
Tags: game-design, mathematics
---


# Question
Title: Should I use float, double, or decimal for stats, position, etc?
The problem with float and double is that they are not exact. If you are to do something like store replays, the values would have to be exact.

The problems with decimal is that they are approximately 16x slower (confirmed by searching and personal testing) than floats and doubles.

Couldn't Vector2s be another problem because they use floats internally for all the components?

How do other games solve this problem? I'm sure they must use floats and doubles but aren't they not deterministic across platforms and different architecture?

The replay files for games like SC2 run in a linear fashion so you cannot skip ahead so how do they solve the determinism issue with floating point numbers?

# Answer
Ideal replay systems don't depend on the exactness of floating point numbers.

All of the actual logic and events can be recorded. That is, you don't just record "fired bullet at pos 3.4,5.2 at vel 1.2,-0.8" and then expect the client to re-execute the bullet collision logic. You record both that the bullet was fired and that the bullet collided with something (and where) and what the results of that collision where. At appropriate time points, the replay data will "correct" any values (that is, after an object bounces, the replay records the new position and velocity, rather than expecting the client to recalculate those).

This is the exact same as network synchronization. A lot of games with replay systems in fact reuse their network infrastructure, since replay data can be the exact same as the data sent to spectator clients.

Thus your replays might at worst have some very slight discrepancies *visually* (highly unlikely to be noticeable), but the replay will still play out mechanically the exact same. Those discrepancies will not be vital to the game itself, and hence you can completely ignore the potential inaccuracies of floating point numbers.

Also keep in mind that those discrepancies will never really happen on most real hardware, because a replay of SC2 is always played back on the same CPU architecture. That is, you aren't going to be recording a session on an x86 CPU and then playing it back on an ARM CPU, because there is only an x86 SC2 client. Same goes for most other games.

The only "hard" part is going to be synchronizing time steps so that events are firing in the proper sequence and at the proper speed, but that's mostly solved by just using fixed time steps.
> 7 votes

---
Tags: c#, floating-point, replays
---


# Question
Title: Translating an Object to a certain Vector 3 in OpenGL and Java LWJGL
So after almost two hours, I got the hang of using glTranslated() (with Java and LWJGL). If I am correct, applying glTranslated on an object moves that object with the x,y,z relative to the previously moved object. I believe the correct term for this is local vs global, global being the one I want. I was wondering if there was a way to translate an object to a specific XYZ position, or relative to the origin. Thanks!

(Code or other details can be supplied if it helps, just let me know. Also sorry if this is a noob comment, Im very new to OpenGL.)

# Answer
Thanks for everyone's help. However, I found what I was looking for, and that was

```
GL11.glPushMatrix();
drawCube(x, y, z); //parameters for the glTranslated();
GL11.glPopMatrix();

```

Thanks again!
> 1 votes

# Answer
To move an object from it current position to some other specific position you need to translate by a displacement vector. The displacement vector will be the difference between the desired position and current position.

```
glTranslatef(desired.x-current.x,desired.y-current.y, desired.z-current.z);

```
> 0 votes

# Answer
Since you brought up the concept of local and global coordinates, then you should also indicate *where* the origin is.

The steps to move the object to a specific XYZ relative to the origin of a specific space is as such:

1. find out the object position in the target space coordinate or;
2. find out the target position in the object space coordinate
3. glTranslate() by the displacement vector in the same coordinate space as per Ken's method

In a professional set up, objects are usually in a hierarchical manner e.g. in an oct-tree; in scene graph; in skeletal animation etc, then you may need to use a recursive function to compute the object position from the object space up its parent space / nodes until you reach the target space where your origin is located.
> 0 votes

---
Tags: opengl, java, lwjgl
---


# Question
Title: relationship between the model and the renderer
I tried to build a simple graphics engine, and faced with this problems:

i have a list of models that i need to draw, and object (renderer) that implements IRenderer interface with method DrawObject(Object\* obj). Implementation of renderer depends on using graphics library (opengl/directx).

1st question: model should not know nothing about renderer implementation, but in this case where can i hold (cache) information that depends on renderer implementation? For example, if model have this definition:

```
class Model
{
public:
    Model();

    Vertex* GetVertices() const;

private:
    Vertex* m_vertices;
};
```

what is the best way to cache, for example, vertex buffer of this model for dx11? Hold it in renderer object?
2nd question: what is the best way for model to say renderer HOW it must be rendered (for example with texture, bump mapping, or may be just in one color). I thought it can be done with flags, like this:

```
model->SetRenderOptions(RENDER_TEXTURE | RENDER_BUMPMAPPING | RENDER_LIGHTING);

```

and in Renderer::DrawModel method check for each flag.

But looks like it will become uncomfortable with the options count growth...

# Answer
> 0 votes
To answer your first question: I'm not sure. I haven't cached vertex information before. But I would use a different interface to represent the buffers, and then have one implementation for OpenGL and one for DirectX. I would then have a separate class ( manager ) for creating and mapping buffers to objects. This way you can ask the manager for a buffer, or create a new one if there isn't one already. You might do the asking inside the renderer's DrawObject method, or you might have a separate method that first checks / creates the caches and then calls the renderer. Again, I haven't seen this done before, so my answer is just the first thing that comes to mind. Also, when designing your classes try making them highly cohesive ( they should have one and only one responsibility ). Keep this in mind when things get messy or you're not sure what goes where.

As for the second question: the information about how an object should be rendered is usually stored in a material object. The material represents the state of the renderer when rendering your object ( think of all the glEnable / glDisable commands ). Usually that's where you store whether or not depth test is active, whether or not you enable blending and what the blend function is, what shaders will be used and what binds to the shader parameters ( constants, matrices, textures, etc ). The renderer should have a method that accepts a material as it's parameter and sets it's state accordingly. You will need to store your object along with the material in a separate class. This makes sense though. You can have the same geometry with different materials represent different entities. You will then render entities instead of objects.

If you need further reference, I recommend you have a look at how other open-source engines are implemented ( Ogre3D, Irrlicht, HPL, etc ).

# Answer
> 0 votes
I recently wrote a simple rendering backend, and it basically worked like below.

First, generate or load your object and pass it to the renderer. The renderer returns an ID that you can use later.

```
const unsigned char* bitmap = /* load this */;
unsigned width, height; /* load these */
int textureId = renderer->makeTexture(bitmap, width, height);

std::vector<Vec3> verticies = /* calculate this */;
std::vector<Vec3> normals = /* calculate this */;
std::vector<Vec3> texCoords = /* calculate this */;

int myModelId = renderer->makeTexturedModel(&verticies,
                                            &normals,
                                            &texCoords,
                                            textureId);

```

Next, when you actually want to render the model, you just pass in the ID:

```
renderer->beginFrame();
renderer->render(myModelId);
renderer->render(otherModelId);
renderer->render(yetAnotherModelID);
renderer->endFrame();

```

This allows the renderer to decide the most efficient way to store and render models, and it's completely hidden from the rest of the code.

For example, in OpenGL ES the model will get converted into a VBO and uploaded to the GPU. Also, in `endFrame` the renderer can sort the models by textureId for efficient rendering. You don't have to worry about any of these details, though, as it's completely hidden in the renderer code.

# Answer
> 0 votes
You need to cache the data in a format that can be flushed out to a vertex buffer.

You need to make some assumptions about what the data format is going to be. Here I'm assuming both OGL and D3D use `FLOAT` for positions and colors.

```
struct Vec3{
  float x,y,z;
};

struct Vec4{
  float x,y,z,w;
};

struct VertexC
{
  Vec3 pos ;
  Vec4 color ;
} ;

// fully loaded v/tttt/n/cccc
struct VertexTTTTNCCCC
{
  Vec3 pos ;
  Vec4 tex[ 4 ] ;
  Vec3 norm ;
  Vec4 color[ 4 ] ;
} ;

```

You then load your model as `VertexTTTTNCCCC`, for example, and then from there you can create either D3D vertex buffers or OGL vertex buffers.

---
Tags: c++, rendering, directx11
---


title: how to implement motion blur effect?

text:
# Question
Title: how to implement motion blur effect?
I wanted to know how one would implement this motion blur or fade effect behind the soccer ball .

Here is what I was thinking . You have the balls current position and you also keep its previous position(couple of sec back). and you draw a "streak" sprite between the 2 points.

I have seen this effect lots of time implemented for projectiles in various 2d games and wanted to know if there is a standard technique.

# Answer
> 9 votes
That looks more like a trail than motion blur. Here's how you can achieve that:

1. Have a small transparent image with a white, isosceles triangle on it.
2. Draw this image stretched ( proportionally with the ball's speed ), rotated along the ball's direction.
3. Draw the ball on top of it ( so that it hides the triangle's base )

Here's an image to help you understand:

Of course, you trail doesn't have to be a triangle. It can be an isosceles trapezoid. It can also have a lower alpha so it blends with the background. It can even have a gradient alpha to fade away from the base.

This method is easy to implement, is parametrized by direction and velocity, and it's highly customizable. You can get almost any effect you want with it.

# Answer
> 0 votes
One way is to have a intermediate bitmap for the motion blur. At start of frame it's replaced and old motionblur bitmap is rendered in it with a little less opacity.

All objects that need to have motion blur have some wrapper that catches the rendering of object and transfers it to this bitmap at full opacity.

At end of frame the motion blur bitmap is rendered to screen.

This is not exactly the method your example seems to use though, and it doesn't seem to use real blur but some cheaper technique.

---
Tags: 2d, special-effects
---


# Question
Title: Making an AI walk on a NavigationMesh (2D/Top-Down game)
For some time I have been working on a framework which should make it possible to generate 2D levels based on a set of rules specified by level designers. You can read more about it here as I won't go into details: http://www.jorisdormans.nl/article.php?ref=engineering\_emergence

Anyway, I'm now at the point of putting the framework to use and have trouble coming up with a solution for AI.

I decided to implement a NavigationMesh in the generated levels as I already have that information to start with. Consider the following image (borrowed from http://www.david-gouveia.com/pathfinding-on-a-2d-polygonal-map/):

When I run A\* on the NavigationMesh, the red path would be suggested when I want to go from point A to B (either direction). However, I don't want my AI to walk that path directly and clipping corners, I'd rather want them to follow the more logical black path.

How would I go about going from the Red path to the Black path, are there any algorithms for this. Which steps do I take? Is A\* the proper solution for this at all?

For some additional information: The proof-of-concept game is a 2D top-down game written in C#, but examples/references in any language are welcome!

# Answer
> 1 votes
I would keep the A\* algorithm as it is and calculate the tangents to the white circles or to other circles with an appriopriate size. You can then either connect the tangents with sharp angles or walk along the cirlce up to the next tangent.

The radius of the circles have to be less or equal to the half distance of the next point.

# Answer
> 0 votes
Yes, A\* is still suitable for this. If you don't want your AI to "cut corners" you need modify the navigation mesh to remove corners. You just need to make sure your navigation mesh only has nodes that are a minimum distance from solid objects. These are the steps I would add to your current algorithm:

1. Generate nodes as you do above.
2. For each surface the node touches, collect its normal.
3. Add all normals together.
4. Scale resulting vector by appropriate scale (whatever the size of your AI unit is)
5. Displace the navigation node by scaled vector.
6. Check node to ensure no surfaces are within x distance, if surfaces found, remove node. This means that you're in a tight corridor that you can't fit a unit through.

You have some options for when to do this. You can do it when you generate your navigation mesh, or you can do it after a path has been found.

If you're doing this when the navigation mesh is generated, you'll have to use the size of the largest unit for your offset. That may negate some paths for smaller units. If you're doing it when finding a path, you may have to path more than once if you find that you've sent a unit down a path where it won't fit.

# Answer
> 0 votes
You can use an internal point in the triangle (like the centroid) as A\* nodes instead of the vertexes. Also, you can pre-proccess the nodes and elimitante the ones that are too close to a wall (like \<0.5 meters or something like that). This will ensure that the AI don't touch the walls.

---
Tags: c#, 2d, ai, path-finding, navmesh
---


title: XNA 4.0, Combining model draw calls

text:
# Question
Title: XNA 4.0, Combining model draw calls
I have the following problem: The levels in my game are made up of a Large Quantity of small Models and because of that I am experiencing frame rate problems. I already did some research and came to the conclusion that the amount of draw calls I am making must be the root of my problems.

I've looked around for a while now and couldn't quite find a satisfying solution. I can't cull any of those models, in a worst case scenario there could be 1000 of them visible at the same time.

I also looked at Hardware geometry Instancing, but I don't think that's quite what I'm looking for, because the level consists of a lot of different parts.

So, what I'd like to do is combining 100 or 200 of these Models into a single large one and draw it as a whole 'chunk'. The whole geometry is static so it wouldn't have to be changed after combining, but different parts of it would have to use different textures (I think I can accomplish that with a texture atlas). But I have no idea how to to that, so does anybody have any suggestions?

# Answer
> 2 votes
You basically answered the question for yourself.

Performance issues caused by too many draw calls can be solved by chunking together the different geometry sections. Also, you must chunk together your textures (atlasing) and modify the UV coordinates of each model to correctly index the smaller texture inside the atlas. Ideally this would happen inside your tool chain, but if it's just a hobby project, you might as well do it at load time.

Alternatively, an easier solution if your small models already share the same textures is to sort your draw calls by textures. Thus avoiding extraneous texture switches.

# Answer
> 0 votes
If you have so many models, they will be small - and if they are small and far away, maybe they can be replaced with billboards. Only two triangles for a model is much faster to draw..

---
Tags: c#, 3d, xna-4.0, graphics, models
---


title: DOT implementation

text:
# Question
Title: DOT implementation
I have some DOT (damage over time) implementation problems. My game runs on 30 FPS speed. Current implementation is: let's say the hero casts a spell which deals 1 damage per second. On every frame I do (pseudo code):

```
damage_done = getRandomDamage() * delta_time;

```

I accumulate damage and when it becomes more than 0, I subtract rounded damage from current health and so on. With 30 FPS and 1 DPS it will be `1/33 = 0.05...` We know that floats are not precise enough to sum 30 circulating decimals and have exactly 1 in the end. But HP is a discrete value and that's why 1 DPS will not result in 1 damage after 1 second, because the value will be 0.9999... instead. It's not such a big deal when you have 100000 DPS, ±1 damage will not be noticeable. But what if I have 1,5 DPS? How do modern RPGs implement DOTs?

# Answer
In my experience, i prefer to use a single "big" hit every so often than to accumulate a lot of very small differences.

I would recomend you to use a frequency (for the sake of simplicity i'd go with 1 second) and on your update loop check how much time has passed since the last time the dot has applied damage. Once you get to a time where you know damage has to be applied, you apply it, reset the counter and wait for the next tick of the dot.

```
float dot_frequency = DOT_FREQUENCY;
bool apply_first_tick_immediately = true; //<--With this you control the behavior as you asked

void on_dot_applied()
{
    if (apply_first_tick_immediately)
        time_since_last_tick = dot_frequency;
    else
        time_since_last_tick = 0;
}

void update(float elapsed_time)
{
    time_since_last_tick += elapsed_time;
    time_since_start += elapsed_time;
    if (time_since_last_tick >= dot_frequency)
    {
        apply_dot_damage();  // <-- here get your formula for dot damage
        time_since_last_tick -= dot_frequency;
    }
    if (time_since_start >= DOT_DURATION)
    {
        remove_dot();
    }
 }

```

I hope this helps.

EDIT: Added an example of how you can work with the "deal damage immediately" idea. Probably the on\_dot\_applied is an event that is called immediately as a dot is applied to setup certain effects of the specific dot, such as a fire particle effect, maybe a shader change.
> 4 votes

# Answer
If you're worried about imprecisions, you could simply apply the damage every second:

```
time_last_damage += delta_time;
if (time_last_damage >= 1.0f)
{
    time_elapsed = floor(time_last_damage);

    damage_done = getRandomDamage() * time_elapsed;

    time_last_damage -= time_elapsed; // keep fractional time
}

```
> 2 votes

---
Tags: c++, game-design, game-mechanics
---


# Question
Title: How can I draw a simple 2D line in XNA without using 3D primitives and shders
I would like to be able to draw arbitary lines in my sprite based 2D XNA game. How can I draw a simple line on screen in XNA without dealing with vertex arrays or shaders.

# Answer
You can draw a line using sprites. SpriteBatch.Draw(...) helpfully allows us to strech and rotate a sprite(texture).

In this code, we take a 1x1 pixel texture, strech it (by defining a rectangle of the correct shape and rotate it so it looks like a line.

```
    Texture2D t; //base for the line texture

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
        // create 1x1 texture for line drawing
        t = new Texture2D(GraphicsDevice, 1, 1);
        t.SetData<Color>(
            new Color[] { Color.White });// fill the texture with white
    }

    protected override void Draw(GameTime gameTime)
    {

        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin();
        DrawLine(spriteBatch, //draw line
            new Vector2(200, 200), //start of line
            new Vector2(100, 50) //end of line
        );
        spriteBatch.End();

        base.Draw(gameTime);
    }

    void DrawLine(SpriteBatch sb, Vector2 start, Vector2 end)
    {
        Vector2 edge = end - start;
        // calculate angle to rotate line
        float angle =
            (float)Math.Atan2(edge.Y , edge.X);

        sb.Draw(t,
            new Rectangle(// rectangle defines shape of line and position of start of line
                (int)start.X,
                (int)start.Y,
                (int)edge.Length(), //sb will strech the texture to fill this rectangle
                1), //width of line, change this to make thicker line
            null,
            Color.Red, //colour of line
            angle,     //angle of line (calulated above)
            new Vector2(0, 0), // point in line about which to rotate
            SpriteEffects.None,
            0);

    }

```
> 20 votes

---
Tags: xna, sprites, spritebatch
---


# Question
Title: What is the difference between Constant Vertex Attributes and Uniforms?
According to the **OpenGL ES 2.0 Programming Guide**:

```
A constant vertex attribute is the same for all vertices of a primitive, and
therefore only one value needs to be specified for all the vertices of a
primitive.

```

For uniforms the book states:

```
...any parameter to a shader that is constant across either all vertices or
fragments (but that is not known at compile time) should be passed in as
a uniform.

```

I've always used uniforms for data that is constant for a primitive but now it appears that attributes can also be used in the same way. Is there more to `constant vertex attribute` than simply *'they are the same as uniforms'*?

# Answer
> 7 votes
This is the first time I've heard of a `constant vertex attribute`, but from it's definition it's clear that it's a **vertex attribute**. Vertex attributes are defined per vertex ( whether they're the same for every vertex or not ). That means you only have access to them in the vertex shader. Uniforms on the other hand are kept in a separate space, and they are accessible to both the fragment and the vertex shader.

Also, since we're comparing vertex attributes to uniforms:

1. there's a limited number of attributes you can use per vertex ( usually small ) and they map to things like position, normal, color, etc., where as the space for uniforms is much larger.
2. There are type constraints to what you can pass as a vertex attribute. You can't use a texture as a vertex attribute.
3. If you try to pass the attribute to the fragment shader through a varying, you'll get an interpolated value for each fragment.

Try to think of them like this:

A vertex attribute is exactly what it's name implies: an attribute corresponding to vertex. Every vertex has that attribute. If that attribute is the same for every vertex, you can use it as a constant vertex attribute. The set of vertex attributes are the input for a vertex shader.

A uniform is something that is stored separate from the vertex or fragment shaders and it's accessible from both. You can store numbers, matrices, textures and even structures. They are not used as *input* but rather as a pool of resources you can access whenever and wherever you want. They're also treated differently by the video card.

---
Tags: opengl, glsl
---


# Question
Title: Question about creating a sprite based 2-D Side Scroller with scaling/zooming
I'm just wondering if anyone can offer any advice on how best to go about creating a 2-D game with zooming/scaling features akin to the early Samurai Showdown games. In this case it would be a side scroller a la Metal Slug, the zooming would come in as more enemy sprites entered the screen, or when facing a large sized boss. A feature that would be both cosmetic as well as functional to the game.

I've done some reading and noticed a few suggestions that included drawing different sized sprites, a standard size and zoomed out size.

Any thoughts?

Thanks for your time.

# Answer
> 1 votes
I do know that using XNA, you can specify your target Rectangle for any texture that you import through the content pipe-line, and it'll zoom the texture to fit that size. So, rather than including, say, dozens of textures of different sizes that are otherwise identical, you could just use some technology like that for zooming purposes.

# Answer
> 0 votes
With any good 2d library you will be able to scale/zoom sprites, however you should be able to achieve what you want, simply by zooming the camera in and out.

# Answer
> 0 votes
You could have multiple sprites and swap once a sprite hits a target scale, but that seems unnecessary to me. You should design your sprites at their largest size, and zoom out accordingly. The only reason you'd need to swap out sprites at the smallest size is if you have a ton of detail which gets really distorted and ugly as you scale the sprite down. However, I think that your art should have the requirement of being able to be scaled easily without losing significant visual clarity.

Some technical considerations to keep in mind:

**Collision Detection**
If your collision detection is coupled with your sprite then the scaling shouldn't impact how collision functions. However, if you've decoupled your hitbox than make sure to update the hitbox size as you scale the sprites.

**Scaling**
Since your scaling is going to be global, a basic camera class is a must. Remember, as you scale out your characters aren't the only things that will scale. The world will need to scale as well for the effect to look natural. Depending on where your registration is located on the sprite, zooming out will require some readjustment of the sprite's position. Make sure to keep track of a world position, and a screen position to make this easier on you.

I'm sure there are other considerations to take into account but these are the two that I would deem most important for a first pass of the system.

---
Tags: 2d, game-design, graphics, sprites
---


title: Speed up lighting in deferred shading

text:
# Question
Title: Speed up lighting in deferred shading
I implemented a simple deferred shading renderer. I use 3 G-Buffer for storing position (R32F), normal (G16R16F) and albedo (ARGB8). I use sphere map algorithm to store normals in world space. Currently I use inverse of view * projection matrix to calculate the position of each pixel from stored depth value.

1. First I want to avoid per pixel matrix multiplication for calculating the position. Is there another way to store and calculate position in G-Buffer without the need of matrix multiplication
2. Store the normal in view space

Every lighting in my engine is in world space and **I want do the lighting in view space to speed up my lighting pass.**

I want an optimized lighting pass for my deferred engine.

# Answer
> 3 votes
For pixel positions, as mentioned in the comments, it's generally considered best to use the depth buffer and the pixel's 2D position on screen to calculate its view space or world space position. If you're using an older D3D/OpenGL API version you may need to store an extra copy of the depth in an R32F buffer (it's unclear to me if this is what you're doing now); but in more recent APIs you can read the actual depth buffer directly, saving yourself one G-buffer slot.

In any case, most of the position reconstruction math can be moved into the vertex shader or the CPU, with only a reciprocal and a madd in the fragment shader (the reciprocal is not needed if you're using a linear depth buffer). The details of how to do this are in this blog post.

---
Tags: lighting, optimization, deferred-rendering, deferred-shading
---


title: Terrain square loading

text:
# Question
Title: Terrain square loading
Games like Skyrim, Morrowind, and more are using quads or square to divide the terrain if im correct. The player is always at #5

```
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9

```

So whenever you cross the border you unload and load the new "areas" But if the user goes just over the edge and then the second after goes back previous area a lot of unnecessary loading and unloading is done. Is there a general approach to this because I dont think games like skyrim have this issue?

Cheers!

# Answer
The general approach is called hysteresis: instead of immediately changing when you cross a border, you change only after you are some distance past the border.

For the simplest example, suppose you want to draw a warning on the screen if you are too close to something. The straightforward code is:

```
if distance < 20:
    draw warning

```

But if you're wobbling between 20.001 and 19.999, the warning might flash on and off. Instead, you can

1. remember whether the warning is on or off
2. use a different threshold for turning it on and turning it off

The code is a bit longer (which is probably why people don't do it all the time):

```
var warning_displayed

if warning_displayed and distance > 22:
    warning_displayed = false
else if not warning_displayed and distance < 18:
    warning_displayed = true

if warning_displayed:
    draw warning

```

Now what happens? If you're wobbling between 20.001 and 19.999 the warning will either stay on (if you last went below 18) or it will stay off (if you last went above 22), but it won't flash on and off.

The same general idea can be used for loading map areas in Skyrim. The wikipedia article gives lots of examples of where this technique comes in handy (not just maps or games or software).
> 7 votes

---
Tags: java, 3d, terrain, loading
---


title: CW/CCW Rotation of a Vector

text:
# Question
Title: CW/CCW Rotation of a Vector
Considering that I have a vector **A**, and after an arbitrary rotation I get vector **B**. I want to use this rotation operation in others vectors as well, but I'm having problems in doing that.

My idea do that is to calculate the perpendicular vector **C** of the plane AB (by calculating AxB). This vector **C** is the axis that I'll need to rotate. To discover the angle I used the dot product between **A** and **B**, the acos of the dot product will return the lowest angle between **A** and **B**, the angle *ang*. The rotation I need to do is then: -rotate \*ang\*º around the **C** axis.

The problem is that I dont know if this rotation is a CW or CCW rotation, since the cos of the dot product does not give me information of the sign of the angle. There's a tip discover that in 2D ( **A.x** * **B.y** \- **A.y** * **B.x**) that you can use to discover if the vector **A** is at left/right of vector **B**. But I dont know how to do this in 3D space. Can anyone help me?

# Answer
> 1 votes
In 3D it's even easier then 2D as the cross product's direction tells us which way is clockwise. The direction C will be point depends on which way is the smallest angle.

Remember the 'right hand rule'; if the smallest angle from A to B is counter-clockwise, then C will be pointing towards you, if the smallest angle from A to B is clockwise, C will be pointing away.

Looking along C you will need to rotate A clockwise to reach B. Most 'rotate about an axis' functions e.g Rodrigues, will do this automatically. The direction of rotation about an axis depends on whether the axis is 'pointing' towards you or 'pointing' away from you.

So you don't need to mess with getting dot products of normal vectors like you do in 2D. Actually, now that I think about it the dot product of the normal(of A) and B (as similar to the expression mentioned in the question);

also happens to be the Cross product of A & B with the 3rd dimension zeroed. The sign of this expression tells us the direction of rotation of the smaller angle.

---
Tags: rotation
---


# Question
Title: How Can I generate a shield block from a Turn based medieval game fight?
Imagine the char below, a Spartan that in his turn attacks and in the opponent turn tris to block. What would be the logic behind the block process? I just don't want to rely generating random numbers to decide

Update:

This is what I want to do, depending of the kind of the shield it would be more likely to block than others:

# Answer
> 3 votes
The easiest way to cause this effect would be to give each shield type a % chance to block (possibly also influenced by other stats, depending on how you want the logic to function)

Say if a small shield blocks 10%, a medium shield blocks 25% and a large shield blocks 50%, like in Orin's comment. At this point you just need to grab a random value and see if it's less than whatever your block value is.

Easy way is to grab a value between 0 and 1 (many random value generators will give you this, if not divide by max possible value and you have it anyway), then compare with the appropriate percentage (10% is 0.1, 25% is 0.25, ...etc). If the random value is greater than or equal to the shield value it's a hit, otherwise it was blocked

If you wish to add a character stat, terrain, direction, or anything else to this calculation, simply decide how it adds or subtracts to the block % and then do the comparison as normal. Values less than or equal to 0 will never block and values greater than 1 will always block, though you can modify this behavior by setting limits on the value.

# Answer
> 0 votes
**I don't know the combat system you are using or are trying to make (how you define it etc.)**

**I'll try to give you a solution from a game called Runescape. You have 3 basic meele combat skills:**

**Attack -** defines how often you will break through / makes the average hit higher

**Strength -** defines the highest possible hit

**Defence -** defines how much less you will get hit

**The weapons you use have three types of "stat bonuses"**

**Attack bonuses** \- for eg. your sword has **+100** slash but just **+30** to crush

**Strength bonus** in your wep. will define the max hit that you be able to hit (more than with fists or worse weps.)

**Defence** will be for eg. **+120 dmg** resistance to slash but only **+10 dmg** resistance to crush.

When you get slashed with that wep. you take the slash stats of the wep and you add +100 to -120 you will find out that you have 20 damage resistance from slash, then using your combat algorythms you can define that the average hit you get when slashed will be low because your armor is better than the attackers atk stats.

When you get crushed you add -10 to 30 and you get that your opponent will have +20 dmg exceeding your armor. And that way the average hits you get will be higher

**If I wrote something unclearl please correct and comment to ask additional questions**

---
Tags: turn-based
---


# Question
Title: Octree implementation for fustrum culling
I'm learning modern (\>=3.1) OpenGL by coding a 3D turn based strategy game, using C++.

The maps are composed of 100x90 3D hexagon tiles that range from 50 to 600 tris (20 different types) + any player units on those tiles. My current rendering technique involves sorting meshes by shaders they use (minimizing state changes) and then calling `glDrawElementsInstanced()` for drawing. Still get solid 16.6 ms/frame on my GTX 560Ti machine but the game struggles (45.45 ms/frame) on an old 8600GT card. I'm certain that using an octree and fustrum culling will help me here, but I have a few questions before I start implementing it:

1. Is it OK for an octree node to have **multiple meshes** in it (e.g. can a soldier and the hex tile he's standing on end up in the same octree node)?
2. How is one supposed to treat **changes in object postion** (e.g. several units are moving 3 hexes down)? I can't seem to find good a explanation on how to do it.
3. As I've noticed, soting meshes by shaders is a really good way to save GPU. If I put node contents into, let's say, std::list and **sort it before rendering**, do you think I would gain any performance, or would it just create overhead on CPU's end? I know that this sounds like early optimization and implementing + testing would be the best way to find out, but perhaps someone knows from experience?

# Answer
1. Yes. It's probably a good idea to stop subdividing your octree once you're down to some threshold number of meshes in the node, since at some point the cost of further subdivision can outweigh the cost of just drawing a few extra meshes.

In fact, the other way around is necessary too: having a mesh in multiple nodes. If a mesh happens to be in a place where it straddles the boundary between multiple nodes, each of the nodes it touches will need to have a reference to it.
2. When objects move, you keep track of which node boundaries they cross, and adjust the list of meshes in each node correspondingly - adding them to nodes they've entered and removing them from nodes they've exited.

If your game contains a reasonably strict separation between moving and non-moving objects, it can also pay to have two octrees, one each for non-moving and moving objects. The level of subdivision for the moving ones could be lower, if appropriate, reducing the number of nodes and therefore the overhead of updating them. But this may or may not be a performance win; you'd have to profile to see.

Depending on your situation, you might also find it necessary to dynamically split and merge octree nodes, if they end up with too many / too few meshes in them. This should be a relatively rare operation, though, and you might be able to get away without it.
3. You can split rendering into two phases: visibility determination (deciding what to draw) and then actually drawing it. During the first phase you'd traverse the octree and accumulate visible meshes into a list; then during the second phase you'd sort that list by shader/material and then draw them.

You can save some time by using a bucket sort here. Rather than literally tossing all the meshes into an std::list and then calling sort(), you'd maintain a list of buckets - one for each material - and each bucket contains a list to which you add the meshes as you find them during the octree traversal. The list of buckets is maintained from one frame to the next and kept sorted (only the contents of each bucket is cleared), so you do not need to re-sort them all the time; the meshes are already sorted by the time you finish traversing the octree.

BTW, for a tile-based game world with an isometric view, an octree might not even be the best choice of subdivision structure. Since meshes are likely to be all about the same size and to be fairly evenly spaced (as opposed to there being some areas with a dense concentration of meshes and other areas that are quite empty), a grid might serve you just as well as an octree, and be simpler to code. Instead of doing a hierarchical tree traversal, you'd just iterate over a rectangle of grid nodes enclosing the frustum, which is easy to calculate since it's just the AABB of the frustum in grid coordinates.
> 4 votes

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


# Question
Title: How to use mount points in MilkShape models?
I have bought the Warriors & Commoners model pack from Frogames and the pack contains (among other formats) two animated models and several non-animated objects (axe, shield, pilosities, etc.) in MilkShape3D format.

I looked at the official "MilkShape 3D Viewer v2.0" (msViewer2.zip at http://www.chumba.ch/chumbalum-soft/ms3d/download.html) source code and implemented loading the model, calculating the joint matrices and everything looks fine.

In the model there are several joints that are designated as the "mount points" for the static objects like axe and shield. I now want to "put" the axe into the hand of the animated model, and I couldn't quite figure out how. I put the animated vertices in a VBO that gets updated every frame (I know I should do this with a shader, but I didn't have time to do this yet). I put the static vertices in another VBO that I want to keep static and not updated every frame.

I now tried to render the animated vertices first, then use the joint matrix for the "mount joint" to calculate the location of the static object. I tried many things, and what about seems to be right is to transpose the joint matrix, then use glMatrixMult() to transform the modelview matrix. For some objects like the axe this is working, but not for others, e.g. the pilosities.

Now my question: How is this generally implemented when using bone/joint models, and especially with MilkShape3D models? Am I on the right track?

# Answer
You are on the right track, but "doesn't work" isn't a particularly helpful error description.

Anchoring a prop onto a skeleton joint is done by simply using the joint transform as the model matrix. That'll put the origin and orientation of the prop model at the joint. This is the chain of transforms you need:

Projection * View * Model * Joint

Now if you're using fixed function OpenGL, you'll have the Projection in GL\_PROJECTION and will need to make sure that the GL\_MODELVIEW is View * Model * Joint. You had View * Model set already to render the character model, so you should be able to just concatenate the anchor joint transform.

Keep in mind that there are usually a lot of different coordinate spaces involved during skeletal animation, and you must use the correct one. The "Joint" transform I talk about is the model-relative transform of the joint in its animated pose. It is not the parent-relative transform, it's not the inverse bind pose, nor is it the concatenation of the model-relative transform with the inverse bind pose that you use to deform the vertices.

In the msViewer2 sample code it looks like the transform you want is joint-\>matGlobal.
> 1 votes

---
Tags: models
---


# Question
Title: just starting and cant find a place to learn a launguage to code games
Like i said im justing starting and it feals like it is impossible to learn a launguage. Id like to code games and would appreciate it if some one could direct me to a site where I could learn how to do so.

# Answer
> 1 votes
It is no easy task to program a game, you need to have a solid background in mathematics especially linear algebra if you want to program 3D games.

If you have no interest in maths, algorithms and serious programming, but just want to create games then look at this http://mashable.com/2008/01/04/20-tools-for-creating-your-own-games/

# Answer
> 0 votes
Purchase a book about programming in a language you think seems interesting. For an example a Java book. You can't write a game before you know how to write code. There are tons of programming books on Amazon, which hopefully will give you inspiration.

# Answer
> 0 votes
As others have pointed out, this is the wrong place ask that question. But here's a link anyway: Lazy Foo Tutorials. The tutorials are designed from ground up to teach game development in C++ using the SDL library. If that's too much for you, consider taking an introductory programming course on Udacity or Coursera.

---
Tags: software-engineering
---


title: How to track many in-game statistics

text:
# Question
Title: How to track many in-game statistics
I am looking to track many in-game events, e.g. the score of each move, how many moves are taken, what types of moves, etc. A lot of stats can simply be tracked with a counter. In some cases I need to aggregate data in order to calculate the value (e.g. most common move). How are you tracking in-game stats for your games? How do you avoid creating a class with tens or hundreds of fields? How do you avoid littering the code with tracking invocations? How do you abstract the aggregate data so as to avoid rewriting it for each scenario?

# Answer
The way I usually end up doing it is to first use a messaging system. Let's say that you send a message each time the player fires his weapon. Then, the weapon system (or the weapon object) acts on that message when it is received and the weapon is fired. If you then want to keep stats of when a weapon is fired, simply log the weapon.fire messages to a list somewhere. Then it would be easy to go from that list and generate statistics from that.

You could consider introducing an object that has the sole responsibility for tracking game stats. It could simply listen to all the relevant messages, and append them to their respective lists
> 5 votes

---
Tags: architecture, statistics
---


# Question
Title: What are the most common AI systems implemented in Tower Defense Games
I'm currently in the middle of researching on the various types of AI techniques used in tower defense type games. If someone could be help me in understanding the different types of techniques and their associated advantages.

Using Google I already found several techniques.

* Random Map traversal
* Path finding e.g. Cost based Traversing Algorithms i.e. A\*

I have already found a great answer to this type of question with the below link, but I feel that this answer is tailored to FPS. If anyone could add to this and make it specific to tower defense games then I would be truly great-full.

How is AI most commonly implemented in popular games?

Example of such games would be:

* Radiant Defense
* Plant Vs Zombies - Not truly Intelligent, but there must be an AI system used right?
* Field Runners

Edit: After further research I found an interesting book that may be useful: http://www.amazon.com/dp/0123747317/?tag=stackoverfl08-20

# Answer
> 4 votes
A\* will work, but for a Tower Defense game that has lots of enemies with the same goal and a relatively static geometry, it may actually be cheaper to just run Dijkstra's algorithm backwards from the goal, to find the shortest path tree from anywhere on the map to the goal, and cache the result until the geometry changes (i.e. a tower is built or destroyed).

Basically, this means that, for each grid point on the map, you store the direction that leads most directly to the goal from that point. Then you just have each enemy move in the direction given by the nearest (If there are *n* groups of enemies with different goals, or different terrain crossing abilities, you need to store up to *n* directions per node. Obviously, flying enemies don't normally need directions.)

Conveniently, if you save the distance from each point to the goal too, you can do incremental updates to the map when obstacles are added or removed: when an obstacle is added, you only need to update points in the branch of the tree cut off by the obstacle, whereas when an obstacle is removed, you only need to update any points from which the goal can now be reached more directly than before.

---

Alternatively, you can combine the caching with A\*: for every enemy, run A\* backwards from the goal to the enemy, but save the resulting tree and distances so that you can reuse it for other enemies (and for subsequent updates). This should quickly give you a fully cached shortest path tree of all the map areas that the enemies are actually passing through, while not wasting effort on dead ends that won't be visited anyway.

Both incremental updates and A\* also let you efficiently test whether a tower would disconnect the map: with incremental updates, you just try the update and see if all enemy entrances can still be reached from the goal, while with A\* you can just run a search from the goal to the entrance and see if it succeeds; if the obstacle does get built, you can then use the result as the starting point for your new pathfinding map.

It should even be possible to get the best of both worlds, by combining the cached A\* idea with the incremental updates, although one would have to be careful about not leaving any stale cached directions where an enemy might try to use them for pathing. (Leaving stale directions in dead ends should be OK.) Basically, when an obstacle is added, you invalidate any cached directions leading through it, while if an obstacle is removed, you re-run A\* from the obstacle to all enemies and possible entrance points and then merge the result with your previous cached paths. I'll have to think about that a little bit more, though...

# Answer
> 1 votes
Well, I don't think plants vs zombies has much in the way of path finding. Just moves left. You could just generate a random number from 1 to 5 or however many lanes you have and stick the enemy there. Maybe with the constraint that it can't roll the same number twice. Or if it does re roll so you don't get too many in the same lane

# Answer
> 1 votes
> If someone could be help me in understanding the different types of techniques and their associated advantages.

I want to answer that question by listing three techniques I would use if I were to implement a TD game:

1) Finite state machines or behavior trees for the little AI any agent would need. For something as simple as TD I'd probably use FSM. (

2) A\* for path finding, with a cost of selecting paths that is already taken (for the AI, clustering is bad as it makes for an easier target) also I would try to select targets where I have 'gotten through' before

3) State planning / adversarial search / alphaBeta pruning for selecting the best agent to spawn next (optimize likelihood of player defeat) (the AI needs its own set of costs and cool-downs for this to work)

---
Tags: ai, tower-defense, search
---


# Question
Title: Does using [STAThread] with XNA have any negative implications?
I'm working on a game in XNA, which has an inbuilt level editor. To facilitate this I want use the `FileOpenDialog` from Winforms. I followed the instructions as per this answer. This involves setting the \[STAThread\] attribute on my Program class.

Does using STAThread have any negative implications? Meaning will it cause worse performance or limit me in some way?

# Answer
> 2 votes
The STAThread attribute is used to indicate to COM that the application should use a single-threaded apartment (STA). This **only affects COM objects**, and is only required as certain dialogs that use COM (such as the `FileOpenDialog`) need the the correct threading model to be specified.

To my knowledge very little (if any) game development will make use of COM with the exception of Windows Forms dialogs and so this is won't have any impact, its simply required for those dialogs.

If you do make use of COM objects then you *may* want to look into COM threading models to fully understand the implication of this setting, however the short version is that in a STA all COM methods will be run on a single thread (the UI thread in this case) even if it was invoked on another thread.

**Update:** DirectX is available as a set of COM objects, however I'm not sure what threading model they require.

---
Tags: xna, multithreading, windows-forms
---


# Question
Title: Why do I have to divide the origin of a quad by 4 instead of 2?
I'm currently transitioning from C#/XNA to C#/OpenTK but I'm getting stuck at the basics.

So I have this Sprite-Class:

```
public static bool EnableDebugDraw = true;
public float X;
public float Y;

public float OriginX = 0;
public float OriginY = 0;

public float Width = 0.1f;
public float Height = 0.1f;

public Color TintColor = Color.Red;
float _layerDepth = 0f;

public void Render()
    {
        Vector2[] corners =
        {
            new Vector2(X-OriginX,Y-OriginY), //top left
            new Vector2(X +Width -OriginX,Y-OriginY),//top right
            new Vector2(X +Width-OriginX,Y+Height-OriginY),//bottom rigth
            new Vector2(X-OriginX,Y+Height-OriginY)//bottom left
        };
        GL.Color3(TintColor);
        GL.Begin(BeginMode.Quads);
        {
            for (int i = 0; i < 4; i++) GL.Vertex3(corners[i].X,corners[i].Y,_layerDepth);
        }
        GL.End();

        if (EnableDebugDraw)
        {
            GL.Color3(Color.Violet);
            GL.PointSize(3);
            GL.Begin(BeginMode.Points);
            {
                for (int i = 0; i < 4; i++) GL.Vertex2(corners[i]);
            }
            GL.End();

            GL.Color3(Color.Green);
            GL.Begin(BeginMode.Points);
            GL.Vertex2(X + OriginX, Y + OriginY);
            GL.End();
        }

```

With the following setup I try to set the origin of the quad to the middle of the quad.

```
_sprite.OriginX = _sprite.Width / 2;
_sprite.OriginY = _sprite.Height / 2;

```

but this sets the origin to the upper right corner of the quad, so i have to

```
_sprite.OriginX = _sprite.Width / 4;
_sprite.OriginY = _sprite.Height / 4;

```

However this is not the intended behaviour, could you advise me how I fix this?

# Answer
When you declare your corners as such:

```
    Vector2[] corners =
    {
        new Vector2(X-OriginX,Y-OriginY), //top left
        new Vector2(X +Width -OriginX,Y-OriginY),//top right
        new Vector2(X +Width-OriginX,Y+Height-OriginY),//bottom rigth
        new Vector2(X-OriginX,Y+Height-OriginY)//bottom left
    };

```

It seems that you are adjusting the corners to be around X and Y and are treating (X, Y) as your origin and your OriginX and OriginY values are just the offsets.

That being said, I don't think this line within your EnableDebugDraw block is right, assuming this is your attempt at drawing the origin:

```
        GL.Vertex2(X + OriginX, Y + OriginY);

```

I believe your origin should simply be (X, Y) making your draw statement:

```
        GL.Vertex2(X, Y);

```
> 8 votes

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


title: 2D tower defense - A bullet to an enemy

text:
# Question
Title: 2D tower defense - A bullet to an enemy
I'm trying to find a good solution for a bullet to hit the enemy. The game is 2D tower defense, the tower is supposed to shoot a bullet and hit the enemy guaranteed.

I tried this solution - http://blog.wolfire.com/2009/07/linear-algebra-for-game-developers-part-1/

The link mentioned to subtract the bullet's origin and the enemy as well (vector subtraction). I tried that but a bullet just follows around the enemy.

```
float diffX = enemy.position.x - position.x;
float diffY = enemy.position.y - position.y;

velocity.x = diffX;
velocity.y = diffY;

position.add(velocity.x * deltaTime, velocity.y * deltaTime);

```

I'm familiar with vectors but not sure what steps (vector math operations) to be done to get this solution working.

# Answer
> 11 votes
Your reasoning was perfect: use a vector to move from my position to my target. This is the purpose of a vector; you simply forgot the *speed*!

Velocity is a vector: a speed and a direction. However, if you forget to normalize the difference vector and multiply it the bullet speed (a scalar), you are basically saying that if you are **close to the target** (the difference vector is small) **the bullet slows down**; while if you are far away the bullet speed is larger.

This is the underlying problem: you need to calculate both the direction *and* the magnitude of the vector.

# Answer
> 8 votes
If the target is moving in a steady direction at a steady pace, and your bullet path is in a straight line at a steady pace, you can use a quadratic equation to predict the exact spot they will intersect and aim your tower's gun at that spot.

Since it is a certainty that the bullet will hit it's mark, and you can calculate the exact time it will take from firing to impact, no collision detection would be required, simply fire the gun, wait the calculated time span, register a hit.

Here is pseudo code for the quadratic equation:

```
Vector totarget =  target.position - tower.position;

float a = Vector.Dot(target.velocity, target.velocity) - (bullet.velocity * bullet.velocity);
float b = 2 * Vector.Dot(target.velocity, totarget);
float c = Vector.Dot(totarget, totarget);

float p = -b / (2 * a);
float q = (float)Math.Sqrt((b * b) - 4 * a * c) / (2 * a);

float t1 = p - q;
float t2 = p + q;
float t;

if (t1 > t2 && t2 > 0)
{
    t = t2;
}
else
{
    t = t1;
}

Vector aimSpot = target.position + target.velocity * t;
Vector bulletPath = aimSpot - tower.position;
float timeToImpact = bulletPath.Length() / bullet.speed;//speed must be in units per second

```

# Answer
> 3 votes
You need to 'predict' the objects position by the time the bullet will reach it. You can do this using the objects speed/velocity (hopefully that is constant ;)) and it's directional vector.

I'm not sure what the exact formula is off the top of my head but I think it's something like this:

NewPosition = OldPosition + (Speed * DirectionVector);

If you have a set path you will need to recalculate when the object changes direction. Use this NewPosition as your enemy.position vector and the bullet should hit the object without the 'homing effect'. Homing occurs due to the fact the enemy object has moved since the original vector was calculated, it can only ever catch up when an object is travelling in one direction long enough.

Hope this helps :)

# Answer
> 1 votes
You can avoid using square root & power of 2.

```
var distX:Float = target.x - x;
var distY:Float = target.y - y;
_velX = distX / timeTravel;
_velY = distY / timeTravel;

// Take out if you want a nice slow down as approaches effect.
timeTravel -= 1.0; // make sure u have a positive timeTravel.
x += _velX;
y += _velY;

if (distX < 0)
    distX = -distX;

if (distY < 0)
    distY = -distY;

if (_velX < 0)
    _velX = -_velX;

if (_velY < 0)
    _velY = -_velY;

// Should both snap @ the same time.
if (distX < _velX)
x = target.x; // snap & see what happens.

if (distY < _velY)
y = target.y; // snap & see what happens.

// TODO: call your onHitTarget here ...
// Hopefully this shall provide 10x the performance
// of using Math.sqrt and all the extra multiplications.

```

It's all written from memory. By the way, use the elements that work - test it line by line if you're new at this. Float is Number in AS3.

---
Tags: projectile-physics, tower-defense, bullet-physics
---


# Question
Title: How do 2D physics engines solve the problem of resolving collisions along tiled walls/floors in non-grid-based worlds?
I've been working on implementing my SAT algorithm which has been coming along well, but I've found that I'm at a wall when it comes to its actual use. There are plenty of questions regarding this issue on this site, but most of them either have no clear, good answer or have a solution based on checking grid positions.

To restate the problem that I and many others are having, if you have a tiled surface, like a wall or a floor, consisting of several smaller component rectangles, and you traverse along them with another rectangle with force being applied *into* that structure, there are cases where the object gets caught on a false collision on an edge that faces the inside of the shape.

I have spent a lot of time thinking about how I could possibly solve this without having to resort to a grid-based system, and I realized that physics engines do this properly. What I want to know is how they do this. **What do physics engines do beyond basic SAT that allows this kind of proper collision resolution in complex environments?** I've been looking through the source code to Box2D trying to find out how they do it but it's not quite as easy as looking at a Collision() method. I think I'm not good enough at physics to know what they're doing mathematically and not good enough at programming to know what they're doing programmatically. This is what I aim to fix.

# Answer
The standard approach to fixing this problem is to preprocess the scene and mark all "internal" edges and then when you collide with one of these edges you determine a different collision feature to use in collision response. (i.e. maybe respond to all adjacent faces for which dot(face.normal, body.linearVel) \< 0 or something - this doesn't address rotations though)

Box 2d addresses this with "Ghost vertices" there's a tutorial about it here. http://www.iforce2d.net/b2dtut/ghost-vertices

Paul Firth talks about this issue on his blog here: http://www.wildbunny.co.uk/blog/2012/10/31/2d-polygonal-collision-detection-and-internal-edges/

Edit: Thinking about this in 2d a bit more it seems like if you have edge-edge connectivity the heuristic you should use is to back the collision point up a little bit along the collision point's velocity and then see if it projects to either edge closer than the vertex (intuitively trying to determine if that point approached within the collision feature's voronoi region) and then use that edge instead of the vertex.
> 4 votes

---
Tags: collision-detection, physics, collision-resolution
---


# Question
Title: Instead of the specified Texture, black circles on a green background are getting rendered. Why?
I'm trying to render a Texture via OpenGL. But instead of the texture black circles on a green background are rendered. (They scale, depending what the rotation of the texture is)

**Example:**

**The texture I'm trying to render is the following:**

**This is the code I use to render the texture, it's located in my Sprite-class.**

```
    public void Render()
    {
        Matrix4 matrix = Matrix4.CreateTranslation(-OriginX, -OriginY, 0) *
                        Matrix4.CreateRotationZ(Rotation) *
                        Matrix4.CreateTranslation(X, Y, 0);

        Vector2[] corners =
        {
            new Vector2(0,0), //top left
            new Vector2(Width ,0),//top right
            new Vector2(Width,Height),//bottom rigth
            new Vector2(0,Height)//bottom left
        };

        //copy the corners to the uv coordinates
        Vector2[] uv = corners.ToArray<Vector2>();

//transform the coordinates
        for (int i = 0; i < 4; i++) corners[i] = new Vector2(Vector3.Transform(new Vector3(corners[i]), matrix));
        //GL.Color3(TintColor);
        GL.BindTexture(TextureTarget.Texture2D, _ID);
        GL.Begin(BeginMode.Quads);
        {
            for (int i = 0; i < 4; i++)
            {
                GL.TexCoord2(uv[i]);
                GL.Vertex3(corners[i].X, corners[i].Y, _layerDepth);
            }
        }
        GL.End();

        if (EnableDebugDraw)
        {
            GL.Color3(Color.Violet);
            GL.PointSize(3);
            GL.Begin(BeginMode.Points);
            {
                for (int i = 0; i < 4; i++) GL.Vertex2(corners[i]);
            }
            GL.End();

            GL.Color3(Color.Green);
            GL.Begin(BeginMode.Points);
            GL.Vertex2(X, Y);
            GL.End();
        }

    }

```

**This is how I setup OpenGL.**

```
    public static void SetupGL()
    {
        GL.Enable(EnableCap.AlphaTest);
        GL.AlphaFunc(AlphaFunction.Greater, 0.1f);

        GL.Enable(EnableCap.Texture2D);
        GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);

    }

```

**With this function I load the texture:**

```
public static uint LoadTexture(string path)
    {
        uint id;
        GL.GenTextures(1, out id);
        GL.BindTexture(TextureTarget.Texture2D, id);

        Bitmap bitmap = new Bitmap(path);

        BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
            ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

        GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0,
            OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);

        bitmap.UnlockBits(data);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
        return id;
    }

```

**And here I call Sprite.Render()**

```
protected override void OnRenderFrame(FrameEventArgs e)
    {
        GL.ClearColor(Color.MidnightBlue);
        GL.Clear(ClearBufferMask.ColorBufferBit);
        _sprite.Render();
        SwapBuffers();
        base.OnRenderFrame(e);
    }

```

As I stole this code from the Textures-Example from OpenTK, I don't understand why this doesn't work.

# Answer
> 5 votes
First of all, your UVs look suspicious to me:

```
    Vector2[] corners =
    {
        new Vector2(0,0), //top left
        new Vector2(Width ,0),//top right
        new Vector2(Width,Height),//bottom rigth
        new Vector2(0,Height)//bottom left
    };

    //copy the corners to the uv coordinates
    Vector2[] uv = corners.ToArray<Vector2>();

```

Normally the UVs for a sprite would range from 0 to 1, not from 0 to width/height. This is probably why you've got a bunch of circles showing up; your UV mapping is accidentally squeezing the texture down to a tiny size and causing those circles to appear as an artifact.

Second, your texture loading logic looks suspicious. Your `LockBits` call specifies ARGB format, while your `TexImage2D` call specifies RGBA internal format. I'm not sure which is the correct one, but presumably they should match. This could be why the texture is turning green and black - the color channels are getting swapped around wrongly.

# Answer
> 1 votes
Have a close look at this part of the code:

```
Bitmap bitmap = new Bitmap(path);

BitmapData data = bitmap.LockBits(
    new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
    ImageLockMode.ReadOnly,
    System.Drawing.Imaging.PixelFormat.Format32bppArgb
);

GL.TexImage2D(
    TextureTarget.Texture2D,
    0, PixelInternalFormat.Rgba,
    data.Width, data.Height, 0,
    OpenTK.Graphics.OpenGL.PixelFormat.Bgra,
    PixelType.UnsignedByte, data.Scan0
);

```

There seems to be a difference between the format of your BitmapData ( Format32bppArgb ) and the format you specify to `GL.TexImage2D`.

Also, having a quick look at the API page for glTexImage2D you can see that the *internalformat* and *format* parameters must have the same value. Yours differ: Rgba, Bgra. Make sure you use the same format everywhere ( namely Argb ).

Hope this helps.

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