# Question
Title: Storing few values in an int - small gain
This might be a bit hard-to-answer question, but... I had a **DirectX::XMFLOAT3** as a vertex attribute. I have changed it to just an int by placing the 3 floats into int (using only 8 bits per float). In the **vertex shader** I am extracting the bits like this:

```
// example int bits: 00000000 10011000 00011101 11111111

input.weight.x =   ( input.w >> 16 )               / 255.0f; // 10011000 / 255.0f
input.weight.y = ( ( input.w & 0x0000FF00 ) >> 8 ) / 255.0f; // 00011101 / 255.0f
input.weight.z =   ( input.w & 0x000000FF )        / 255.0f; // 11111111 / 255.0f

```

But with this manner I've only gained like 1-5 fps (from ~130 to ~135), how is that possible that the fps boost is that small? What's the culprit here? Is the extracting bits on GPU that heavy?

# Answer
> 3 votes
I don´t think this will gain you anything, in fact i rather think you will lose performance off this. You should use a profiler to get a good pinpoint of where the bottleneck is.

A good thumbrule is to never mix Interger and Float math on the gpu, this is typically a downfall. Of course there is points when it´s needed, but packing floats into int´s is really bad! rather think of using a vertexlayout that uses Float16. so you use the half precision of the floats.

Another note is that you might belive you are bandwidth bound, this is pretty common for textures rather than vertex buffers. a mesh containing one million vertexes is barley taking as much memory as a 512x512 texture is. ( worth focusing on optimizing there instead )

On the other hand, the gpu stores vertexbuffers, textures and other things on it´s internal memory, so unless you are updating your vertexbuffer every frame you don´t stream it to the gpu.

---
Tags: hlsl, directx11
---


# Question
Title: using heightmap to simulate 3d in an isometric 2d game
I saw a video of an 2.5d engine that used heightmaps to do zbuffering. Is this hard to do? I have more or less no idea of Opengl(lwjgl) and that stuff.

I could imagine, that you compare each pixel and its depthmap to the depthmap of the already drawn background to determine if it gets drawn or not.

Are there any tutorials on how to do this, is this a common problem? It would already be awesome if somebody knows the names of the Opengl commands so that i can go through some general tutorials on that. greets!

Great 2.5d engine with the needed effect, pls go to the last 30 seconds

Edit, just realised, that my question wasn't quite clear expressed: How can i tell Opengl to compare the existing depthbuffer with an grayscale texure, to determine if a pixel should get drawn or not?

# Answer
> 6 votes
This is actually a quite simple thing to do.

Use your "heightmap" as a texture input to the shader of your sprite.
Then simply add the heightmap height to the fragment depth inside the shader.
Here's a little example fragment shader:

```
uniform sampler2D heightmap;
void main(void)
{
        gl_FragDepth = gl_FragCoord.z + texture2D(heightmap, texture_coordinate.xy).r;
}

```

**Keep in mind that you'll first need to convert the heightmap height to a non-linear value before adding it to "gl\_FragCoord.z".** Here's a topic that explains how to do that: https://stackoverflow.com/questions/10264949/glsl-gl-fragcoord-z-calculation-and-setting-gl-fragdepth

Also: Since you're probably using orthographic projection, be sure to properly set the sprite's z position correctly so opengl can calculate gl\_FragCoord.z properly for you.

**But be aware:** Setting the fragment depth in the shader by yourself eliminates the possibility for early depth testing. But that shouldn't be a problem unless you draw a lot of sprites with complex shaders.

---
Tags: opengl, java, fragment-shader, depth-buffer, 2.5d
---


# Question
Title: Why is this code producing jittery movement?
I have a new project, all settings default with a simple cube on a plane. Cube is not kinematic but is a rigid body under the effects of gravity. I'm trying to normalize the direction before I translate it to prevent diagonal movement from being too fast. The movement is perfectly smooth when I just translate by the speed, but when I try to normalize it and multiply that vector, the movement becomes jittery and feels delayed, almost. I have no idea what the cause could be. Here's the code in question. It takes place in the `Update()` override:

```
    float directionHorizontal = Input.GetAxis("Horizontal");
    float directionVertical = Input.GetAxis("Vertical");

    Vector3 translationDirection = new Vector3(directionHorizontal, 0, directionVertical);
    translationDirection.Normalize();

    translationDirection *= Speed * Time.deltaTime;
    transform.Translate(translationDirection);

```

EDIT: After some further tinkering and testing, I'm finding that the problem is more specifically that the movement seems to jump from frame to frame rather than move smoothly from one spot to another. It seems like it's moving the right speed, but this kind of really fast start/stop gives it that jerky feel.

Is this normal behavior? Shouldn't the delta time multiplication smooth out the movement and give it a more interpolated feel? This happens even if i avoid the normalization method and just multiply the axis by speed and time.

# Answer
When you start moving, input values returned by Input.GetAxis() normally (with default Input settings) don't jump instantly from 0 to 1 but rather are gradually increased during several frames, even if you use digital input (such as keyboard keys) rather than a gamepad's analog stick.

Now, the problem is that after normalization, your direction vector has magnitude = 1.0 even if movement speed supposed to be small, which gives this sudden jump from speed = 0 to speed = 1 as soon as you start moving:

```
Vector3 translationDirection = new Vector3(0.1f, 0, 0);  // slowly moving to the right
translationDirection.Normalize();  // results in Vector(1, 0, 0)

```

Rather than normalizing this vector, you should instead limit its magnitude only when necessary:

```
Vector3 translationDirection = new Vector3(directionHorizontal, 0, directionVertical);
translationDirection = Vector3.ClampMagnitude(translationDirection, 1);

```

This will give you smooth increase in speed when you start moving (or decrease when stopping), while at the same time preventing from exceeding the maximum speed.
> 3 votes

# Answer
Don't have enough rep to comment yet so I'll take a stab at an answer.

I had a similar problem in an XNA project I was working on a few months ago. The issue I was having was caused by scaling the object. Basically the physics wasn't being scaled by the same amount as everything else and that resulted in jitter.

You don't seem to be building up a force either. Was that the intention? Apologies if any of this is incorrect / irrelevant I'm attempting to answer before my early morning coffee.
> 2 votes

# Answer
Try placing this code in FixedUpdate() instead of Update().

Physics motions happen in FixedUpdate() and Update() is synched with draw calls. The two don't always happen at the same frequency. Most of the time this is the cause of the jittery motion.

So, if you are going to affect the motion of a physically-simulated object, you need to do it in FixedUpdate().

Now, why does it happen only when you do the normalization? Probably it's because the extra processing time required by Normalize() causes the Update calls to lag more behind FixedUpdate. The fact that it acts differently in different computers also supports this idea. How much out-of-sync Update and FixedUpdate get depends a lot on the available CPU cycles, which tends to be nondeterministic.
> 2 votes

---
Tags: c#, unity, movement, vector
---


# Question
Title: Should I be using spritesheets, because of or despite of my vast number of images?
I am developing a 2D game, and I have a lot of sprites. I used 3D animations and models to render into 2D, to give them that "Fallout" or "Diablo" look to them. It is also easier than drawing by hand, lol.

I have already had to cut the framerate down to 15fps, which was the lowest I could lower without making them have a choppy look to them. However, it was sad due to how incredibly smooth 24 frames looked.

There are two reasons I did this:

1) Cut down on HDD space. The fewer the images, the smaller my total game will be.

2) Cut down on RAM consumption. The fewer images to load, the more likely I am to avoid issues bloating my RAM limitation.

However, if there was a way to compress the images in both HDD space and RAM, I would do so. I have tested it before, and most do not receive any change in quality when giving from RGBA8888 to RGBA5555 and only a little hit when converting to RGBA4444 in my TexturePacker program. I do not do this currently, because SFML seems to use the same amount of memory regardless of which type of .PNG image it is. I looked into researching how to load it differently, but failed to find anything on the subject.

I have read a lot about how to handle 2D video games. The consensus is overwhelming: Pack your Sprites into a Bigger Texture for great performance! So I pack my tiny sprites into a much larger spritesheet using TexturePacker.

However, I plan to have 10-15 animations per character, 5 directions to move, and 15-40 frames per animation (probably an average of 24). With 15 animations, 5 directions, and an average of 24 frames per animation; That is 1800 individual frames per character. If packed in a sprite sheet, that is only 75 images instead. (One sprite sheet per Animation, per Direction. 15 * 5)

For the one huge boss character in the game, I cannot use a spritesheet and have to program a way to simply load in one image at a time. I do not know if I can do this for performance yet.

For the characters, I already pack them in a spritesheet. For a single character walking about, this seems to work most of the time, although sometimes it stalls. However, I attribute that to my ill conceived code that swaps out textures instead of preloading all textures for that character.

If I were to preload the textures, it makes sense for sprite sheets. I would only imagine it's a bad idea to preload 1800 tiny images for each character.

However, I imagine streaming them into and out of memory one at a time would be extremely fast, so I would only need to have a single image in memory at one time. Wouldn't this mean that at any given moment I would only have each character consume a few KB instead of 45+MB?

I imagine this would kill my performance, as streaming would need to be incredibly fast (15 images going into and out of memory and rendering, per second) and although the images would be very small- it might be a better idea to load character spritesheets into memory instead. But I will have to code a single-image stream-like render system for my larger boss character anyway.

I have been experimenting, but it is not a simple process. Especially given the fact I am working on other parts of the game engine that do not deal with graphics right now.

# Answer
> 16 votes
We have a similar case with our RTS Remake. All units and houses are sprites. We have 18 000 sprites for units and houses and terrain, plus another ~6 000 for team colors (applied as masks). Long-stretched we also have some ~30 000 characters used in fonts.

So the main reason behind atlases are:

* less wasted RAM (in older days when you upload NPOT to GPU it stretched/padded it to POT, I read it's still the same with iOS and some frameworks. You better check on range of hardware you target)
* less texture switches
* faster loading of everything in fewer bigger chunks

What did not worked for us:

* paletted textures. The feature existed only in OpenGL 1.x 2.x and even then was mostly dropped by GPU makers. However if you aim at OpenGL+Shaders you can do that in shaders code yourself just fine!
* NPOT textures, we had issues with wrong borders and blurred sprites, which is unacceptable in pixel art. RAM usage was much higher too.

Now we have everything packed in several dozens of 1024x1024 atlases (modern GPUs support even bigger dimensions) and that works just well eating only ~300mb of memory, which is quite fine for a PC game. Some optimizations we had:

* add user option to use RGB5\_A1 instead of RGBA8 (checkerboard shadows)
* avoid 8bit Alpha when possible and use RGB5\_A1 format
* tightly pack sprites into atlases (see Bin Packing algorithms)
* store and load everything in one chunk from HDD (resource files should be generated offline)
* you might also try hardware compression formats (DXT, S3TC, etc.)

When you seriously consider moving to mobile devices you will worry about constraints. For now just get the game working and attract players! ;)

# Answer
> 5 votes
I have a tangentially related answer in here, but the general idea is that, if you're loading and drawing textures at different times (you're not loading additional textures while you're rendering), then there are two places where what you do will affect your performance:

**Loading time:**

This is the moment where you upload your textures into memory. The *entire* amount of data you are sending to VRAM is what will mostly define how long your loading time will be. Making your textures have smaller formats, like RGBA4444, will make this faster. However, unless you're uploading textures in the high hundreds of megabytes to VRAM, you will probably not be having a bottleneck in here. If you do, a nice loading screen can ease the wait.

Joining your textures into atlases will have little effect, as the entire amount of information you're sending into VRAM will be the same. In fact, if you're atlasing your textures, and you have to leave empty spaces in your atlases, then you will be actually sending *more* data into VRAM, and therefore this part will be slower!

**Rendering performance:**

Once all your textures are in VRAM, the amount of textures you have will not affect the rendering performance. There are four elements that do affect your rendering performance:

1. **Render state changes**: Each time you change the image you want to render from, will seriously increase the time required to render it. In general, you want to minimize the amount of state changes, and you can reduce the amount of state changes by grouping several images that you will consecutively draw, into a texture atlas.

Just atlasing is not enough. You have to atlas in a way in which state changes are reduced, in order to get performance gains. For example, one may think that having your main character in a sprite sheet will get you a performance gain, but if you're only drawing one sprite from that sprite sheet per frame, you won't be getting any performance gains compared to having each sprite in a separate file.

Proper atlasing is not trivial, but in general you can safely group sprites from the same layer. For example, having all GUI items in one sprite sheet is a very promising idea, while grouping monsters alphabetically may not.
2. **Draw calls:** In general, you may want to keep your draw calls to a minimum. A good rule of thumb is that if there are no render state changes between two draw calls, you can join them into a single draw call. For more advanced performance gains, you can use, say, 8 texture samplers, and group draw calls for every 8 textures, so you only have to change textures every 8 textures.
3. **Triangle count:** In fact, the more triangles you draw, the longer it will take to draw them. However, in modern computers, and for most 2D games, you will be very far away from maxing this out. You can safely draw hundreds of thousands of sprites per frame and still get insanely good framerates. You will probably be more CPU-bound if you're drawing extreme amounts of sprites before you get problems with your GPU.
4. **API settings:** If you're doing everything right, and you're still getting strangely low framerates, check the settings with which you're drawing your sprites. I don't know SFML, but for example, in Direct3D 9, creating a vertex buffer with `D3DUSAGE_DYNAMIC`, or in `D3DPOOL_MANAGED` can easily increase your rendering times tenfold. Of course, using vSync will cap your framerate at the refresh rate of your monitor. Also, using non-aligned FVFs may decrease performance in some GPUs. This too, is for Direct3D 9.

In your case, check the documentation for the API that you're using.

If you only have a low to moderate amount of textures (less than 1GB), and you're drawing low amounts of sprites (less than a million per frame), then the first thing I would look is at changing the API settings, and then reducing the amount of render states and draw calls.

---
Tags: 2d, textures, animation, sfml, texture-atlas
---


# Question
Title: What is the range of RAM consumption for the typical 3D character in a video game?
What is the average number of KB in memory for a 3D character? Granted, this will obviously be biased based on what game we're talking about. However, I am less interested in actual size in KB, and more interested in the range. Simply, a general idea.

I want to know this information, to compare it to my 2D game. Currently, my 2D game has an almost exact scale for how much RAM a character takes up in memory.

The current formula is this: 95KB * Number of Animations * Number of Frames * Number of Directions. So for example, if a character had an Idle Animation with 15 frames, and a Walk animation of 15 frames, and there were 4 directions the character could move, the character would take 11.4MB in memory.

3D Characters have to load their mesh, textures, and animations. 2D characters simply load a image. However, with hundreds of animations- I can only imagine the 2D character would eventually exceed the memory requirements of a 3D character.

I need to get a general idea of how many characters I should limit on screen, how I should load my characters and their animations in memory, etc. I get some performance hits when swapping out textures in memory, probably because they are large spritesheets. I do not know if not using spritesheets would fix this or not. I was always told "Sprite Sheets are good for performance."

What about 3D games? Any example would work, and it doesn't have to be a real range. I just want to know what I may be looking at. An example of a lower quality 3D game and an example of a higher quality 3D game would be perfect.

# Answer
General idea is very simple - "how much it needs to be" and depends on your artistic needs. You can make a model in Minecraft style (just a few Kb) or go a full scale NVidia-quality character (hundreds of Mb).

Calculate your budget first, how much memory you can spend on a model, what kind of quality do you need. Then you can do the estimates if you can fit an acceptable quality model in. Perceived model quality also greatly affected by artistic skills of the maker and rendering (dynamic lighting, complex SSS and SSAO shaders, etc.).

Try to compare with similar games.

P.S. From personal experience with racing games models. Good car model can take from 400kb to 26mb with the quality totally unrelated to the models size.
> 2 votes

# Answer
First, we eyeball the memory requirements for a 3d model.

* Each polygon has three vertices.
* Each vertex consists of three coordinates.
* Each coordinate is a floating point value of 4 bytes (or a double of 8 bytes)

So the amount of memory used for a 3d model is `polygons * 3 * 3 * 4` or `polygons * 36` byte. When your graphic engine uses double-precision floating point values, the size gets doubled.

So how many polygons does a character need? That depends on your level of detail. The characters from Minecraft have just about 100 polygons. But in a game which aims for a highly realistic graphic style, the polygon count for a single character can be tens of thousands of polygons.

This is just the 3d mesh. What we also need is the texture which is a simple 2d graphic. Maybe you want to use multi-texturing with normal maps, specular maps etc. Each of them is another 2d graphic. The memory consumption of each of them is `width * height * color-depth`. How large the texture needs to be depends on your desired level of detail. When the object is displayed up close you need a much higher texture resolution than when it is always small and far away, so it is hard to say which texture resolution is appropriate for your specific game.

Then we need the texture coordinates for each polygon (which part of the texture is mapped to each polygon). These are again 3 floating-point or integer values per polygon, so another 12 byte per polygon, getting us to `48 bytes per polygon`.

Now we have a 3d model with a texture standing in our game. What's needed now? Yes, animation! Compared to 2d sprites, animations for 3d models are rather cheap. You don't need a whole new 3d model for each animation frame. You usually just specify how whole parts of the 3d model move for each animation. You usually just define the end-points of keyframes and when your 3d engine excutes the motion, it interpolates the positions in-between. That means that the additional memory requirement for a whole animation sequence are usually just a few hundred to a few thousand bytes.

**By the way:** Usually, 3d models are not stored in RAM of the system but in the VRAM of the graphic card.
> 2 votes

---
Tags: 2d, 3d, models, memory-efficiency, memory
---


# Question
Title: Velocity deacceleration working incorrectly
Basicly, I've tried to code velocity into my game, which works sort of. The deaccelaration works sort of, but not correctly.

The problem is, that the positive values, decreases just fine and dandy to 0. (Up and Right) but if the velocity gets negative (Down and Left) the velocity value do get changed, but just changes instantly instead of using the Lerp.

I've tried anything that I can think of really, and which is why i've come here.

It should be said, that Im using the Unity engine and C# for this.

**Velocity code:**

```
if((velocity.z != 0)) {
        velocity.z = Mathf.Lerp(velocity.z, 0, deaccelerationSpeed);
        if((velocity.z < 0.0001f && velocity.z > 0)) {
            velocity.z = 0;
        } else if((velocity.z < -0.0001f && velocity.z < 0)) {
            velocity.z = 0;
        }
}

if((velocity.x != 0)) {
    velocity.x = Mathf.Lerp(velocity.x, 0, deaccelerationSpeed);
    if((velocity.x < 0.0001f && velocity.x > 0)) {
        velocity.x = 0;
    } else if((velocity.x < -0.0001f && velocity.x < 0)) {
        velocity.x = 0;
    }
}

```

# Answer
As I mentioned in my comment, your conditionals don't make any sense. The first will never execute and the 2nd is redundant. In the redundant conditional, you're setting velocity to zero *when velocity is less than zero*. Stew on that for a moment.

```
velocity.x = Mathf.Lerp(velocity.x, 0, deaccelerationSpeed);
if(Mathf.Abs(velocity.x) < 0.0001f) velocity.x = 0;

```
> 4 votes

# Answer
Like Drew mentioned, your conditionals don't make any sense for what you're trying to achieve. Instead, try:

```
velocity.z = Mathf.Lerp(velocity.z, 0, deaccelerationSpeed);
if (velocity.z < 0.01f && velocity.z > -0.01f)
    velocity.z = 0.0f;

```

Also, be careful of using the == operator with floats, since floats don't always evaluate they way you expect. If you haven't yet, go to this question and read the excellent answer by R...
> 1 votes

---
Tags: c#, unity, mathematics, debugging
---


# Question
Title: Graphics card settings tampering with my Java game
I'm working on a simple 2D side scrolling platform game in java.

It is a canvas with a bufferstrategy which is placed inside a jframe, and that jframe is set as the fullscreenwindow on the graphics device.

Now my computer has a decent nvidia card. In the nvidia control panel on my computer, just looking at the basic settings, if I set the the mode to "Emphasize performance," the game runs as it should and renders properly. The game is not vertical synced.

If I set the mode to "Emphasize quality" or "Let the 3D application decide," the game renders lines a slight distance away from where I intended them, collision detection is also slightly off, and things are overly anti-aliased. The game is now vertical synced.

Now on my crappy laptop, the game runs fine because the card is much less sophisticated. (I think?) However, on my friends computer, he plays with his ATI control center a bit (turns every enhancement off) and then the game runs perfect, but by default its a mess just like with my nvidia card.

**TLDR: Is there any way to override the settings on the graphics card or force the settings to be set a certain way from inside Java?**

# Answer
Thanks to XiaoChuan Yu who commented on my original post. This is the basic idea behind how I changed my game loop to make this problem go away:

```
private void gameLoop() {

    long current;
    long old = System.nanoTime();
    double nsPerUpdate = 1000000000D/60D;
    double updates = 0.0;

    while(running) {
        current = System.nanoTime();
        updates += (current - old) / nsPerUpdate;
        old = current;

        while (updates >= 1) {
            // perform all updates/logic here
            updates -= 1;
        }
        // render/draw here
    }

}

```

I'm still learning, but hopefully someone else will stumble upon this and it will help them. I appreciate the help.
> 1 votes

# Answer
Use OpenGL directly to get a consistent API across graphics devices and platforms.

I've found that SDL has been extremely reliable in providing a consistent interface across varied hardware. SDL exposes control over multisampling also.

EDIT: here's a binding: http://sdljava.sourceforge.net/

You can control vsync with:

```
SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, vsync_enabled);

```

And multisampling with::

```
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, fsaa_enabled);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, fsaa_quality); // try 2 or 4

```

This library has a native cross platform implementation, so it fits well with something like a Java game which (in my opinion) should be cross platform but still access low-level features.
> 1 votes

---
Tags: java
---


# Question
Title: What is the difference between a bonus and a power-up?
What is the difference between the notions of "bonus" and "power-up?"

I have in-game some objects and the player has the ability to pick up some bonuses/power-ups that allow the player to create an explosion all around. There's also an item that lets the player teleport from one place to another -- are these all power-ups?

# Answer
"Bonus" is usually used to describe something that effects the score or the outcome of the game (such as a score multiplier). "Power-ups" generally refer to things that give the game extra abilities/mechanics like increased speed or power. However, whoever you are talking to will probably understand what you mean no matter which word you use.
> 23 votes

# Answer
Personnaly, I'd see :

* a "power-up" as something that makes you more "potent"
* a "bonus" as a reward
> 11 votes

# Answer
Genrally (and perhaps not only in games)...

IMHO there is no **bonus** in what you describe, but only the pickup that lets the player explode all around (as a **powerup**), where the teleport is simply a **trigger**.

E.g. in Super Mario you have the coins which are simply **pickups** and you have the mushrooms that actually give you an extra ability making the mushroom a **powerup**. In some games you gain an extra bonus if you complete a level if you completed the level within a given time.
> 7 votes

# Answer
From my point of view,

* "power-ups" are items/abilities that can be gathered while playing (like a super temporary shield) to help,
* whereas "bonus" is something given because you were good enough to deserve it (like a bonus stage).

But power-ups are often called bonus and vice-versa.
> 5 votes

# Answer
* "power-ups" as the word suggests "pulls-up" your current "powers" ingame. Thus the effect is temporary and your powers will return to their previous default value when the power-up expired.
* A "bonus" is an addition to the things you own ingame (score, collection, powers) but it is has no time-out. (example : have a defensive bonus on a shield. the bonus won't go away unless i decide to swap it for some other bonus / if the bonus can expire after some time it's a power-up ;-) )
> 2 votes

# Answer
bonuses give you extra points/currency

power-ups give you extra abilities which you can use to earn points/currency more efficiently
> 0 votes

---
Tags: game-design
---


title: Circle-Rectangle collision resolution

text:
# Question
Title: Circle-Rectangle collision resolution
I have a non axis aligned rectangle, like a car, in my game. I have to check and resolve the collision between the rectangle and circle, which is stationary.

I have found lots of ways to determine the collision, but couldn't find anything on resolving it. It is clear that i have to push back the rectangle away if there is a collision, but I can't find a proper way.

Is there a way of handling and resolving the collision between a rectangle and a circle? Like an algorithm?

I am developing in c++.

# Answer
@ErikEsTT: the OP was specifically asking for more than a boolean "is intersecting", they need closest points or penetration depth or some other meaningful measurement of collision, not just a yes/no.

To answer the OP's question, circle-vs-rectangle can be implemented using a signed distance query between a rectangle and a circle. Probably the easiest thing to do is to transform the circle into the rectangle's local space (where it's an axis-aligned box) and then perform a point-vs-AABB signed distance query.

There is a brilliant (but quite confusing) signed box distance function here: https://iquilezles.org/www/articles/distfunctions/distfunctions.htm , or any good book (e.g RTCD or GeomTools) should have similar queries explained.
> 0 votes

# Answer
I took this answer, which is AABB - circle intersection and changed it into OBB - circle intersection and added compute of intersection point.

```
struct Vec2
{
    Vec2(): x( 0.0f ), y( 0.0f ) { }
    Vec2( float _x, float _y ): x( _x ), y( _y ) { }

    float x, y;
};

struct Box
{
    Vec2 Position, Size;
    float rotation;
};

struct Circle
{
    Vec2 Position;
    float radius;
};

Vec2 TranslatePointOnBox( const Vec2& BoxPosition, const Vec2& BoxRotation, const Vec2& Point, const Vec2& Sign )
{
    Vec2 LocalPoint( Point.x * Sign.x, Point.y * Sign.y );

    Vec2 WorldPoint;

    // rotate
    WorldPoint.x = LocalPoint.x * BoxRotation.x - LocalPoint.y * BoxRotation.y + BoxPosition.x;
    WorldPoint.y = LocalPoint.y * BoxRotation.x + LocalPoint.x * BoxRotation.y + BoxPosition.y;

    // translate
    WorldPoint.x += BoxPosition.x;
    WorldPoint.y += BoxPosition.y;

    return WorldPoint;
}

bool Itersects( const Circle& circle, const Box& box, Vec2& OutputPoint )
{
    Vec2 Diff1; // difference in world coord.
    Vec2 Diff2; // difference in local coord.
    Vec2 Rotation;
    Vec2 HalfSize;
    Vec2 Sign;  // for restoring intersection quadrant

    Diff1.x = circle.Position.x - box.Position.x;
    Diff1.y = circle.Position.y - box.Position.y;

    Rotation.x = cos( box.rotation );
    Rotation.y = sin( box.rotation );

    Diff2.x = Diff1.x * Rotation.x - Diff1.y * Rotation.y;
    Diff2.y = Diff1.y * Rotation.x + Diff1.x * Rotation.y;

    Sign.x = Diff2.x < 0.0f ? -1.0f : 1.0f;
    Sign.y = Diff2.y < 0.0f ? -1.0f : 1.0f;

    Diff2.x = abs( Diff2.x );
    Diff2.y = abs( Diff2.y );

    HalfSize.x = box.Size.x / 2.0f;
    HalfSize.y = box.Size.y / 2.0f;

    // intersection AABB - circle
    if( Diff2.x > HalfSize.x + circle.radius ||
        Diff2.y > HalfSize.y + circle.radius )
    {
        OutputPoint = Vec2( 0.0f, 0.0f );
        return false;
    }

    if( Diff2.x <= HalfSize.x )
    {
        OutputPoint = TranslatePointOnBox( box.Position, Rotation, Vec2( HalfSize.x, Diff2.y ), Sign );
        return true;
    }
    if( Diff2.y <= HalfSize.y )
    {
        OutputPoint = TranslatePointOnBox( box.Position, Rotation, Vec2( Diff2.x, HalfSize.y ), Sign );
        return true;
    }

    float CornerDistSquared =
        pow( Diff2.x - HalfSize.x, 2.0f ) +
        pow( Diff2.y - HalfSize.y, 2.0f );

    if( CornerDistSquared <= circle.radius * circle.radius )
    {
        OutputPoint = TranslatePointOnBox( box.Position, Rotation, HalfSize, Sign );
        return true;
    }
    else
    {
        OutputPoint = Vec2( 0.0f, 0.0f );
        return false;
    }
}

```

Note:

Intersection point is located on box surface, closest to circle center.

It is better to hold Box rotation in `Vec2 rotation;` instead `float rotation;`, so you don't need to compute sin/cos each intersection (compute only when rotation changes).

And you can omit `OutputPoint = Vec2( 0.0f, 0.0f );`, it return zero vector in no intersection cases.
> 0 votes

# Answer
I answered this over here, except the code is in Java (the math is easily translatable).

https://stackoverflow.com/questions/18704999/how-to-fix-circle-and-rectangle-overlap-in-collision-response/18790389#18790389

My solution handled axis-aligned boxes, but you can easily convert it to handle oriented boxes by rotating the circles current and future positions around the center of the rectangle until the rectangle is axis-aligned.

The aforementioned code accounts for high velocity moving circles, so that they can't pass through the rectangle and can't skip over corners.
> 0 votes

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


title: Monogame minimum hardware requirements?

text:
# Question
Title: Monogame minimum hardware requirements?
What are the minimum hardware / driver requirements for running a Monogame 3.x game, on each of the various Operating Systems?

# Answer
For the upcoming MonoGame SDL2 version; https://github.com/flibitijibibo/MonoGame

The SDL2 version is currently not slated to replace the Linux, Mac & GL solutions but when i asked the Dev he replied with "I hope so." I also asked him about shader versions;

As MonoGame runs on XP i'd assume that the D3D shader model requirement would be 3.0 (i.e. DirectX 9.0c). I feel it is also safe to assume then that the current MonoGame ports require GL 2.1 without ARB extensions. Which my laptop must lack.

My laptop for reference is running with an Intel Celeron processor with Mobile Intel® GMA 4500M for graphics (Which i believe has OpenGL 2.0/2.1) and that is currently on Linux(Before I changed it to running Linux I was running windows 7 and the WindowsGL solution would work perfectly fine).

This article on Gamasutra also provides more information on software requirements;

> For Windows desktop, you can use VS 2010 Express or higher, or VS 2012 Express for Desktop or higher on Windows 7 or 8.
>
> For Windows Store, you will need VS 2012 Express for Windows 8 or higher on Windows 8.
>
> For Windows Phone 8, you will need Windows 8 64-bit and the Windows Phone 8 SDK. This will install VS 2012 Express for Windows Phone, and can also work with VS 2012 Professional or higher.
>
> To use the Windows Phone 8 emulator, your PC needs to meet specific hardware requirements; see www.microsoft.com/en-GB/download/details.aspx?id=35471 for details.
>
> For Android and/or iOS, you will need VS 2010 or 2012 Professional or higher and Xamarin Business or higher on Windows 7 or 8.

http://www.gamasutra.com/view/feature/192209/from\_xna\_to\_monogame.php
> 1 votes

# Answer
Okay I'll start the wiki.

# Supported Platforms

iOS, Android, Windows (both OpenGL and DirectX), Mac OS X, Linux, Windows 8 Store, Windows Phone 8, PlayStation Mobile, and the OUYA console.

References: http://www.monogame.net/

# Prerequisites

References: https://github.com/mono/MonoGame/wiki/Tutorials:prerequisites https://monogame.codeplex.com/discussions/438421

# Platform Specific Requirements

* iOS - OpenGL ES
* Android - OpenGL ES
* Windows (OpenGL) - OpenGL
* Windows (DirectX) - DirectX
* Mac OS X - OpenGL
* Linux - OpenGL
* Windows 8 Store - DirectX
* Windows Phone 8 - DirectX
* PlayStation Mobile - ?
* OUYA - OpenGL ES

Reference: Project files https://github.com/mono/MonoGame/tree/develop/MonoGame.Framework

# Content Processing

The following are the system requirements for building content for all MonoGame target platforms:

* Windows XP w/SP2, Windows Vista, Windows 7, Windows 8.
* Visual C# 2010 Express or Pro with SP1 installed.
* Windows Phone SDK 7.1 (NOTE: Ensure that you install the Windows Phone SDK 7.1.1 Update shown below.)
* Windows Phone SDK 7.1.1 (**older XNA versions do not work!**)

At this time MonoGame does not include an independent implementation of the XNA content pipeline. We depend on Microsoft's XNA content pipeline implementation and Visual Studio 2010 on Windows to build content for all MonoGame platforms.

Reference: https://github.com/mono/MonoGame/wiki/MonoGame-Content-Processing

---
> 3 votes

# Answer
I asked the question over on the Monogame forums, this is the list that came from that:

> * **Windows Phone 8**: No restrictions. Will run on all Windows Phone 8 devices.
> * **Windows Store**: No restrictions. Same requirements as you you needed to meet to install Windows 8 on that PC.
> * **Windows desktop (OpenGL)**: I think OpenGL 3.0 is the minimum for graphics, plus OpenAL for audio.
> * **Windows desktop (DirectX)**: DirectX 11 installed.
> * **Android**: Android 2.3 minimum.
> * **iOS**: I think iOS 4.0 is the minimum.
> * **Mac OS X**: Should run on all recent and current Mac OS X hardware.
> * **Linux**: OpenGL 3.0 driver support, I think there's some other required packages such as libsdlmixer, etc.
> 3 votes

# Answer
Software:

Windows Vista:
DirectX11 installed
.NET 4.0/4.5 installed

Windows 7:
.NET 4.0/4.5 installed

Windows 8:
No dependancies (DirectX11 + .NET 4.5 already comes with OS)

Hardware:

However, that being said, it really depends on how memory intensive your game is. If it's a game with a lot of models, sprites etc. then you're going to need more RAM. A normal game needs about 2-4 GB of RAM, with a decent processor and a 64-bit OS.
> 0 votes

---
Tags: c#, monogame, .net, mono
---


title: Game Engine Design for the LWJGL

text:
# Question
Title: Game Engine Design for the LWJGL
I'm about to begin on the engine for the game I am making. However, I am quite uncertain how I should design it. I have heard lots about threaded games, component and asynchronous systems. I'm wondering which design will give the best performance using the LWJGL with a 2D game. I know that how I build it will greatly impact the performance. I just want to know what direction I should go in for the engine based on what has worked for others.

# Answer
> 2 votes
LWJGL is a tight wrapper around OpenGL. This means that best-practices, techniques and designs are rougly the same as any other language.

You have 2 options here:

* Write your own 2D engine with OpenGL
* Use a library for LWJGL like Slick. It will give you the basics like simple texture loading, font drawing and more.

If you are new to Java in general, it's a good idea to use a library, as you can focus more on the general Java programming instead of the OpenGL syntax. If you are completely new to Java though it's probably a better idea to do some normal Java programming first. Making a game is not a simple thing, especially if you are going to make the engine yourself. You will need to use alot of OOP, and you definitely need programming experience.

A good video tutorial series about Slick 2D: EddieVanHalen98 (youtube).

The exact techniques and designs depend on the type of game, and the scale of it. Your question is too broad for this site. As Sean said, start with your code, profile your code, and come back here for more specific questions.

---
Tags: 2d, performance, lwjgl
---


# Question
Title: Are binary storage methods more efficient than text based ones?
I'm working on a game which could potentially generate rather large save files, and so I'd like to find the smallest (most efficient, if you will) method of saving the game's data. I would need to save block types along with entity positions. Would a binary approach generate a smaller file than a text-based one? If so, how do I store the binary data?

# Answer
> 3 votes
It's not just about storage efficiency (and with today's disk sizes it could be argued that storage efficiency is among the least of your concerns), it's also about how fast it is to load data and how easy it is to translate your loaded data into something you can use.

For speed of loading, binary wins hands-down. It can be just as simple as a single fread into a previously allocated pointer, then your data is loaded and you're ready to go.

For translating that into something you can actually use, I'd argue that's more of a design issue than a format issue. If you build a design that requires complex and involved serialization, then it's going to require complex and involved serialization, irrespective of whether you use text or binary. On the other hand if you design simpler, then binary can win again - that single fread can result in everything you need loaded and correctly in-place, compared to having to write and debug a text-parser.

If despite this you still opt for text, then I'd advise that you at least design a single common format that you can run through a single common parser, otherwise you'll end up with multiple different, specialized, and useless-for-anything-else text-parsers in your code. Which is OK if you like writing text-parsers but not OK otherwise.

Ultimately it's up to you. Text does have the oft-cited advantage of being human-readable, but is that important for what you want to achieve? Are you designing a format to be read by humans or read by a machine? If you want human-readability then text is the way to go, if you don't need it then you should seriously consider binary.

---
Tags: savegame
---


# Question
Title: OpenGL: What are the adoption rates of the various versions (And what's a reasonable version to use)
This question is looking for updated answers for this question, which was made 1.5 years ago - as well as seeking more information.

Given that OpenGL 3.0 was released just over 5 years ago, what kinds of numbers are reasonable to expect for casual (To moderator) gamers, who have video cards that support OpenGL 3.0?

I think it's clear that a "modern gamer" would have a video card that supports OpenGL 3.0, and it's reasonable to assume that people who only use their computers for word processing and internet usage wouldn't... But what about in between? Is there data, either implicit through game popularity, or explicit from data sources like Steam (Which only tracks DirectX, sadly), that would give a decent idea of OpenGL adoption rates?

The reason why the Steam hardware survey isn't ideal for this, is because of the fact it groups hardcore gamers (And a lot of them) in with everyone else, not to mention the lack of OpenGL data - which can't always be inferred from DirectX support due to Microsoft requiring newer versions of Windows for newer versions of DirectX.

# Answer
The latest Intel drivers are limited to OpenGL 4.0. The hardware is likely capable of higher version, but that's all they're advertising. Chipsets older than Ivy Bridge are locked at GL 3.0 with no driver updates in years.

Linux's default FOSS drivers are limit to roughly OpenGL 3.1, though it can vary for each GPU chip. The base supported GL version has been increasingly steadily, with Intel usually the first chip to support new GL versions and some slightly older AMD chips right on their heels. Newer chipsets from AMD and almost everything from NVIDIA have very lacking support on the FOSS drivers.

OSX only supports up to 3.2 last time I looked, though the new version about to come up may increase that.

Windows drivers for AMD and NVIDIA (and the Linux versions of the proprietary drivers) are generally of the very latest version. Said versions are often quite buggy, however, and even some GL 3.x features were unusable just a year ago without getting frequent driver crashes or other driver issues.

For mobile, OpenGL ES 2.0 is standard. A few devices coming out this year have OpenGL ES 3.0 (a handful of Android devices and the iPhone 5S), but even the vast majority of brand new sets are still GL ES 2.0.

WebGL 1.0 is based on OpenGL 2.0. There is an experimental WebGL 2 from the Mozilla folks that targets GL ES 3.0, but it's in no way official or recommended for use by Khronos or supported by any browser except Firefox, and probably only behind a config flag.

The safest bet for maximum portability is to target the feature intersection of OpenGL ES 2.0 and OpenGL 3.0, and just account for the minor API differences that you'll run into. You can write code supporting both without too much effort. If you're looking to maximize capabilities of a graphics engine, you're just going to need to support different feature levels or APIs.

Aside from minimum version level support, just be aware of bugs. Just because you can use GL 4.x features in some place does not mean those features are stable. The vast majority of games and even CAD applications these days use DirectX or GL 2.x, so the newer versions of GL don't have a lot of stress tests from common applications. In general if you're writing a GL game you're at the mercy of what the tiny handful of other popular GL games (id's games, for instance) do as they will be well-supported. Simply calling certain GL functions in a different order than Carmack's team did could result in hitting a driver bug. In other words, a driver might support OpenGL 4.2, but you can only safely use the GL 3.1 subset of that and a few select popular extensions (arbitrary version numbers chosen for exposition). I'm not personally aware of any major bugs in GL 3 Windows drivers these days.

For information on driver stability and version support, I look to at Christophe Riccio's OpenGL status page. He is the author of GLM and a leading expert on OpenGL. That page does not list all drivers (the FOSS drivers are usually absent) and does not indicate uptake, but it is a key data point since as you stated DirectX versions don't map directly to GL versions (largely due to GL drivers lagging the standard pretty heavily).
> 5 votes

---
Tags: opengl
---


# Question
Title: How do I programmatically animate a .obj model?
I am developing on Qt, I have tried translate and rotate an .obj model.

I would like to know is there any possibility to do programmatically animate in Qt.

# Answer
> 7 votes
If you want to do animations, .obj is the wrong format for you. But, never-the-less:

You can do that with mesh-keyframing, or Skeletal animation. Skeletal animation is the typical, newer, choice. But mesh-keyframing still has it's place, and is easy to implement.

**Mesh-Keyframing**: Is when you have a whole bunch of meshes that represent a model doing certain thing's, when strung together. So, doing it with OBJ models, you might have something like:

```
Person_Standing.obj
Person_Crouching.obj
Person_LayingDown.obj
...

```

Where each model has all the same data, just different places for the vertices. You then loop through, blending between two model's, and you have a smooth animation! Though, typically, people use **`.md2`** files for that. There is plenty of documentation on it.

**Skeletal Animation**: Is when you have a hierarchy much like a skeleton in the human world, your hand's connected to your arm, which is connected to your torso, which is also connected to by your head, other arm, and leg's. You then "bind" the vertices of the mesh to their respective bone, and work out a system in which moving the bone moves the vertices bound to it. Collada files are typically used for this (**`.dae`** I believe.)

Here's a couple use-full references for you:

**Edit:** Some source code for you to reference.

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


# Question
Title: Tiled Map Editor - Isometric View Problem
I'm using the latest version of Tiled Map Editor (0.9.1) to create isometric maps. I have objects that are larger than my tile size (64 x 32), so I am breaking them up into two tiles of the correct size. Below I show that the blue blocks are made of a top and a bottom (both of which are 64 x 32).

You can also see that when I am placing these blocks side by side, there is some strange rendering overlap. Shouldn't the foreground be showing if it is rendered in the correct order?

In that picture you can see 4 blocks stacked side by side with the problem, 2 blocks side by side with the problem, 1 block by itself without the problem, and 1 dissected block in its two components.

Anyone know what's up?

**Note: this is the view from within the Tiled Map Editor itself, not from within my game.**

# Answer
> 2 votes
Figured it out. It's due to the tile graphic extending beyond the tile.

Update: I managed to work it out by playing with the tile layers. I placed foreground tiles in a layer below the background tiles.

---
Tags: rendering, tiles, isometric
---


title: Matchmaking system in Unity

text:
# Question
Title: Matchmaking system in Unity
I was wondering, how would one go about making a matchmaking system in Unity? I've tried some ideas with the Master Server, but it wasn't doing its job right, since thats a lobby based solution. I have a dedicated server of my own, so hosting myself is no problem.

I was simply just wondering, how and where to begin with this? I'm not asking for a "Complete solution" neither a package from the Unity Assetstore. Simply just an idea of how to start out.

# Answer
I'm assuming you are talking about a matchmaking system akin to those found in many multiplayer games, that attempts to pair you up with a player of a similar level of skill to your own.

I would start by looking to my favorite web development environment. You will need to create some sort of web interface that you can connect to using Unity. Typically, the easiest way to do this is using simple HTTP requests via the WWWForm class. In order for matchmaking to work, you will need to be able to identify the user, so you need some sort of authentication system, be it one where the user logs in to play, or one that stores some sort of ID on his machine -- but authentication is a whole other topic in itself.

So now you have a server that can identify the player, and a database with information about all the players. This is the point where you need to decide on a matchmaking algorithm. A few of these algorithms exist, but most games use the Elo system, typically slightly modified to better fit the game. Alternatives include Microsoft's TrueSkill and Mark Glickman's Glicko system.
> 2 votes

---
Tags: c#, unity, multiplayer, server, matchmaking
---


title: An approach for storing points in space

text:
# Question
Title: An approach for storing points in space
I am going to work on my next game project, however there are some issues I want to correct since my last one. Here is one of them:

This is a problem I think I can already solve, but I'd like to hear any criticisms on said solution, and perhaps hear other solutions that may exist.

**The problem:**

I have a window 800W by 600H, and my player's position is stored as pixels down, and pixels right. Lets say this player can run to the edge of the screen. This works fine until someone say, changes the size of the window, thus the player can run further out, where he should not be. In one of my first game attempts (a TD), enemies were dependent on the pixel position of game objects (Tiles), and thus by resizing the window, they ended up wandering off path.

**A solution:**

Represent the world with boundaries placed at 0 and 1 (or any other numerical pairing), and place entities as a percentage across. e.g. Player.positionX = 0.5, would mean that the player is half way across the map. Perhaps instead of 0, 1, it was 0, 1000 instead? With floating/double error in mind, what choice might I make?

So I think that would work fine in most cases, do you think so? What is a typical approach? What other approaches exist? How might platform/game type affect this choice? What if for some reason, the world size were to change dynamically? (Odd, but I'll throw it in there)

# Answer
> 4 votes
Letterbox and scale.

Percentages will still break your game. Think about different *aspect ratios*. The window might be 3:4, 16:10, etc. If you depend on pixel locations, these ratios between player and enemy locations will end up differing.

Instead, just pick a size of your world *completely independent of pixels*. Scale your graphics up or down if the resolution is different than your target. Strongly recommend to players to use even multiples of your graphics' intended resolution so that the game still looks smooth. Do *not* use on-screen pixels as any kind of meaningful unit of measurement!

For different aspect ratios, use letter boxing (black bars, either vertically or horizontally, to fill up the "excess space" from the resolution). That is, if the resolution's ratio is wider than your target, add vertical black bars on the side of the screen.

You can also just stretch and squash the pixels. If the player makes the window twice as wide, the game will *look* wide, but all your in-game units will be unchanged. The player might look like it's moving twice as fast horizontally but all the mechanics will be unchanged; the only difference is visual. This is not an ideal situation, but it works.

Ideally your game design just shouldn't care about these questions of resolution or aspect ratios. All of the interesting action should take place in a narrow aspect ratio, players with wider displays get no unfair advantages, etc. This is similar to what movies do. They are made in very wide formats like 2.39:1 but the cinematographer and director work to make sure that all the interesting things in the scene can be kept in after cropping down to the 4:3 ratio still common on older TVs (and eventually will target at minimum the 16:9 common to HDT/FHDT sets).

---
Tags: resolution, screen
---


# Question
Title: Shadows go through meshes, and also being applied to itself
I am using Ogre3D and I am using stencil shadows for my character. They work pretty well, but I have 2 problems: first, the shadow is applied to the entity it is casting the shadow, and secondly, the shadow goes through all the entities on the screen, and I would like to apply the shadow to only the first entity.

Also, the shadow gets rendered on the back of the model.

Images showing the problems:

# Answer
When you render stencil shadows, you have to extrude the silhouette edges out a large distance from the light. If you only extrude them down to the first platform, though, they will only affect that platform. The shadow volume will also have to be capped for this to work, in case you're not already doing that.

By extruding the volume to a level between the top and bottom surfaces of the platform, you can also ensure that the shadow appears only on the top side of the platform.

Another possibility, if you only need to cast shadows onto flat surfaces (the platforms), would be to switch to projected shadows. That's where you render the shadow caster using a matrix that squashes its geometry onto the floor, and use blending to darken the floor in that area. You can use the stencil test to prevent double-blending. It's a good bit simpler than shadow volumes, if you can work within its restrictions.
> 1 votes

---
Tags: ogre, shadows, stencil
---


title: Collision Code Organization

text:
# Question
Title: Collision Code Organization
Im making a game in java as a hobby and ive reached a part where i have a few game elements which i want to have collision. Since im using a tilemap, the collision with the wall tiles is pretty simple and since every game element has a pointer to the tilemap, the tile collision code can be placed in the game element class itself, so that every game element collides with the map, at least.

but as for the collision between the game elements themselves, which im going to do with separate axis theorem, i dont really know where to place it. the objects of each level are created on the said level class, since im using a game state manager and each level has a separate class (everything is a state basicly, lets say menu, level1, level2 etc)

So i COULD put the collision code in a, lets say, superclass of Level, but it sounds kinda wrong to put collision code on a class like that, and i dont really have any ideas.

So i would like to know how you organize your collision code in your games, i appreciate any kind of technique or simple architecture

# Answer
Create a separate class that has reference to the list of entities in your world. The entities should have metadata on them which dictates the type of entities they can collide with. Your new class should do two things, determine all possible collisions (this is called broadphase in the game-physics world), and then handle those potential collisions.

The first step could be a simple loop through every entity and check for collision with every other entity, OR you could use a spatial database to make this part quicker (like a grid, quadtree, etc). If you haven't used a spatial database before, just do it the former brute-force way.

The second step involves the actual collision checking.

There are SO many things that could change the way you handle collisions between entities. If you wanted your entities stackable for example, you would have to handle it a different way: You would loop through each entity, determine it's future position... and then check if it's future self would intersect with anyone else... if it does then don't move to the future position (or move it close enough so that it's not intersecting). Note the difference here, one just blindly updates position of all entities then tries to resolve collisions (like most physics libraries) and one carefully moves one entity at a time... which enables things like stacking and it avoids crazy intersections between multiple entities.
> 4 votes

---
Tags: java
---


title: Rotate image around a specified origin

text:
# Question
Title: Rotate image around a specified origin
I'm trying to rotate my Turret.png (small Gunhead with a laser in front) towards the mouses location on the screen. I tried just using my method for rotating projectiles towards the next step on their trajectory, but this produces unexpected results. Not only does the image not rotate about a fixed point, it also will clip based on the original images bounds.

My goal is for the turret to rotate about a fixed point on the gun head, so that the laser always points towards the mouse and the gun head is at a fixed position. Here is an example of how I'm trying to get it to rotate; in this example the rotation was 78 degrees done in Illustrator. The red dot represents the origin.

My current code is as follows,

This method updates my Gun Tower and tells the turret the angle to rotate to:

```
 public void setTargetAndDirection(int x, int y)
        {
                setTarget(x, y);
                deltaX = getTargetX() - getX();
                deltaY = getTargetY() - getY();
                turret.setRotatedImage(turret.getActiveImg(), -getTargetAngle());

        }

```

This is the method that actually handles the rotation:

```
      public void setOriginRotate(BufferedImage imageIn, float angle)
  {
      GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment()
                                .getDefaultScreenDevice().getDefaultConfiguration();

      int transparency = imageIn.getColorModel().getTransparency();
      BufferedImage temp =  gc.createCompatibleImage(
                              imageIn.getWidth(), imageIn.getHeight(), transparency );
      Graphics2D g2d = temp.createGraphics();

      int x = xLoc;
      int y = yLoc;

      g2d.setColor(Color.RED);

      AffineTransform at = AffineTransform.getTranslateInstance(x, y);
      at.setToRotation(Math.toRadians(-angle));
      g2d.setTransform(at);
      g2d.drawImage(imageIn, 0, 0, null);

      g2d.dispose();

      displayImg = temp;

      dispSizeX = displayImg.getWidth() / sizeMod;
      dispSizeY = displayImg.getHeight() / sizeMod;
  }

```

Any help would be greatly appreciated.

# Answer
> 6 votes
Instead of drawing the rotated image out to another image where you then draw that image out to Graphics to be displayed... why don't you draw directly to that Graphics object? This way it saves ALOT more time and doesn't waste memory.

```
Graphics2D g2d = ...
AffineTransform backup = g2d.getTransform();
AffineTransform trans = new AffineTransform();
trans.rotate( sprite.angle, sprite.x, sprite.y ); // the points to rotate around (the center in my example, your left side for your problem)

g2d.transform( trans );
g2d.drawImage( image, sprite.x, sprite.y );  // the actual location of the sprite

g2d.setTransform( backup ); // restore previous transform

```

And that should be it!

---
Tags: java, 2d, rotation, projectile-physics
---


title: #include loop C++

text:
# Question
Title: #include loop C++
I'm a noob in game development and i want to make a simple platform game in C++. The problem is whenI make two classes (Game and Graphics) I can't include Game.h in Graphics.h because I have already included Graphics.h in Game.h. Can anybody help me?
code:
Game.h:

```
#pragma once

#include "Graphics.h"

struct Game {
    Game();

    void init();
    void handle();

    bool running;

    Graphics g;
};

```

Graphics.h:

```
#pragma once

#include <SDL.h>

struct Graphics {
    SDL_Surface* screen;

    void init();

    void rect(SDL_Rect rect, Uint32 color);
    void rect(SDL_Rect rect, int r, int g, int b);
    void rect(int x, int y, int w, int h, Uint32 color);
    void rect(int x, int y, int w, int h, int r, int g, int b);

    void render(Game* game);
};

```

# Answer
First of all, an advice: keep www.cplusplus.com under your pillow. Go there at the minimum doubt you encounter with the language.

More specifically about the problem you are facing regading recursive includes, check out this article http://www.cplusplus.com/forum/articles/10627/, go to the section 4 of the article.

Applying the guidelines described in above mentioned article, you have to forward declare class Game in Graphics.h file, while you have to include Graphics.h in Game.h.

Game.h:

```
#pragma once

#include "Graphics.h"

struct Game {
    Game();

    void init();
    void handle();

    bool running;

    Graphics g;
};

```

Graphics.h:

```
#pragma once

#include <SDL.h>

// Forward declaration
struct Game;

struct Graphics {
    SDL_Surface* screen;

    void init();

    void rect(SDL_Rect rect, Uint32 color);
    void rect(SDL_Rect rect, int r, int g, int b);
    void rect(int x, int y, int w, int h, Uint32 color);
    void rect(int x, int y, int w, int h, int r, int g, int b);

    void render(Game* game);
};

```
> 4 votes

---
Tags: c++
---


# Question
Title: Design problem with specific requirements (logical dependencies needed)
I started to write some code for a small 3D environment. This week I wanted to start with my entities and when I thought about it again, I stumbled across some unmet requirements. My design works fine concerning the game loop, but I missed the logical relationships between distinct entities.
To show what I mean: my entities could interact through a common interface (my base class) but they lack the ability to react to a specific environment, e.g. imagine you have a simulation with some different animals. Some are carnivores (pretator) and some herbivores (prey). When I thought about my design, I somehow missed to include the ability to catch an entity's surroundings. My prey cannot find out about the predators near them ('am I in danger of being eaten? should I flee or am I safe? ..'), nor can the predators actually hunt their prey.

So I am looking for a design that is able to manage all entities through a single interface (game side) and allows information about the environment (entity side). Besides these, there are some more conditions:

* thread-safety
* expandable via dll (I'm using C++)
* effectivity

Side notes: my entities don't need to change properties during runtime (like in ECS) and I want injected entities (through dlls) to work properly with the original ones (e.g. if someone adds a lion through a dll, any prey should properly react to nearby lions as they are a kind of predator).

# Answer
Some years ago, I read an inspiring book which opened my mind to new approaches when creating software. The book is named "Turtles, Termites, and Traffic Jams: Explorations in Massively Parallel Microworlds (Complex Adaptive Systems)" and it explores the idea of having a non-static world but one which is modified by the creatures living on it. I think you can apply this approach to your case.

You can make all your creatures to leave a stench wherever they passes by. Each creature will have a different stench and it can be of a given intensity, have a given lifespan, etc. The creatures will have the ability to perceive stenches and react differently based upon it. So, in the end, the creature both affect and get affected by their environment, which sounds quite logical.

Stenches will be applied on the world, not on the creature, so creatures become independent one from another and you can easily add more types of creatures as when creating a new creature by plugin, it just needs to define which stench they lay on the world. Stenches can also be plugins easily.

You can have a base abstract class for the stench and define many specializations of it as needed (maybe the one for predator and the one for prey is enough for a test, but you can create one for carnivores, herbivores and so on).

About being threadsafe, this approach I think could be, as stenches are applied to the world, which has to be threadsafe beforehand.

I know I am not giving much details. Hope somehow helps, though.
> 1 votes

# Answer
You can use the same technique used in MMOs:

1) Every "entity" derive from an Item class;

2) World is divided in Regions (a grid for example);

3) Each Region has a subscribing mechanism. All Items can subscribe by passing a callback to a Region. Regions call these callbacks whenever them changes (for example after a move() function of an contained Item);

4) All relevant changes on Item are notified to the Region that contains it;

5) The "surroundings" of an Item are encapsulated by an InterestWindow which is a box or circle that subscribes the Item with whatever Region it enters or unsubscribe it with whatever Region it leaves.
> 1 votes

---
Tags: c++, entity-system, design-patterns
---


# Question
Title: Which consoles support fee-less indie game publishing?
On which consoles can I publish indie games without paying a license fee?

# Answer
> 2 votes
At the time of writing, all the major current and upcoming generation consoles (but one) don't make it possible to publish indie games without paying some kind of fee.

With the Xbox One, Microsoft's ID@Xbox program *may* provide what you are looking for. Currently, there's no explicit mention of payment on their site, but there's also no explicitly mention of gratis licensing, so you'll have to wait for more details to emerge as the console nears release, probably.

Additionally, right now they are only accepting applications from developers with a proven indie track record, so you may find getting accepted difficult.

Your next best bet is probably the Xbox Live Indie Games, on the 360 platform via XNA. This is not a free program -- membership costs $99 per year.

If you don't mind considering portable systems, Sony's mobile developer program also costs $99 per year, but as of May 8th Sony had stated that the fee for indie developers would be waived.

---
Tags: publishing
---


# Question
Title: Should I use select() for networking in my gameloop?
I'm writing a simple networked game in C/C++. To keep things simple I'm using TCP.

In my server's game loop I'm using a POSIX `select()` with a zero second timeout for two things:

* Discover incoming data from connected clients
* Discover new incoming connections

Is this a reasonable way to do it? Instead of using `select()` I could just loop through all connected socket descriptors and call `recv()` (or something like it) for each, to see if there is any new data. Would that be better?

The same question goes for the client. Note that on the client there's only one socket descriptor. Should I here use `select()` and a zero second timeout to find out if there's any new data incoming, or should I just call `recv()` on each game tick?

Or perhaps it would be even better if I pushed networking to a separate thread?

# Answer
For most real-time, interactive games, there's no benefit to moving your networking code into a separate thread; it just makes the code more complicated, creates more edge cases to have to cope with, and makes the game's networking more difficult to write and debug, *without giving you any benefits*.

Checking for activity using a non-blocking call to `select()` once each time through your game's main loop should be fine, unless you have some reason why your specific game's networking system needs to be multi-threaded.
> 2 votes

# Answer
If you can afford, from a complexity standpoint, to make networking threaded that would likely be your best option. That being said POSIX select will function fine otherwise.
> 0 votes

# Answer
If you're going to publish the network calls on a separate thread - feel free to do that but when you delegate events off to other systems in your game via packets you should make sure you try and call those from the main loop function. Otherwise, you're going to be in for a nasty concurrency issue. :) Start with one thread, let it go. Profile your game. If you find networking is sucking too much CPU, only then should you consider more complex implementations. Don't overdo it - you'll never finish your game if you stack on layers of complexity needlessly.
> 0 votes

---
Tags: networking, game-loop, c
---


# Question
Title: What to change when neural network is not classifying correctly?
I'm designing a learning algorithm for a simulation. In this simulation, there are minesweepers/tanks and also mines. Tanks are supposed to avoid collisions with mines, I'm using a neural network for teach them to avoid mines.

The inputs to my neural network are:

* Angle betweem tank and mine
* Distance between tank and mine

I'm trying to teach the network the following avoidance algorithm (pseudocode):

```
        if (angle < 10 && dist < 15){
            if mine is in clockwise direction:
                return -PI/4
            else
                return PI/4
        }
        else{
            return 0
        }

```

This will result in the tank not changing direction, turning left or right of mine. I have three layers in my network, 2 input neurons, 4 hidden neurons and 1 output neuron. Ive been testing my network with 300, 1000 and 42666 training examples. The best it's done is to produce only two directions for the tank, it never turns left meaning my network does not classify the -PI/4 part.

What can I tune to make it work? Do I increase training examples and iterations in the training loop, increase hidden number of neurons?

\[**EDIT**\]

I think I should mention that I'm using the hyperbolic function as an activation function. I added a bias to the inputs, the tanks are now doing a better job at avoiding mines, however, they still cannot turn left (network does not give negative values) hence they collide sometimes.

# Answer
> 4 votes
Firstly if you have a solution on how to do this don't use a neural network they are best in problem domains where the data is prone to be noisy and complex.

That said I'll carry on assuming a neural network is the right choice.

Your training data will need examples were -pi/4 is the expected output. In terms of volume you should be able to do it easily with that much data, are you using training and validation sets? Really you should train the network on around 60-70% of the whole data and use the other 40-30% to make sure the network is getting better at generalising and not just turning into a fancy lookup table.

Another point with the data, it should be normalised ideally. Say you have two inputs distance and rotation and in one instance you had a rotation of 0.2 rads and a distance of 200 metres the distance input will have a big effect on the output and the rotation will have a negligible effect. Normalise your inputs and they have the same sway on the networks output.

Moving from the data to the network.

A neuron traditionally has input legs and a bias leg, the values put into these give an output. Without a bias leg your neurons will be limited to positive values (which you naturally don't want).

When dealing with multilayer networks the back propagation algorithm is most common for training, you need an algorithm that can adapt each layers weights to minimise training time.

In terms of training the network, learning rate, momentum, network topology and iterations are what performance hinges on. These effect the network as follows:

Learning rate is basically the rate of change of the weights, the higher it is the quicker the network reaches an equilibrium however a lower learning rate although it takes longer moves through the state space at a finer resolution making it less likely to miss the optimal solution.

Momentum keeps the networks adjustments moving in a similar direction, this is useful to prevent the network reach equilibrium in a local minima in the state space. It will essentially overshoot the suboptimal solution and if at the right value keep going to the solution. When it reaches the solution it will overshoot, come back on itself and eventually decrease to settle (much like a pendulum swinging and coming to a stop). Momentum is useful in preventing premature stops.

Iterations the longer you go the more chance you have of reaching that equilibrium point where the network is just leaping on and off the best solution it can find given the learning rate and momentum used. Too many iterations can cause the network to "overlearn" and basically become a fancy lookup table working on your input data but not working as well on data it wasn't trained on. There are methods using the validation set to decide when to stop training based on a minimum desired accuracy or the point where the accuracy on the validation set starts to decrease on average.

Network layout. You really need to experiment with this one, too many it may not settle easily, too few hidden neurons it won't solve the problem sufficiently. There are heuristics to choose a number of hidden neurons but really trial and error is the best way.

Saying all this I don't think a neural network is the best solution for this. It's generally too uncontrollable/esoteric for game ai. I've used a neural network in one project it was classifying radar returns from the ionosphere and had 34 inputs from 3 high frequency receivers (an academic project). I achieved a 99.6% accuracy of classification. This is generally what neural networks are best at, for game AI I'd stick to behaviour trees, finite state machines, fuzzy logic and GOAP.

But neural networks are fun, and you are more than welcome to give it a shot you'll definitely learn from it.

---
Tags: algorithm, ai
---


# Question
Title: OpenGL camera translate and rotate on cameras local axis
How can I make rotation and translation on a local camera axis in OpenGL? I want to make camera like "aeroplane" camera with a pitch yaw and roll. I want to have good explanation on everything!

Can the solution be with gluLookAt maybe and be without gimbal lock?

# Answer
Please feel free to tell me if every step is understandable. If it's not i will add more explanation.

***Active variables -------------------------------------------------------------------------------------------------***

1. **camera\_drot={Rotation arou x(right) axe, -\\- y(up) axe, -\\- z(forward) axe} \[radians\]**
2. **camera\_dtra={Translation by x(right) axe, -\\- y(up) axe, -\\- z(forward) axe}**

Code:

```
float camera_drot[3]={0,0,0};
float camera_dtra[3]={0,0,0};

float camera_place[3]={0,0,0};
float camera_right[3]={1,0,0};
float camera_up[3]={0,1,0};
float camera_forward[3]={0,0,-1};

```

***Algoritem of transformation ------------------------------------------------------------------------------------***

1. I will delete camera\_ for better view. :)
2. If you rotate camera's axis around x axe you must rotate y and z axe (example).
3. **After the rotation its vital to make sure the forward,up,right acis is rectangular and all axis must have length "1"! If we dont make Orthonormality(forward,right,up) the errors in computers computation will sums up really fast! Belive me!**
4. **After the Orthonormality we can translate cameras place in local system of cameras axis.**
5. The good old gluLookAt() the simplest thing to comunicate with OpenGL obout cameras properties.

Code:

```
if(drot[0]!=0){
    MYRotation(right,up,drot[0]);      //#Rotate up axis oround right for drot[0] radians
    MYRotation(right,forward,drot[0]);
    drot[0]=0;}
if(drot[1]!=0){
    MYRotation(up,right,drot[1]);
    MYRotation(up,forward,drot[1]);
    drot[1]=0;}
if(drot[2]!=0){
    MYRotation(forward,right,drot[2]);
    MYRotation(forward,up,drot[2]);
    drot[2]=0;}

Orthonormality(forward,right,up);

if(dtra[0]!=0){
    MYTranslation(right,place,dtra[0]);
    dtra[0]=0;}
if(dtra[1]!=0){
    MYTranslation(up,place,dtra[1]);
    dtra[1]=0;}
if(dtra[2]!=0){
    MYTranslation(forward,place,dtra[2]);
    dtra[2]=0;}

glLoadIdentity();
gluLookAt(place[0],place[1],place[2],
          place[0]+forward[0],place[1]+forward[1],place[2]+forward[2],
          up[0],up[1],up[2]);

```

***MY Functions --------------------------------------------------------------------------------------------------------***

***Orthonormality***

1. Normalize vec0! If we normalize vec0 we simplify many things!
2. Projected vec1 on ortogonal space of vec0 vector.orthogonal complement
3. After a projection we have to normalize new vec1!
4. And in this step we find vec3 with Gram–Schmidt process
5. Final step is normalize vec3.

Code:

```
static void Orthonormality(float vec0[3],float vec1[3],float vec2[3]){
    //1
    float normalize = pow(vec0[0]*vec0[0]+vec0[1]*vec0[1]+vec0[2]*vec0[2],-0.5);
    if(normalize!=1){
        vec0[0]=vec0[0]*normalize;
        vec0[1]=vec0[1]*normalize;
        vec0[2]=vec0[2]*normalize;}

    //2
    float x1=vec1[0];
    float y1=vec1[1];
    float z1=vec1[2];

    vec1[0]=x1*(vec0[1]*vec0[1] + vec0[2]*vec0[2]) - vec0[0]*(vec0[1]*y1 + vec0[2]*z1);
    vec1[1]=-vec0[0]*x1*vec0[1] + vec0[0]*vec0[0]*y1 + vec0[2]*(y1*vec0[2] - vec0[1]*z1);
    vec1[2]=-(vec0[0]*x1 + vec0[1]*y1)*vec0[2] + (vec0[0]*vec0[0] + vec0[1]*vec0[1])*z1;

    //3
    normalize = pow(vec1[0]*vec1[0]+vec1[1]*vec1[1]+vec1[2]*vec1[2],-0.5);
    vec1[0]=vec1[0]*normalize;
    vec1[1]=vec1[1]*normalize;
    vec1[2]=vec1[2]*normalize;

    //4
    float x0x2_y0y2_z0z2=vec0[0]*vec2[0] + vec0[1]*vec2[1] + vec0[2]*vec2[2];
    float x1x2_y1y2_z1z2=vec1[0]*vec2[0] + vec1[1]*vec2[1] + vec1[2]*vec2[2];
    vec2[0] = vec2[0] - vec0[0]*x0x2_y0y2_z0z2 - vec1[0]*x1x2_y1y2_z1z2;
    vec2[1] = vec2[1] - vec0[1]*x0x2_y0y2_z0z2 - vec1[1]*x1x2_y1y2_z1z2;
    vec2[2] = vec2[2] - vec0[2]*x0x2_y0y2_z0z2 - vec1[2]*x1x2_y1y2_z1z2;

    //5
    normalize = pow(vec2[0]*vec2[0]+vec2[1]*vec2[1]+vec2[2]*vec2[2],-0.5);
    vec2[0]=vec2[0]*normalize;
    vec2[1]=vec2[1]*normalize;
    vec2[2]=vec2[2]*normalize;
    }

```

***MYRotation***

Rotate vec around line for drot radians.

```
static void MYRotation(float line[3],float vec[3],float drot){
    float ux=line[0]*vec[0];
    float vy=line[1]*vec[1];
    float wz=line[2]*vec[2];
    float uu=pow(line[0],2);
    float vv=pow(line[1],2);
    float ww=pow(line[2],2);
    float uxvywz=ux+vy+wz;
    float sa=sin(drot);
    float ca=cos(drot);
    vec[0]=line[0]*uxvywz+(vec[0]*(vv+ww)-line[0]*(vy+wz))*ca+(-line[2]*vec[1]+line[1]*vec[2])*sa;
    vec[1]=line[1]*uxvywz+(vec[1]*(uu+ww)-line[1]*(ux+wz))*ca+( line[2]*vec[0]-line[0]*vec[2])*sa;
    vec[2]=line[2]*uxvywz+(vec[2]*(uu+vv)-line[2]*(ux+vy))*ca+(-line[1]*vec[0]+line[0]*vec[1])*sa;
    }

```

***MYTranslation***

Translate vec for line\*dtra

```
static void MYTranslation(float line[3],float vec[3],float dtra){
    vec[0]+=line[0]*dtra;
    vec[1]+=line[1]*dtra;
    vec[2]+=line[2]*dtra;}

```
> 2 votes

---
Tags: c++, opengl, 3d, camera, transformation
---


# Question
Title: Is there a place in games for people with financial engineering or operations research backgrounds?
I just started my first year in college in an engineering school. I haven't had any classes about programming, and although I'm in an engineering school I'm not that good at (and don't enjoy) physics or chemistry. For me, the way to go is math related majors, which are Financial Engineering or Operations Research.

Although I believe I will be somewhat good in those areas I definitely don't want to get sucked into the "financial blackhole" with extreme work hours and stress levels. I want to have creativity in my life.

So I am wondering what kind of jobs can I find in the gaming industry with a background of Financial Engineering or Operations Research? Can I join the creative groups of game development companies?

# Answer
> 2 votes
There are almost *zero* formal jobs in the industry for that kind of educational background, I'm afraid.

The most likely place you'd find a job that utilizes those skills would be in the economics analysis areas occasionally employed by studios that ship large MMOs. Those "departments," if they exist at all, are typically very small (often only a single person) in size and you won't likely be getting that kind of job right out of college. Because the economics of online computer games differ somewhat from the economics of reality, studios that have those positions will prefer senior people who also have other experience in the games industry.

I hate to break it to you, but in that position you often won't have that much creative input either. Of course this varies from studio to studio, but I wouldn't hold my breath. Additionally, you seem to be somewhat out of touch with the reality of the games industry, which is one fraught with crunch and unpaid overtime. If you're looking for a leisurely life in this field, you probably won't find it easily. It exists, but it may take you a long time to get there.

This isn't to say that you won't be able to get a job in the industry. Actual game designers tend to have a wide variety of backgrounds, because that helps bring a sense of well-roundedness to the entire team. You should know that in a position as a game designer, you may end up calling on the skills you learned in those college programs occasionally, but they won't be a part of the majority of your day-to-day tasks in all likelihood.

---
Tags: career, education, jobs
---


title: Changing weapons on a model?

text:
# Question
Title: Changing weapons on a model?
How would you have 1 soldier model and then change the weapon depending on what class is chosen without having to load all the weapons at once and without having to load a new soldier for every weapon?

# Answer
> 7 votes
You make a single soldier model. You make a number of weapons.

Then you would use something oft called a "hard point" (or "attach point" or many other things). You set such a point on the model's hand. You set another such point on the gun's grip. Now you can programmatically look up these points in the model data and mount the gun's grip in the soldier's hand (using either "model parenting" if you support such or just setting the world position of the gun appropriately). Because the soldier's hard point should be attached to a bone, the gun will stay in the soldier's hand during animation. You can now swap out the gun at will and place whichever gun you want in the soldier's hand with no additional work.

You may also have some animation data for the soldier to control when the hand is in a "hold a pistol" state or both arms and hands are in a "hold a rifle" state or the soldier is holding nothing and is in an "unarmed" state. You can blend these animation states with the other animations being used, or make a set of animations (running, idling, etc.) for each general class of gun. The complexity of the animations and desired level of realism/fidelity will determine how far you must go here.

You can go another step and programmatically animate the soldier model to the gun's dimensions using the hard points to determine where the hands should be placed and what general state they should be in so that the soldier smoothly works with any of a very wide variety of accurately modeled guns (not all rifles are held the same way). This is not the easiest thing to do by any stretch but is required if you want a very realistic game or have a very wide variety of gun types.

---
Tags: 3d, models
---


# Question
Title: Robust "soft" platform collision using SAT
We'll start with the questions, then a pile of background:

* How do you rigorously and thoroughly define "soft collision" of the Mario-esque type (if I start above, or in a jump my feet apex above a "soft platform", I'll land on it)?
* Can you suggest a definition in terms of object-versus-segment (or line, or ray, or whatever similar terrain boundary), in a SAT framework?
* Any good examples/references for soft collision out there, even in non-SAT frameworks?
* Finally, any edge/corner cases, literal or otherwise, that might not be obvious?

---

The background:

6+ years ago, I built a simple AABB object versus line-segment terrain collision system for $work, based heavily on N Tutorial A - Collision Detection and Response. (This goes against my advice to never write physics/collision for production code oneself, but we had strange requirements: no FPU, blazingly fast SRAM and bus, and a relatively slow CPU.)

Over the years, we've dealt with a number of (sometimes quite literal) "corner cases", including how we deal with fast-moving objects (currently very fine-grained multisampling), order of collision resolution, et cetera. This is the usual difficult stuff for naïve SAT, it would seem.

Recently another issue with our "soft collision" -- that is, platforms one can jump "up" through, but not fall "down" through (where "up" and "down" are relative to a unit normal off the line segment) -- has cropped up.

This has me wondering if I've "stated the problem" correctly vis a vis soft platforms.

As background, the bug in this case involved characters jumping with an arc such that their "head" *just* hit the bottom of the soft line segment. Our collision system does, roughly:

1. **early-miss** if `movement.dot( segmentUnitNormal ) > 0` // moving away from segment, for all segments *(debatable whether this should be here, but probably largely irrelevant for this problem)*
2. normal three-axis SAT (x-axis, y-axis, and line-axis) with miss if any axis shows separation; compute proposed `projection` to displace box out of segment if hit
3. **late-miss** unless `0 <= projection.dot( segmentUnitNormal ) < 1` // for "soft" segments only
4. finally, **hit**

Step #3 -- specifically the `0 ==` part of `0 <=` -- is the issue here. (On the other end of the range, the choice of `1` as cutoff for maximum interpenetration is arbitrary: it's based on our multisample worst case projection response.)

Amusingly, the comment above step #3 in the code says something like "Miss unless we started 'above' the segment, or if interpenetration is too deep."

The logic as stated says nothing about starting above, instead dealing only with response along unit normal.

As mentioned, the `0` case here is the issue: if the character's "head" hits the segment exactly at the peak of his jump and we compute a zero response, we'll treat that as a hit, when we'd expect to only get hits when our "feet" are at or just above the segment.

We could just exclude the 0 case here, and deal with a little "bounce" when resting on our soft platform, but then we'd have strange cases where we might not seem to be in contact with the world geometry every other frame, which has other implications for the animation system and the like. I'd like to preserve 0 interpenetration = hit behavior.

I have a few possible solutions, mostly boiling down to things like:

* "check if AABB centerpoint started on the correct side of the segment", or
* "retain the directionality of the projection even if it collapses to zero length" (something like a "signed zero" here -- we already have this from our SAT calculations earlier),

...coupled with a little more care re whether we're using "computed projection along the line axis" versus "shortest computed projection" in these tests.

All of these solutions seem to be robust, in my initial tests.

But it has me wondering if I'm missing something obvious; hence the questions above.

# Answer
Generally this is done with *collision filters*.

Set a filter on the block. This filter is called when a *new* collision is detected and tells the physics engine whether it should resolve the collision as usual or ignore the collision *for the lifetime on the collision* (meaning the filter's decision is applied until the objects stop colliding, and is called again next time the objects collide).

This filter then simply sets the collision as ignored if the initial collision is not a "downward" collision (that is, if the bottom of the moving sprite was above the top of the platform the previous frame). That's all there is to it.

Some games which allows players to "drop" through a platform would restart the collision when the drop key combination is pressed and would ignore any collision with such a platform so long as the key combination is pressed.

There is absolutely no need to change the collision detection (SAT or such). It's the *resolution* that needs to be updated to enable the use of filters and ignoring contacts per the filter's result.
> 4 votes

---
Tags: collision-detection, separating-axis-theorem
---


# Question
Title: Confused about DXT/DDS compression and color depth
I have done my research on DDS/DXT compression, and the information is kind of "everywhere." It is rather difficult to even find good, organized, sensible information on color depth. However, it is apparent that DXT5 changes the image to... RGB565?

Alright, so I am restricted to 16 bit color and RGB565. Makes sense. I also read that converting it yourself, choosing the colors in the image, can stop or even entirely prevent loss of detail.

Nvidia's Photoshop plugin seems to degrade the quality to something much worse than other programs are capable of when converting an image to RGB565.

In particular, I use an absolutely wonderful tool which allows me to choose the colors. I altered my image to actually only include 128 colors. This is less than the 256 allowed by RGB565.

However, Nvidia's Photoshop plugin seems to ignore those colors, and chooses its own- as if I never changed the image in the first place. It's identical to what it was if I convert it to DDS from 24 bit Truecolor.

Why is Nvidia's tool not keeping my color table? Why is it still lossy, and significantly worse at Nvidia's 256 colors, when my 128 color version is so superior and loses no quality or detail?

Currently, I am using "COLOR QUANTIZER", which is the best tool I have found to lower the number of colors without losing image quality.

I might be a little confused, as apparently TexturePacker's RGBA5555 is 20 bit and unsupported in a lot of frameworks, which confused me thinking RGB565 and RGBA5555 were both 16 bit. (Dur! The non-existence of RGBA5555 in google threw me off bigtime.) However, I assume I could easily achieve RGBA4444 (16 bit with alpha) because my colors can degrade in COLOR QUANTIZER to 128 colors, and RGBA4444 supports 256 colors. When I use TEXTUREPACKER or other programs, it is worse quality than in COLOR QUANTIZER. This program is simply superior in my experience, and I have been obsessive with all tools available to find the best one.

My images: PNG with pre-multiplied alpha. Can degrade to 128 colors, in COLOR QUANTIZER, before losing any quality. Alpha is a very big requirement, so RGB565 and DXT1 are out of the question. These are small sprites, which are smaller than 100x200.

My Goal: Low memory consumption and compression. Obviously, the best way to handle this would be DDS/DXT5 so I can keep the textures compressed in memory. Although I could handle RGBA4444, it is only a 2:1 compression, while DXT5 is 4:1. I would much prefer to use the DDS format.

# Answer
It may sound like DXT5 uses RGB565 palette, but in fact this is a bit more complicated. Image is being split into small blocks and in each block DXT picks 2 colors to be stored in RGB565 format, also 2 colors are interpolated and these ones can be RGB888 (if you take two neighbor 565 colors and 2 in between).

It looks like COLOR QUANTIZER that you mention picks best 128 colors, so the quality loss is not noticeable. DXT on the other hand has one major limitation - it can pick only 2 colors per block of 4x4 pixels. That mean that if you e.g. have a small rainbow and R G B colors in one block, only two colors will be preserved and third will be dropped. Example I could find, original is on left, notice how due to bad colors the right image has blocks of red chipped:

Usually that does not happen with large images, because they tend to have less colors transitions in small areas, but if you use pixel-art it damages it a lot.

There is another issue (at least it was true in 2008) with nvidia compression tool. It picked unoptimal pair of RGB565 colors for the block of pixels. E.g. if I compressed a logo on pure almost white background (254,254,253) even when there were blocks of solid color they all were replaced with a different greenish tint (250,254,249). So you might look for a different compression tool if quality "almost" satisfies you.

The fact is however, that you need to test the options you have and pick the one that suits your situation best. It may be DXT, or it could be S3TC or something else. Just see what options SFML offers you and start trying them out!
> 1 votes

# Answer
Err, you've got confused somewhere. Both RGB565 and RGBA4444 support exactly 65536 colours, and there's no colour palette used. If you ignore alpha then RGB4444 only stores 4096 colours, which generally isn't very useful.

DXT1 supports more colours than that because it can interpolate between two 565 colours. However in any 4x4 block it only supports four different colours (two 565 ones, and two interpolated ones). That can cause nasty compression artefacts on small detailed images, but will generally work well on a texture for a 3D object.

DXT5 does the same thing with the colour channel as DXT1, but also supports an alpha channel on top, which has better precision than the colour channel. It's also double the size of a DXT1 image.

It might be helpful if you posted an example of a problematic image, before and after compression.

If you want to store a palletized image, then you'll need to store the image data in an 8-bit texture format, and the palette separately as an RGBA image. You can then combine them in the fragment shader.
> 2 votes

# Answer
Step 1: Load your color and alpha images into two different OpenGL textures.

Step 2: Use glActiveTexture to switch to between and bind both color and alpha to GL\_TEXTURE0 and GL\_TEXTURE1.

Step 3: In your fragment shader, define texture samplers for color and alpha, and use the right one to get the right channels in your shader.

Step 4: Set "color" and "alpha" uniform variables using glUniform1i to 0 and 1, for textures 0 and 1.

This will let you pick different memory layouts for color and alpha, and should still save memory over a standard 32-bit, while providing perfect alpha gradients.
> 1 votes

---
Tags: textures, compression, dds
---


# Question
Title: Udp VS Tcp connection for a platformer multiplayer
Tcp is connection based so it's really good for chat or login or anything that needs reliability. Udp should be used for lots of small packets like position packets... The problem is that in a game like what I'm doing right now (terraria like), I can't decide what to use and how to use it properly. I though about using both at the same time, but can't find a way to ensure the udp "connection" will work.

If I were to choose UDP, is there a way I could make a "connection" out of it? to rely on it for login or chat messages?

And if I were to use TCP, would there be a way to speed it up?

More info : I'm doing this in C#.NET with XNA (I know it's no longer developped but I like it :P). I would also like to use Serialized objects (.Net BinaryFormatter), but it uses streams, and stream are only available in TCP... which makes it more attractive...

Thanks a lot!

# Answer
> 1 votes
Don't use TCP and UDP at the same time. I would recommend you to use UDP for everything, and some way of knowing when packets get lost.

I recommend a library called Lidgren for UDP programming: http://code.google.com/p/lidgren-network-gen3/

And using protocol buffers (there is a C# implementation of them) for serializing.

# Answer
> 0 votes
**The old debate over UDP/TCP speed is over a decade old but still troubles newcomers.**

As long as you remove nagle's algorithm and such, TCP will be fine for you. It is (IMO) also easier to use because all the checks (packet loss / orders) are already done. If you are unsure anyway, use some package/library that takes care of all of those things for you, there are ones where you can choose UDP or TCP as you want to too.

---
Tags: xna, c#, server, udp
---


# Question
Title: physics of 2D car racing game with heightmap
I want to develop a simple car racing game where the road is defined by a heightmap. It looks basically like this:

The player can use throttle and brake to control the car.

I'm wondering what the best approach for the physics is. I have some ideas:

* Use a mass-spring system with one mass for each wheel.

*Pro:* Gravity affects each wheel independly, so if one wheel stands on ground and the other one floats in the air, the car rotates. Can be extended to three dimensions by adding two more wheels.

*Contra:* The distance between the weels varies. The system may explode (when forces amplify each other). The car will fall down if both wheels float, but the middle of the car touches ground.
* Define the car's state using position, momentum, rotation and spin.

*Pro:* The wheel distance is constant, no springs included

*Contra:* very complex, hard to compute, not really extensible to a third dimension

I think there must be a better way than those.

# Answer
If you want to apply physics, you have to use physical engine. I would recommend you to use Box2D which is a good 2D physical engine for C++ or JBox2D which is the Java version of Box2D. If you want a 3D physical engine I think Bullet is a nice one. There are lot of tutorials about all of them, just google it (I can't add more hyperlinks).
> 1 votes

---
Tags: 2d, physics, racing, car
---