title: Is learning OpenGL 2.1 useless today?

text:
# Question
Title: Is learning OpenGL 2.1 useless today?
I'm new to 3D OpenGL/DirectX world and I found out that OpenGL 4.1 and GLSL specifications were just released today.

A friend of mine gave me the Red Book for OGL v2.1 but, as far as I've read, 3.x and 4.x differ a lot from 2.x and a lot of things are deprecated now.

Can I use the book to start learning the basics of 3D and CG or is it better to find a newer copy?

# Answer
> 19 votes
In times like this I always head for the Steam Hardware Survey: http://store.steampowered.com/hwsurvey/ \- you'll see that market penetration of DX10/11 class systems is at almost 80%; this being broadly equivalent to GL3.3 or above. This 80% is restricted to Vista/7 users - add in a DX10/11 GPU with XP and you rise to just over 90%.

Bearing in mind that we're talking about slightly more hardcore gamers here, you then need to start thinking about your target audience. Are these the people you want to target? Are you aiming at those with more downlevel hardware instead? What about Intel graphics? What about Mac and Linux users? These are all questions that you need to answer for yourself, so broadly general guidelines are the best you're going to get.

Adding to that, you need to take account of the fact that if you're starting to learn today with the intention of shipping something, you're looking at a period of about one year minimum before you get there (unless we're talking about really trivial/simple cases). With the upward trend of gfx capabilities continuing, we're looking at being real close to 100% uptake of GL3.3+ hardware by then.

Then factor in that with GL2.1 or lower you're going to be learning and using an awful lot of crufty old nonsense, even if you restrict yourself to the shaders and VBOs subset of GL2.1 (downlevel GLSL versions are nasty to use, and streaming VBOs are all but unusable without GL\_ARB\_map\_buffer\_range) - GL3.3+ has introduced *much* nicer (and more performant) ways of handling many things, you'll be making better use of the player's hardware (and they'll be grateful to you for that) and you'll be spending more time writing productive code rather than fighting an API that really doesn't want to co-operate with you.

And then of course there's the dreaded driver situation. The hard but true fact is that GL drivers on Windows are in a sorry state - NV support things they shouldn't, AMD don't support things they should, and with Intel you really need to restrict yourself to GL functionality for which there is an equivalent in D3D. The newer the GL\_VERSION is the more likely it is you'll encounter driver bugs, but for GL3.3 things are reasonably stable now.

So the summary is that, in the absence of any other info (target audience, etc), I'd target GL3.3 as a baseline (possibly pulling in functionality from higher GL\_VERSIONs where it's available and where it doesn't disrupt the codebase too much) unless there was a very specific and definitively identified reason to go any lower (and I'd want to be absolutely 100% certain of that rather than using some vague notion of "*but what about those with older hardware*"). In the latter case I wouldn't go below GL2.1, and I'd look to pull in as much 3.x functionality as possible even then.

# Answer
> 38 votes
I would suggest sticking with the intersection of 2.1 and 3. There is still a lot of hardware and drivers that only support OpenGL 2.1, but the practices encouraged by OpenGL 3 core *are* better. This tutorial is a pretty good place to start (teaches OpenGL 2.0 without features that have been deprecated in 3).

# Answer
> 18 votes
I would say it's not useless.

Why? Well, while the rest of the world is supporting OpenGL 3.x and 4.0, Mac OS X still only supports OpenGL 2.1. And, OpenGL ES, which is used on most, if not all, portable platforms, is still widely supported at all versions: 1.0, 1.1, and 2.0; which are roughly comparable to OpenGL 1.4, 1.5, and 2.1, respectively.

So until OpenGL ES 1.0 disappears completely from the face of the Earth, knowing OpenGL 2.x will *not* be a waste.

That's not to say there isn't value in using OpenGL 3.x or 4.0 on platforms that support it, of course.

Update: As of the release of Mac OS X Lion (10.7), OpenGL 3.2 Core profile is now supported on the Mac. This release deprecates large parts of OpenGL 1.x to simplify the API. Users of older versions of OS X (and low-end Intel graphics) are still limited to OpenGL 2.0 and 2.1. Knowing OpenGL 2.x is nevertheless still useful, and will remain so for quite some time.

# Answer
> 11 votes
mh01's answer covered much of the basics, so I'm going to add a few suppliments.

## OpenGL ES

Let's talk about about ES 2.0 vs. desktop GL 2.1 vs. desktop GL 3.3. For the purpose of this discussion, the term "GL X.Y" will refer to the desktop OpenGL version X.Y, while "ES X.Y" will refer to OpenGL ES X.Y.

*Structurally*, ES 2.0 has more in common with core GL 3.3 than it does with GL 2.1. GL 3.3 and ES 2.0 are both pure-shader based. They're both pure buffer-object based. Etc. GL 2.1 has many performance and coding traps that would make it easy to write a GL 2.1 app that wouldn't easily be portable to ES 2.0.

However, in terms of shading language *syntax*, GLSL ES 1.00 (mapping to ES 2.0) looks much more like GL 2.1's GLSL than GL 3.3's. The `attribute` and `varying` keywords don't exist in 3.3 core; it uses `in` and `out`, which is a lot more consistent and reasonable when you're dealing with more than 2 shader stages (which is why ES 3.0 adopted the GL 3.3 syntax).

It is easy to map the *concepts* learned in GL 3.3 to ES 2.0. So if you learn GL 3.3 for any of the various tools for doing so, you'll understand how to work in the ES 2.0 world. You'll need to figure out where the subset is, of course (ie: the things that GL 3.3 can do that ES 2.0 can't), but the concepts are the same.

Mapping GLSL's syntax, so that you can copy shaders from one to the other, is a bit harder. But really, all it takes is a few #defines in the right places. Also, GLSL 3.30 has a few ES compatibility features, like `highp` and so forth (which do nothing in desktop GLSL).

So you do gain something for ES 2.0 when learning from GL 3.3 instead of GL 2.1.

# Answer
> 8 votes
For games that do not require the larger changes to OpenGL exposed only in the newer versions, using only 3.x+ limits you to an nvidia 8 series and upwards (not sure on the other graphics vendors you'd want to look that up). So if you're not using 3.x+ features, you're just creating an artificial limit, stopping people with older, but plenty powerful, graphics cards from playing your game.

For this reason I'd highly recommend learning the forward compatible subset, and the newer versions, then picking the lowest version you can effectively push your game into. You can

I will also note in response to another question that OpenGL:ES 2.0 removes the fixed function pipeline, so it's more equivalent to 3.0 than 2.1.also always support different features per the supported gl version at runtime.

# Answer
> 4 votes
I would say it's save to learn OpenGL using your Red Book, just ignore those things that are deprecated in the newer versions (like glBegin(), glEnd() - use VBO's instead). Most of the functionality in the newer versions was already available before through extensions.

# Answer
> 4 votes
I mostly agree with thbusch. But I would not completely ignore the deprecated APIs: there is too much code still out there that uses them. I would pay them much less attention, though. No point, for example, in learning glBegin(), glEnd() thoroughly enough to write your own code using them. But you should recognize them when you see them, and have some idea of what they are doing.

It is still worth reading through the whole Red Book at least once, even if you don't build the sample code and do exercises covering features discontinued in OpenGL 3.x.

# Answer
> 3 votes
The short answer:

No. Learning OpenGL 2.1 is a good idea, even today, as long as you learn the "good parts".

The Long answer:

OpenGL can essentially be divided in two parts: "The good parts" and "Legacy functions".

Honestly, I don't see much benefit in learning legacy functions (the "fixed function"). However, a substantial portion of OpenGL 2.1 (the good parts) are still available today with relatively minor changes.

As such, learning some parts of OpenGL 2.1 can be beneficial. In particular, OpenGL ES 2 is very popular these days, and ES 2 is *mostly* (but not exactly) a subset of OpenGL 2.1. For 3D programming in smartphones, OpenGL ES 2 is a must.

So what's "good"? Essentially anything that is in OpenGL 3.x "core profile" (as opposed to "compatibility profile") and/or in OpenGL ES 2.

* Vertex and fragment Shaders: Learn them
* Textures: Still good.
* Matrixes: Knowing how they work is beneficial, but `glLoadIdentity` and that sort of functions are outdated and should be avoided
* Light: Knowing how light can be simulated in computer graphics is useful, but `glLightfv` and other fixed function light functions should be avoided.
* Array buffers: Good
* `glBegin`, `glVertex`, `glColor`, `glEnd`: Avoid them. Might be good for quick experimentation, but there are other better ways to do the same.
* Display lists: Avoid

The question where I originally posted this answer turned out to be a duplicate, so I'm reposting it here.

# Answer
> 1 votes
I don't believe it is a bad idea. A lot of GL concepts span across all versions of OpenGL and will still ultimately help you. I have a number of OpenGL books from 10 years ago that still help today. I would say that if you are new to OpenGL and there are some better books that are older, you will learn plenty and the code should still work. Most of OpenGL is backward compatible (I believe).

# Answer
> 1 votes
I advise that you learn the modern stuff first and just pretend the legacy stuff doesn't exist until you need it.

The out of date stuff can be useful in some cases for example if you are trying to program for something only supporting OpenGL 1.5 or older (can be found on older crappy netbooks and older MacOS systems), OpenGL ES 1.x (the older iPhones and Android before 1.6), or OpenGL SC (The Saftey Critical subset if you happen to be programming a display on jet fighter). Minecraft for example is built against OpenGL 1.3 so it can support really old hardware (but even that does have an 'advanced' option).

It can also be useful if you just want to get pixels on the screen and don't care about doing it the 'right' way.

It is useful to rely on some of the features that OpenGL does by default when learning such as setting up a -1.0 to 1.0 viewport and rendering without shaders. This allows you to learn without having to do everything in 1 go.

But other than that it should be skipped if possible.

I suggest you check out my answer's here and here for more in-depth information.

---
Tags: opengl
---


# Question
Title: android opengl-es spritesheet display number
Whats the best way to display numbers on android with opengl using a spritesheet?

I like to display the number "294" using the spritesheet: https://i.stack.imgur.com/wv5Zh.png

# Answer
> 0 votes
I found what I was looking for.

In my code then I just can write normal text and I can get the ascii codes of each character to calculate where its position on the generated spritesheet.

Here is a fragment of my used code where I get the acsii codes of my "text":

```
    byte[] ascii = new byte[0];
    try {
        ascii = text.getBytes("US-ASCII");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

```

---
Tags: android, opengl-es, spritesheet
---


title: First-Time GLSL Shadow Mapping Problems

text:
# Question
Title: First-Time GLSL Shadow Mapping Problems
I'm working on building out a 2.5D engine and having massive problems getting my shadows working. I'm at a point where I'm VERY close.

So, let's see a picture to see what I have:

As you can see above, the image has lighting -- but the shadow map is displaying incorrectly. The shadow map is shown in the bottom left hand side of the screen as a normal 2D texture, so we can see what it looks like at any given time.

If you notice, it appears that the shadows are generating backwards in the wrong direction -- I think. But the problem is a little more deep -- I'm just plotting the shadow onto the screen, which I know is wrong -- I'm ignoring the actual test to see if we NEED to show a shadow.

The incoming parameters all appear to be correct -- so there has to be something wrong with my shader code somewhere.

Here's what my code looks like:

VERTEX:

```
    uniform mat4 LightModelViewProjectionMatrix;
    varying vec3 Normal;            // The eye-space normal of the current vertex.
    varying vec4 LightCoordinate;   // The texture coordinate of the light of the current vertex.
    varying vec3 LightDirection;    // The eye-space direction of the light.

    void main()
    {
        Normal = normalize(gl_NormalMatrix * gl_Normal);
        LightDirection = normalize(gl_NormalMatrix * gl_LightSource[0].position.xyz);
        LightCoordinate = LightModelViewProjectionMatrix * gl_Vertex;
        LightCoordinate.xy = ( LightCoordinate.xy * 0.5 ) + 0.5;

        gl_Position = ftransform();

        gl_TexCoord[0] = gl_MultiTexCoord0;
    }

```

FRAGMENT:

```
    uniform sampler2D DiffuseMap;
    uniform sampler2D ShadowMap;

    varying vec3 Normal;            // The eye-space normal of the current vertex.
    varying vec4 LightCoordinate;   // The texture coordinate of the light of the current vertex.
    varying vec3 LightDirection;    // The eye-space direction of the light.

    void main()
    {
        vec4 Texel = texture2D(DiffuseMap, vec2(gl_TexCoord[0]));

        // Directional lighting

        //Build ambient lighting
        vec4 AmbientElement = gl_LightSource[0].ambient;

        //Build diffuse lighting
        float Lambert = max(dot(Normal, LightDirection), 0.0); //max(abs(dot(Normal, LightDirection)), 0.0);

        vec4 DiffuseElement = ( gl_LightSource[0].diffuse * Lambert );

        vec4 LightingColor = ( DiffuseElement + AmbientElement );

        LightingColor.r = min(LightingColor.r, 1.0);
        LightingColor.g = min(LightingColor.g, 1.0);
        LightingColor.b = min(LightingColor.b, 1.0);
        LightingColor.a = min(LightingColor.a, 1.0);

        LightingColor *= Texel;

        //Everything up to this point is PERFECT

        // Shadow mapping
        // ------------------------------
        vec4 ShadowCoordinate = LightCoordinate / LightCoordinate.w;

        float DistanceFromLight = texture2D( ShadowMap, ShadowCoordinate.st ).z;

        float DepthBias = 0.001;
        float ShadowFactor = 1.0;

        if( LightCoordinate.w > 0.0 )
        {
            ShadowFactor = DistanceFromLight < ( ShadowCoordinate.z + DepthBias ) ? 0.5 : 1.0;
        }

        LightingColor.rgb *= ShadowFactor;

        //gl_FragColor = LightingColor;

        //Yes, I know this is wrong, but the line above (gl_FragColor = LightingColor;) produces the wrong effect
        gl_FragColor = LightingColor * texture2D( ShadowMap, ShadowCoordinate.st );
    }

```

I wanted to make sure the coordinates were correct for the shadow map -- so that's why you see it applied to the image as it is below. But the depth for each point seems to be wrong -- the shadows SHOULD be opposite (look at how the image is -- the shaded areas from normal lighting are facing the opposite direction of the shadows).

Maybe my matrices are bad or something going in? They're isolated and appear to be correct -- nothing else is going in unusual. When I view from the light's view and get the MVP matrices for it, they're correct.

EDIT: Added an image so you can see what happens when I do the correct command at the end of the GLSL:

That's the image when the last line is just glFragColor = LightingColor;

Maybe someone has some idea of what I screwed up?

# Answer
> 1 votes
I think the error is somewhere here:

```
    float DistanceFromLight = texture2D( ShadowMap, ShadowCoordinate.st ).z;

```

A shadowmap does not produce the distance from a light but produces if the light can 'see' the area we are shading now. This is why the 'wrong' line works. It is fragmentColor * 0 if the light cant see the area and fragmentColor * 1 when it can.

---
Tags: c#, glsl, shadows, shadow-mapping
---


# Question
Title: How to detect collision in Unity3D without rigid bodies?
The target platform of my game is mobile devices therefore I try to develop it performance oriented. It will be a strategy game so I don't really need physics in it, consequently I did not add RigidBody to my object to avoid unnecessary computations. However according to the Box Collider reference page, the collison event cannot be triggered, unless one of the objects is a RigidBody. Is there a simple way to check collision between objects other than using RigidBodies? Or can it be that I'm overreacting this performance thing and the physics engine won't slow my game down?

# Answer
What you're doing sounds a lot like premature optimization to me. Did you try using the physics-engine and did it actually turn out to cause performance issues?

If you don't need the physics-simulation and just care for the collisions, why not use sensors (or "triggers", as they are called in Unity). For stationary objects, use a collider with the `Is Trigger` checkbox ticked. For moving objects do the same, but also add a rigidbody and set it to be kinematic.

That way you'll only get collisions out of the engine and no other simulation is necessary (use the `OnTrigger...` callbacks instead of the `OnCollision...` ones).

If you only need to detect collisions in 2D and the physics engine really turns out to cause performance issues (I highly doubt that, but I have no clue how your game looks like), then you could probably get away by representing your entities as circles and just do a very fast circle vs. circle test?
> 8 votes

---
Tags: collision-detection, physics, unity, performance, rigid-body-dynamics
---


title: Organize game classes C# XNA

text:
# Question
Title: Organize game classes C# XNA
I've just begun working on my game and I don't know how to organize my game in separate classes, because I need some variables/methods to be available to every class. I have a screen manager class and some screen classes which inherit a base screen class. But I can't access the screen manager's methods without making it a singleton, and I would like to avoid this solution. And I would like some game variables or methods to be available from any other class, but I can't do it without making them static. Let's say I have variable which stores the game difficulty throughout the game screens. If I would like to implement such a thing I would need to make it static in the Game1 class. Short story, I don't know how to make methods/variables global without making them static.

# Answer
> 1 votes
In case your reason for not making them static is that you see a possibility for needing to have several instances of them in the future then I think using singletons is an elegant solution.

Assuming that you might need to make several instances of these classes in the future you could store a reference to them in a wrapper class and send this as parameter in the constructor of those classes that need them. Alternatively you could send references as parameters to whatever methods need them (like draw or update or whatever). However having a lot of circular references might be a "bad smell" ie a warning sign that somthing needs to be redesigned...

# Answer
> 1 votes
There is often a temptation to make some parts of your application globally accessible, most commonly by making them static or by using the Singleton pattern or the Registry pattern. Do not follow that temptation.

Instead, try to reduce dependencies in your OO design. Then pass the objects explicitly to whatever other objects and methods need it.

This will not only lead to more elegant, maintainable, and extendable code. It is also a requirement for your code to be testable. Have a look at http://www.youtube.com/watch?v=-FRm3VPhseI for more information on this.

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


# Question
Title: Can't work out how matrix is applied to 2D vertices
I have a texture, some 2D vertices, and a matrix. The matrix is used to calculate the texture coordinates for each vertex, but the problem is that the matrix comes with absolutely no documentation and I'm having trouble working out how to calculate the texture coords correctly. I have it partially working.

The matrix is in this format:

```
sx rx tx
ry sy ty

```

Where `s` means "scale", `r` means "rotate", and `t` means "translate".

If the matrix doesn't contain any rotation (i.e. `ry = rx = 0`), I can correctly calculate the texture coordinates `u` and `v` like this:

```
u = x/sx - tx
v = y/sy - ty

```

But I can't figure out how to put `rx` and `ry` into the equation and get the correct results. Normal matrix multiplication involves multiplying and adding but this one involves dividing and subtracting, so I know I'm missing something but I don't know what it is.

Here is one of the matrices with rotation:

```
26.191574096679688   7.0180206298828125  1579
-7.0180206298828125  26.191574096679688  1879

```

Here is one of the matrices without rotation:

```
27.115478515625  0                1867
0                27.115478515625  800

```

# Answer
> 1 votes
As analyzed in the comments, the matrix was the inverse matrix. Inverting it gives the correct results. Here is the first example from the question:

```
scale = 27.115515  rot = -15 deg   trans = {1579, 1879}

26.191574096679688   7.0180206298828125  1579
-7.0180206298828125  26.191574096679688  1879

```

the inverse matrix to use is:

```
0.0356226228  -0.0095450654   -38.3129425048
0.0095450654   0.0356226228   -82.0065689086

```

---
Tags: 2d, mathematics, textures, matrix
---


# Question
Title: Impact of variable-length loops on GPU shaders
Its popular to render procedural content inside the GPU e.g. in the demoscene (drawing a single quad to fill the screen and letting the GPU compute the pixels).

Ray marching is popular:

This means the GPU is executing some unknown number of loop iterations per pixel (although you can have an upper bound like `maxIterations`).

How does having a variable-length loop affect shader performance?

Imagine the simple ray-marching psuedocode:

```
t = 0.f;
while(t < maxDist) {
    p = rayStart + rayDir * t;
    d = DistanceFunc(p);
    t += d;
    if(d < epsilon) {
       ... emit p
       return;
    }
}

```

How are the various mainstream GPU families (Nvidia, ATI, PowerVR, Mali, Intel, etc) affected? Vertex shaders, but particularly fragment shaders?

How can it be optimised?

# Answer
> 9 votes
There was a nice talk at GDC 2012 on GPU distance field ray-marching (and other topics): http://directtovideo.wordpress.com/2012/03/15/get-my-slides-from-gdc2012/

As far as performance goes, the latest (DX11-class) graphics cards execute shaders on SIMD units that run 32 (NVIDIA) or 64 (AMD) "threads" in lockstep. These groups are variously known as warps or wavefronts. For pixel shaders, each thread equals one pixel, so I would expect that the SIMD unit is processing something like an 8x4 (NVIDIA) or 8x8 (AMD) block of pixels together. Branching and flow control is done per-wavefront, so all the threads in a wavefront have to loop as many times as the deepest individual pixel within that wavefront. SIMD lane masks will turn off execution for the pixels that have finished already, but they still have to silently go along with the overall wavefront's flow control. This means, of course, that the system is much more efficient when the branching is coherent, so that threads in a wavefront tend to all branch the same way or have similar numbers of iterations.

In my experience, branch overhead is still pretty high even if all threads in the wavefront branch the same way. I've seen performance gains in some cases by unrolling the loop to amortize some of the branch overhead. However, it depends on how much work you're doing in each loop iteration, of course. If the loop body has enough "stuff" in it, unrolling won't be a win.

# Answer
> 2 votes
I suggest reading Running Code at a Teraflop: How GPU Shader Cores Work (pdf) from SIGGRAPH 2008: Beyond Programmable Shading. It talks about dynamic branching.

# Answer
> 0 votes
With regards to dynamic branching, one additional note (may be obvious, but still worth noting to some people): it can severely affect the performance of unrolled loops (you obviously cannot unroll a loop if there is a non-constant number of iterations).

# Answer
> -5 votes
int s=0;

now for(int k=1;k\<=n;k++){s+=k;} is the same like s=n\*(n+1)/2

so thats not true in general :D

---
Tags: opengl, glsl, opengl-es2, raytracing
---


# Question
Title: Why I'm getting the same result when deleting target?
In the following code we use target in the function:

```
moon.mouseEnabled = false;
sky0.addChild(moon);

addEventListener(MouseEvent.MOUSE_DOWN, onDrag, false, 0, true);
addEventListener(MouseEvent.MOUSE_UP, onDrop, false, 0, true);

function onDrag(evt:MouseEvent):void {
    evt.target.addChild(moon);
    evt.target.startDrag();
}

function onDrop(evt:MouseEvent):void {
    stopDrag();
}

```

But if I rewrite this code without `evt.target` it still work. So what is the difference, am I going to get errors later in the run time because I didn't put target? If not then why some use target a lot while it works without it.

```
function onDrag(evt:MouseEvent):void {
    addChild(moon);
    startDrag();
}

```

# Answer
The `target` property of an `Event` is the object that triggered the event! So if you mouse-down on a sprite on your stage, the "moon" object will get attached to the clicked sprite (because events bubble)!

So no, these examples don't do the same thing!

If you did this, then it would be the same thing:

```
evt.currentTarget.addChild(moon);

```

That is because `currentTarget` is always the object that had the event listener attached to. Generally, you should learn about scope. If your event handler function is on another object than the event listener was attached to, the two methods wouldn't do the same thing either.

Examples:

```
// this adds "moon" to the object that triggered the event
evt.target.addChild(moon);

// this adds "moon" to the object that had the event-listener added to it
evt.currentTarget.addChild(moon);

// this adds "moon" to "this" (current scope)
addChild(moon);

```

Sometimes these might be the same, unde other conditions they won't be the same.
> 1 votes

---
Tags: flash, actionscript-3, flash-cs5
---


title: 2d games unity vs Flash

text:
# Question
Title: 2d games unity vs Flash
do people find unity better than flash for 2d games while unity is 3d engine , or Flash still better because it's made for 2d games and flash can get the job done faster ,and now flash is better for ios/android 2d games . so what platform is the best for 2d games?

# Answer
> 5 votes
While Flash is still a thriving and vibrant platform to develop on, I would ditch it in favour of Unity, simply considering the unavailability of Flash on some mobile platforms that you may want to port to later.

There is a free package available in the Unity marketplace called Orthello, which greatly simplifies the process of making 2d games with Unity.

Finally, if you don't mind tackling new APIs altogether, you should take a look at haxenme and playN. While toolsets and editors to develop games with these APIs may not be as mature and developed as Unity and Flash, the scope of their cross platform reach is quite impressive, especially playN.

---
Tags: unity, flash, actionscript-3
---


# Question
Title: In a client server first person shooter how does the server keep track of each player's hit boxes?
Do all the clients send a transformation matrix for each of the hit boxes which make up the character?

# Answer
The server is running the game as well. And because it's transmitting your character's transform to every other client, it knows where you are. It can work out your character's hit boxes in exactly the same way that the client does.

Sending the hit boxes' location up to the server would be a recipe for exploits. There'd be an extremely trivial hack that simply makes you invulnerable, if that was the chosen mechanism (just send the server fake hit box information off in the middle of nowhere).
> 4 votes

---
Tags: client-server, first-person-shooter
---


# Question
Title: glGetFloatv – should it be avoided? Can it be replaced?
Platform is OpenGL ES 1.x. I am using glGetFloatv() to get MODELVIEW matrix. This allows me to compute points, where I need to draw a shadow effect. This is very handy, as I can forget about complexity of scene (its translations, rotations, etc.) – and by simple 3x1 matrix multiplication get the points.

But here it is stated that the call should be avoided. Is it correct recommendation? Can be glGetFloatv() omitted?

# Answer
> 4 votes
From a pure performance standpoint, the glGet\*() functions should generally be avoided where possible, as they can introduce unnecessary synchronization points inside the graphics driver. Basically, when you call glGet\*(), the driver may have to stall the CPU and wait for the GPU to finish any outstanding rendering operations, so that a correct and up-to-date value can be returned from glGet\*(). Even better, the performance penalty may vary from driver to driver, so what runs fine on one platform may be unacceptably slow on another.

The faster (but much less convenient) solution is to manually cache any necessary render state in the application code. For example, when you pass a MODELVIEW matrix to OpenGL, keep an extra copy around for yourself, so you don't need to call glGetFloatv() later to retrieve it.

That said, a single call to glGetFloatv() per frame probably isn't going to kill your performance. Just use these functions sparingly, be aware of their potential side effects, and profile often!

# Answer
> 3 votes
The fastest way to solve this would be to use modern, programmable pipeline OpenGL (2.0 ES), since you would typically be creating the model, view and projection matrices on the client side, and would thus never need to request them from the server.

I don't know if this is an option for you -- you may be supporting older devices.

# Answer
> 2 votes
This is going to be driver-dependent behaviour, so an absolute one-size-fits-all answer won't be possible. However, while the general rule is that any glGet call should be avoided, in certain cases they can be used without undue problems.

The reason for this is that not every glGet call will be dependent on the result of previous GPU-side operations, and that it's only those that are so dependent that will involve synchronization and pipeline stall/flush problems.

In the case of the current modelview matrix, this will - generally - always be calculated CPU-side by the driver, then sent to the GPU for actual use when a draw call occurs. So a glGetFloatv on the current modelview matrix won't actually need to round-trip to the GPU - it can just grab the copy of it that the driver is storing CPU-side and give that back to your program.

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


# Question
Title: Only apply Advanced Graphics on high FPS Dynamically
I wonder why not prevent lags by only appying advanced optional graphics stuff when the FPS are high at time. So The game could use simpler or even no shaders and skip decorative models some time.

**It there an approach of dynamically calculating more or less each frame for higher FPS yet?**

Is there a project using this approach yet?

# Answer
> 4 votes
You might find http://software.intel.com/en-us/articles/dynamic-resolution-rendering-article/ interesting.

Off the top of my head, there's a couple of things that will make automatically scaling somewhat complicated though:

* Measuring FPS isn't enough. At the very least you need to know if the bottleneck is the CPU or the GPU so you can make a good choice as to what changes to make to the detail settings. Even if you know the GPU is the bottleneck, the changes you want to make may depend on which part of the pipeline is the issue (memory bandwidth, poly count, pixel shaders, ROPs, etc).
* You probably don't want to oscillate between two levels of detail rapidly, so you need some damping in the system to keep it under control. However, damping the detail reduction will mean the player can still see low frame rates some of the time.

---
Tags: shaders, rendering, performance, level-of-detail
---


title: Reducing Memory Use on OpenGL ES

text:
# Question
Title: Reducing Memory Use on OpenGL ES
I'm using an opengl es based framework to create my game.I have an out of memory problem on some devices.I have 15 textures with a size 1024x1024(totally 10 mb).On memory they covers a lot of space.Some devices are exiting from game on loading time

I want to reduce memory use and how can i do that?Maybe a solution when i loading bitmaps into memory will be great.That's my texture class:Texture.java

# Answer
Texture compression it is. Here is a link explaining with example code snippet: https://stackoverflow.com/questions/9148795/android-opengl-texture-compression
> 0 votes

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


title: Enter text in XNA?

text:
# Question
Title: Enter text in XNA?
I'm looking for some help how to add text in XNA? I'm doing a game where I want the player to enter his or her name in the beginning. Is ther a simple way to do this? Help is preciated! Thanks!

# Answer
Had a post dedicated to this on my blog. I need to set my server back up :/

Anyways keyboard input in XNA is very poorly supported. Many including myself prefer to use a windows form event hook. This makes things very simple. Code below is very C#ish pseudocode off the top of my head so you may need to tweak it.

```
// Just draw this string
string text = "";

//Add an event for a character being added
InputSystem.CharEntered += delegate(Object o, CharacterEventArgs e) {
    if (Font.Characters.Contains(character)) {
        text += e.Character;
    } else if (e.Character == '\b' /* backspace */) {
        if (text.lenght > 0 ) { text = text.substring(0, text.lenght - 1); }
    }
};

```

Unfortunately the above only works on the pc, though it sounds like that is your development environmental.

If you will need additional GUI controls it might be worth downloading a 3rd party library such as Neoforce, XNAGui (Mine), or Nuclex.
> 2 votes

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


# Question
Title: 2D Rendering with OpenGL ES 2.0 on Android (matrices not working)
So I'm trying to render two moving quads, each at different locations. My shaders are as simple as possible (vertices are only transformed by the modelview-projection matrix, there's only one color).

Whenever I try and render something, I only end up with slivers of color! I've only done work with 3D rendering in OpenGL before so I'm having issues with 2D stuff.

Here's my basic rendering loop, simplified a bit (I'm using the Matrix manipulation methods provided by `android.opengl.Matrix` and `program` is a custom class I created that just calls `GLES20.glUniformMatrix4fv()`):

```
Matrix.orthoM(projection, 0, 0, windowWidth, 0, windowHeight, -1, 1);
program.setUniformMatrix4f("Projection", projection);

```

At this point, I render the quads (this is repeated for each quad):

```
Matrix.setIdentityM(modelview, 0);
Matrix.translateM(modelview, 0, quadX, quadY, 0);
program.setUniformMatrix4f("ModelView", modelview);
quad.render(); // calls glDrawArrays

```

and all I see is a sliver of the color each quad is! I'm at my wits end here, I've tried everything I can think of and I'm at the point where I'm screaming at my computer and tossing phones across the room. Anybody got any pointers? Am I using ortho wrong? I'm 100% sure I'm rendering everything at a Z value of 0. I tried using `frustumM` instead of `orthoM`, which made it so that I could see the quads but they would get totally skewed whenever they got moved, which makes sense if I correctly understand the way frustum works (it's more for 3D rendering, anyway).

If it makes any difference, I defined my viewport with

```
 GLES20.glViewport(0, 0, windowWidth, windowHeight);

```

Where `windowWidth` and `windowHeight` are the same values that are pased to orthoM

It might be worth noting that the `android.opengl.Matrix` methods take in an offset as the second parameter so that multiple matrices can be shoved into one array, so that'w what the first `0` is for

For reference, here's my vertex shader code:

```
uniform mat4 ModelView;
uniform mat4 Projection;

attribute vec4 vPosition;

void main() {
    mat4 mvp = Projection * ModelView;
    gl_Position = vPosition * mvp;
}

```

I tried swapping `Projection * ModelView` with `ModelView * Projection` but now I just get some really funky looking shapes...

# Answer
Well first of all

```
void main() {
    mat4 mvp = Projection * ModelView;
    gl_Position = vPosition * mvp;
}

```

is incorrect, doesn't matter that it looks less wrong.

There are two ways you can multiply vectors and matrices. If your vector is represented as a row and your matrix is constructed apropriately, then the order you're multiplying in should go as follows.

```
new_vector = vector * matrix;

```

However, if you represent the vector as a column and construct the matrices apropriately (i'm fairly sure that all of the built-in matrix functions do exactly this, it's kind of a standard), then your equation should go as follows.

```
new_vector = matrix * vector;

```

So, in the end, **if everything else was done correctly**, swapping your vertex shader main function to

```
void main() {
    mat4 mvp = Projection * ModelView;
    gl_Position = mvp * vPosition;
}

```

should fix the problem. If it doesn't fix the issue then we can go from here, but so far this is definetly incorrect and won't produce proper resaults even if everything else is correct.
> 4 votes

# Answer
I wasted quite some time trying to find out how to form a 2d projection matrix because I couldn't find an explanation what this matrix really is. I'm talking about the 4x4 matrix M that you pass to the veretex shader and use like

```
gl_Position = M * vPosition

```

Finally I figured out. Here is an explanation before I forget, and sory for my math language.

This matrix is an operator that makes a point in OpenGL coordinates from a point in model coordinates. OpenGL coordinates map an area on the screen that OpenGL controls into the \[-1,1\]x\[-1,1\] square. What I call the model coordinates are the coordinates that you think in when you build your scene. The third coordinate should be 0 since we are in 2d. These are projective coordinates. The fourth coordinate is such that Euclidian coordinates are obtained by dividing the first three projective coordinates by the fourth coordinate.

Assuming you don't need a rotation, here is how to build this matrix:

```
float[] mMVPMatrix = {a,0f,0f,0f,0f,b,0f,0f,0f,0f,-1f,0f,-a*cx,-b*xy,0f,zoom};

```

to show an 2\*a\*zoom x 2\*b\*zoom rectangle with a center in in cx,cy. Parameters a and b should be proportional to the dimmensions of the area that OpenGL controls (what you get as arguments in the onSurfaceChanged method). So forget about all these functions that build matrices while hiding information and don't use the expensive matrix multiplication for something as simple as this. It is much easier to debug something you understand.
> 1 votes

# Answer
Okay, I finally figured it out!

I changed

`Matrix.orthoM(projection, 0, 0, windowWidth, 0, windowHeight, -1, 1);`

to

```
float ratio = static_cast<float>(windowWidth) /
              static_cast<float>(windowHeight);
Matrix.orthoM(projection, 0, 0, ratio, 0, 1, -1, 1);

```

I then had to scale my projection matrix to make it a lot smaller with `Matrix.scaleM(projection, 0, 0.05f, 0.05f, 1.0f);`.

I then added an offset to the modelview translations to simulate a camera so that I could center on the action (so `Matrix.translateM(modelview, 0, quadX, quadY, 0);` was changed to `Matrix.translateM(modelview, 0, quadX + camX, quadY + camY, 0);`)

Thanks for the help, all!
> 0 votes

---
Tags: android, opengl-es, opengl-es2
---


# Question
Title: applying rotation and speed to move user
My player has a position (vec3), rotation (quaternion) and speed.

I have a fixed time step. At each tick, I work out from key-state etc what rotation and speed adjustments to make.

How do I now compute the new position?

And how, for the graphics which run at a different framerate, do I compute the the tweening for smooth movement?

# Answer
> 1 votes
(Rotation\*Vector3::Forward).Normalize() * move\_speed * dt

**dt** \- time elapsed since last frame **Vector3::Forward** \- direction to move relative to current rotation.

---
Tags: mathematics, geometry
---


# Question
Title: What happened to procedurally generated textures?
I recall some time ago that procedurally generated textures were becoming a big deal that a lot of people/companies were really interested in with some serious benefits (smaller deployments, potentially faster loading, higher quality, scalable textures, potentially cheaper to produce, etc.).

From what I can tell, the buzz is dead and no games on my radar are using them. What happened?

I was hoping I'd see procedural textures go the way that NaturalMotion's stuff has (slow but steady adoption).

# Answer
> 15 votes
Content creation tools for procedural texturing have been the biggest roadblock. Artist are very fast putting things together in Photoshop and the potential gains with procedural texturing haven't outweighed the increased content creation time.

Allegorithmic (http://www.allegorithmic.com/) has some interesting tools they've developed to try and make procedural options more user friendly. Haven't played with them enough to really comment on their usability though.

# Answer
> 4 votes
The loss of artistic control, and the size increase of storage options have make this a hard sell. That, plus you'd have to retrain artists, while you hired them for what they were good at -traditional texturing. Unless size or unique texturing is really really an issue, there is general little desire to go the procedural way.

# Answer
> 3 votes
Basically, the big guns aren't supporting it, so it's not being used much. There have been cool things (albeit a little old), like .kkrieger but the loading time on that (back in the day) was reaaaaally slow, since it had to generate all the textures at loading time.

We might see something or other in next generation engines (Unreal 4 etc) but I don't think that the gain vs development is big enough.

There are examples out there in the AAA world, for example Spore has procedurally generated textures and animation for the creatures you created.

# Answer
> 3 votes
Procedural texture suffers from the problem that an Art Director can not reliably point at the work of an Artist and say "please make that part a little more X." because the procedural shading system may not support X cheaply or at all.

For example, a brick shader may support clean brown brick, but may not support brick that was painted with an advertisement 80 years ago and graffiti 10 years ago. Or it may not support having one purple brick out of 1,000 brown bricks. In exactly that one spot, because that spot appeals to the Art Director's taste.

A real texture can support all these things of course, and in this sense a real texture is superior to a procedural texture.

The procedural texture exerts artistic control by virtue of its preference for certain use cases over others. A real texture exerts little such control.

GPU hardware, however, has a strong preference for proceduralism, because texture memory is so many cycles away from the ALU units that do the shading.

# Answer
> 1 votes
well it still seem like a great idea specialy for games. Since you could proceduraly generate textures on-fly so that world around the player would look more natural. No big data needed. It can be sure used to increase even the resolution

# Answer
> 0 votes
You have the typical *time memory trade off*. Well, like it or not, procedural generation trades CPU time for memory conservation. Actually as storage gets cheaper and people always want shorter loading times, the trend is to go the other way around - pregenerated or photographed assets consume memory in exchange for speed.

Does a jpg load faster than a procedurally generated version? Most likely, *yes*. If the jpg is 2MB and you load it once, why should you bother with procedural? At runtime, the texture takes the same amount of RAM anyway (uncompressed and loaded into GPU memory)

---
Tags: textures, procedural-generation
---


# Question
Title: if a desktop machine supports OpenGL 3.0+ I can assume that it supports OpenGL ES 2.0 too?
This isn't clear for me, if i use the drivers from the GPU manufacturer and they support OpenGL 3.0 and/or above, i can always make an OpenGL ES 2.0 application work?

# Answer
What do you mean by "make an OpenGL ES 2.0 application work?" If you mean, "Can I modify it to run on a desktop GL 3.x context with relatively minimal effort", then the answer is, "it depends". Obviously you'll need to change the version declaration of shaders, and your texture uploads may well be slower. ES 2.0 programs often use PVR compressed textures, which generally are not supported on desktop GL hardware.

A bigger problem is with binary shaders. Even if an implementation supports the ES2\_compatibility extension, there's no guarantee that the implementation will support the specific binary shader formats that the program requires. So your program should be using text shaders.

Also, don't make a core or forward-compatible 3.x context; use the compatibility profile instead.

But if you have some executable that uses ES 2.0, you cannot simply run it on a desktop GL 3.x computer and expect it to work.
> 1 votes

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


# Question
Title: How to Use Images Instead Of Drawing Primitives
I want to build backgammon game. I have successfully built the board using primitives such as lines, triangles and circles. I'm curious whether it's possible to draw the board using images which will make the board look much nicer. Is it possible to have images of triangle and then to put on top of it tiles? How is this achieved?

For example, let's say I have 100x80 image of a triangle and a 100x20 tile image of tile. What theoretically needs to be done in order for the tile image to be shown on top of the triangle image? (each have different colors, and the width of both is the same).

P.S I'm currently programming this in Objective C for the iOS, but I don't think it's important, as this is more of a general question.

Thanks.

# Answer
The answer is that it's simply a matter of the pictures you use. It turns out that .png files have no background which means you can create layers. I created such files using Pixelmator and here is a quick tutorial on the subject: http://www.pixelmator.com/tutorials/quickly-remove-unwanted-background/

I'm developing for the iphone so if anyone is interested, I used UIImageView and added subview to the master UIImageView and it works very nicely.
> 0 votes

---
Tags: 2d, tiles
---


# Question
Title: What's the difference between Tiled maps' various tilewidth/tileheight values?
I'm parsing Tiled maps (.tmx) for my game, and even after reading the documentation, I don't understand what the difference is between the attributes `tilewidth` and `tileheight` of the `map` element versus the attributes of the same name in the `tileset` element. They are often the same; an example where they differ is the map \_isometric\_grass\_and\_water.tmx\_ from Tiled's *examples* folder:

```
<map version="1.0" orientation="isometric" width="25" height="25" tilewidth="64" tileheight="32">
<tileset firstgid="1" name="isometric_grass_and_water" tilewidth="64" tileheight="64">

```

Also, there's this child element of `tileset` whose purpose I don't understand:

```
    <tileoffset x="0" y="16"/>

```

Do those distinct values exist for isometric maps? If anyone could shed some light on this, my hurty brain'd be very thankful.

# Answer
> 1 votes
The map is a grid, where the spacing of the grid is specified as the map.tilewidth and map.tileheight.

Now tiles can be bigger (also smalller, but that doesn't make much sense) than the grid spacing. If the map has a tilesize of 64x64 for example there could be tiles with a size of 128x128 or 64x128. This is useful when you want to overlap the tiles. If no offset is specified these will be drawn from the bottom left corner, this is fine for rectangular tilemaps, but for isometric tiles you are often required to apply a offset.

---
Tags: tiles, tilemap
---


title: moving in the wrong direction

text:
# Question
Title: moving in the wrong direction
**Solution**:

To move a unit forward:

```
forward = Quaternion(0,0,0,1)
rotation.normalize() # ocassionally
...
pos += ((rotation * forward) * rotation.conjugated()).xyz().normalized() * speed

```

I think the trouble stemmed from how the Euclid math library was doing Quaternion\*Vector3 multiplication, although I can't see it.

---

I have a vec3 position, a quaternion for rotation and a speed.

I compute the player position like this:

```
rot *= Quaternion().rotate_euler(0.,roll_speed,pitch_speed)
rot.normalize()
pos += rot.conjugated() * Vector3(0.,0.,-speed)

```

However, printing the pos to console, I can see that I only ever seem to travel on the x-axis.

When I draw the scene using the `rot` quaternion to rotate my camera, it shows a proper orientation.

What am I doing wrong?

Here's an example:

* You start off with rotation being an identity quaternion: w=1,x=0,y=0,z=0
* You move forward; the code correctly decrements the Z
* You then pitch right over to face the other way; if you spin only 175deg it'll go in right direction; you have to spin past 180deg. It doesn't matter which direction you spin in, up or down, though
* Your quaternion can then be something like: w=0.1,x=0.1,y=0,z=0
* And moving forward, you actually move backward?!

(I am using the euclid Python module, but its the same as every other conjulate)

**The code** can be tried online at http://williame.github.com/ludum\_dare\_24\_evolution/ The only key that adjusts the speed is W and S. The arrow keys only adjust the pitch/roll.

At first you can fly ok, but after a bit of weaving around you end up getting sucked towards one of the sides. The code is https://github.com/williame/ludum\_dare\_24\_evolution/blob/cbacf61a7159d2c83a2187af5f2015b2dde28687/tiny1web.py#L102

# Answer
The rotation of the direction-vector using the quaternion is wrong, it must be:

```
    Pout = q * Pin * conj(q)

    Pin  -> input vector
    q    -> quaternion
    Pout -> rotated output vector

```

Details can be found here: Transformations using Quaternions

Code correction:

```
    pos += rot * Vector3(0.,0.,-speed) * rot.conjugated()

```

**Note:** If the movement is still wrong, then `roll_speed` and `pitch_speed` are most likely absolute values, rather than the relative orientation change in this frame, then the first line would have to be:

```
    rot = Quaternion().rotate_euler(0.,roll_speed,pitch_speed)

```
> 2 votes

---
Tags: mathematics, geometry
---


# Question
Title: How to reconcile depth ordering with minimal shader context changes?
We generally want to minimise shader-program switches (`glUseProgram` and all associated context changes) for the sake of performance. AFAIK it is not uncommon to render by shader program, i.e. group draw calls of all mesh instances that use the same set of shaders - or vertex shader at least (i.e. that have the same set of vertex attributes), for this reason.

How then do we go about doing both depth ordering and shader program changes, quickly? Because it seems to me one either orders primarily by program (thus minimal program context changes), or primarily by depth (frequent context changes), and that they're mutually exclusive in terms of maximising performance.

PS. In my current work I'm not using the hardware Z-buffer, instead I'm using the painter's algorithm prior to making all draw calls... If this affects the answer to the question at all, I'd be happy to hear solutions for both sorts of depth-ordering.

# Answer
> 2 votes
If you're using the painter's algorithm, you have to sort back-to-front and there's no way around it if you want accurate sorting - and even that sorting isn't going to be accurate if there's any chance of objects overlapping, unless your game is 2D and you know that each object has exactly one depth value. You could only sort subsections by shader program (or texture, or any other property) if your objects shared the same depth value, or if you could guarantee that all the objects you are rendering are in the same logical depth layer and do not occlude anything else.

What was your rationale behind foregoing Z-buffer use? At first glance it looks like you could have it both ways with a Z-buffer, but I don't know your specific situation. In my experience, the performance gain of consolidating render state changes and texture loads outweighs the minimal performance impact of a Z-buffer.

# Answer
> 6 votes
In general, unless it's a 2D game, people *don't use* the painter's algorithm. There's just no point to it; depth buffer is not only cheap, but *faster* than what you're trying to do. Yes, really.

With early depth tests, fragments can be culled before having the fragment shader even execute. This saves time with scenes that have heavy overdraw. With coarse front-to-back sorting, there's just no reason to not use a depth buffer.

Thus, once you commit to the painter's algoithm, you've already given up quite a bit of performance. What you might save from optimized `glUseProgram` calls is irrelevant next to what you lose from the *massive overdraw* your scenes will have.

Most important of all, until you have profiling data that suggest your number of `glUseProgram` calls is too great, you shouldn't much bother. Or if you are going to bother, make sure that your sorting criteria is something you can change, so that you can adjust what you sort based on.

---
Tags: opengl, 3d, directx
---


# Question
Title: How to handle 3D collisions using raycasting (with a reflection vector?)
I'm making a game using THREE.JS, and I want my character to walk on the terrain, and collide with static 3D objects (=AABB boxes) that are on that terrain.

The problem is: THREE.JS has only a raycasting class which can be used for collisions.

I figured it would be possible if I casted 8 rays from my character to the points of an imaginary cube around the character (simulating an AABB box). I realize a sphere would be much better, but I wouldn't know how to do that using rays.

```
var rayDirections = [];
rayDirections.push(new THREE.Vector3(1, 1, 1));
rayDirections.push(new THREE.Vector3(-1, 1, 1));
rayDirections.push(new THREE.Vector3(1, 1, -1));
rayDirections.push(new THREE.Vector3(-1, 1, -1));
rayDirections.push(new THREE.Vector3(1, -1, 1));
rayDirections.push(new THREE.Vector3(-1, -1, 1));
rayDirections.push(new THREE.Vector3(1, -1, -1));
rayDirections.push(new THREE.Vector3(-1, -1, -1));

```

Then, I simply test the rays against the terrain and possible 3D meshes on the terrain, and check if the ray distance from one of the raycasts is smaller than the AABB box size. This would mean a collision occured.

Rays around the character http://www.ironbane.com/images/colbox.png.

So far so good! I cast a ray from the character's position with every rayDirection and check if one collides with the meshes array (which contains the terrain and other 3D objects on the terrain)

Once I have a collision, **what to do now?** Should I calculate a reflection vector? If for instance I simply walk on a flat terrain, the four rays at the bottom should trigger a collision. How do I use this reflection vector in my situation?

```
for(var r in rayDirections) {
    // this.position refers to the character's current position
    var ray = new THREE.Ray( this.position, rayDirections[r] );

    for (var m in meshes) {
        var intersects = ray.intersectObject( meshes[m] );

        if ( intersects.length > 0 ) {
            // Normal vector of the meshes' face we hit
            var nV = intersects[0].face.normal;

            // Velocity vector (of the character)
            var vV = this.velocity.clone();

            // And calculate the reflection vector
            var rV = n.multiplyScalar(-2 * vV.dot(nV)).addSelf(vV);;

            // ... Now what?
        }
    }
}

```

# Answer
> 1 votes
What shape are you modelling your character as? An axis-aligned cylinder? (which is typical)

Personally, I'd just move the character without worrying about collisions, then check if the character is "inside" any obstacle, and move him to the nearest non-intersecting location. This is pretty trivial in most cases.

In the case of an AABB and a cylindrical character, it's only necessary to check a collision with certain points (depending on how accurate you want it to be and what kind of obstacles you'll have). Maybe you just need to check:

* If any corner of an AABB obstacle is inside the player (if so, move player to nearest non-intersecting point using linear interpolation)
* If any axis-aligned edge of the cylinder is inside any AABB obstacle

In the case of the player standing on a platform, he is constantly falling slightly, and constantly being moved back to the top of the platform (the player doesn't notice this, as no rendering happens between these two events)

Just write down your use-cases. Example:

1. Player does not fall through a platform he's standing on
2. Player cannot walk through a wall orthogonally (at right-angles)
3. Player approaching wall non-orthogonally, slides along it as they collide (e.g. if at 45 deg to wall, you'll still move along the wall at a lower speed than you're trying to go)
4. Player cannot pass under a suspended obstacle which is too low for his head
5. Player cannot become partially embedded in the corner of an obstacle (e.g. if approaching the corner off-centre)

I think you don't need to worry about raycasting. Just moving the player out of overlapping objects is sufficient.

This technique also works quite well for moving platforms (provided they don't move *too* fast), especially if you use Verlet integration.

# Answer
> 1 votes
Collision detection is just the very first part of a pretty complicated problem. You might find it's much easier to integrate functionality from an actual physics engine. I haven't used this one, but anything based on Box2D has a good chance of being pretty good: http://box2d-js.sourceforge.net/

---
Tags: collision-detection, javascript, raycasting, three.js
---


# Question
Title: Does using the XNA Content Pipline eliminate the overhead caused by file IO when working with a large number of files?
I'm working on a game in XNA with my goal being that it is fairly data driven so that I can easily tweak the system without having to update code. The research I've done shows that using XML files combined with the content pipeline should provide me with what I need to accomplish this.

That being said, being a developer that really has only been exposed to object oriented programming I have this "one class per file" mindset that I really like because it makes finding and updating what I want to change very easy. This leads me down a path of wanting to set up a system where instead of a large, heavily nested XML file that defines everything (like the web.config files I am used to), I want to go with a folder structure with files that define individual objects - or at the very least something in between. At this point in time I'm not entirely sure how many files I could end up having but I believe it could escalate to a point where it could cause a performance problem if done wrong and if I discover a performance problem because of it, redesign and consolidation of it all could be a big enough chore that I definitely want to try my best to make the right decision up front.

Usually I would see the above mentioned approach being a big performance hog because of the large amount of file IO that would have to be done when loading up the game. Based on my experience with images in the content pipeline, I am assuming that XML files are also combined into a single XNB file when compiled. From this my questions become:

* If it is true that all XML files become a single XNB file should I still expect a notable performance loss when loading the data from these "files" or has that overhead disappeared since its all within a single XNB file?

If yes I am sure there tools out there that can make managing / updating a single and very large XML file more manageable which I will begin researching and am open to suggestions on.

# Answer
Resources like shaders, textures, fonts, etc. Each live individual XNB files after being processed by the content pipeline.

XML files may be used as an index of resources and configuration data, but I'm having a hard time imagining a situation where it would be beneficial to include the XNB contents within the XML.

Given that, XML files are typically pretty small. I doubt you'll see any performance degradation from that.

If your concern is about loading large numbers of different files from disk(platform?) then remember that the won't be loaded until you call Content.Load. If your app is structured correctly, I doubt you'll be loading thousands of items at the same time. They should be loaded just before their first use when possible.
> 3 votes

# Answer
XML files do not get merged into a single XNB, unless you have a custom content processor that you've specifically configured to do so (you'd know if you had, it's a non trivial process).

I recommend going with whatever file structure helps you develop most quickly, and in the end if you have a tremendous number of files you may want to consolidate them into a single data file that is read by a custom content manager. This generally isn't necessary on Windows, since the file system there is pretty good at dealing with quite a few files, but the XBox does noticeably suffer when there are lots of files in a folder. Here's a thread on that topic: Pack of resources in one big file with XNA

A proper setup will take care of all this automatically during a standard build.
> 3 votes

---
Tags: xna, performance, xml, xna-content-pipeline
---


# Question
Title: Implicity of "Objects" in component based design
For a while, I have mostly been using "standard OOP" (inheritance heavy, tree structure, etc.) styled designs for my Game Development needs. However, for my current project I am trying to shift over to a component-based design (This is all at a hobby level, so time/money/productivity speed are not important ATM.) However, while researching into component based designs, I am confused about how the concept of "objects" are implement.

From what I can understand, there are 2 schools of thought in regards to the relationship between components and objects. One paradigm seems to implement objects as classes that simply serve as "containers" for holding components that interact with another. However another paradigm seems to get rid of the concept of an object itself, with objects only existing implicitly. (however, I fail to understand how synchronization issues don't appear. If anybody could also explain this, that would be very helpful.)

Regarding these 2 ideals, are there any major benefits (performance, usability, etc.) to choosing one paradigm over another?

# Answer
*Note that I'm not sure how objective this answer can be. I feel it's objective enough for SE, but then few people think their opinion on a subjective matter is anything less than absolutely correct.* :)

*Note also that the terms "component-based design" and "entity system" are not clearly defined in the industry, so it's quite possible that different people have different ideas of what these terms mean.*

The second system you mention is called an "entity system" these days. The idea is that you only have components, and they all share some kind of of shared identifier to link them together. Even systems that use a "container object" often work this way, with the object simply being a distinct concept from a component and allows some extra features that the components do not.

Some people also use the entity system moniker to differentiate between between "logic components" and "data components". The difference there is whether your component types have any methods that implement logic or if they just contain data.

Personally, I find the idea of an "object-free" entity system to be completely broken, and to my knowledge it has never been used for a "real" game (certainly nothing large and complex). There are all kinds of pieces of data that are not related to any particular component but rather are shared by all components (i.e. they're properties of the game object itself).

However, I also find strong advantages to preferring data components over logic components. Data components allow a lot more flexibility, better performance, etc. For instance, your PhysicsComponent should not be responsible for moving the object. There should be a PhysicsSystem that has an efficient collection of all PhysicsComponents and which updates all of them together in one pass. This is more efficient, reduces errors in the simulation, etc. The same goes for graphics (you absolutely DO NOT want to have each object drawing itself, that breaks a lot of opportunities for batching and instancing and is horrifically inefficient on modern hardware!) and so on. Your components should contain the data the systems need, and otherwise just serve as a way to register the object with the appropriate systems.

That said, again there are problems with an academic puritanical approach. There always, always are. If you outright ban logic components, you're going to hate life when it comes time to implement actual game logic. Game logic is hairy, dirty, and hardly ever able to be fit into a clean universal architecture. You're going to want to have a game object that behaves in some special way when some event happens. Which is easier: hardcoding all the possible behaviors into a BehaviorSystem and selecting them based on some property of the object, or just attaching a component to the objects that need a particular behavior? Even most entity systems allow behavior components, they just lie and call them something else; like a script attached via a ScriptComponent, in which the script is really just another component (but without all the support and integration that real components could potentially get, and without the ability to attach multiple independent scripts easily).

There are hence some good ideas in the entity component systems being bandied about, but you're best off taking those ideas and applying them to a foundation you're more comfortable with. The same goes for inheritance: component based design says you should *avoid* inheritance with your objects and favor aggregation, but no experienced developer worth working with is going to tell you that it's sensible to outright *ban* inheritance in a system. There are just far too many places that inheritance makes things easier, cleaner, and faster. The trick is to use it when it makes sense and to use something else when it does not make sense. Learning those situations comes with experience, not reading blogs or forums or StackExchange answers, and your best bet is to just program, program, and program some more. :)

**Some reasons you might want to consider a "traditional" component based OOP design:**

1. If you want to know if a particular object id exists, you don't want to have to search all component pools for that id.
2. If you want to make an object with delayed deletion (you *always* want delayed deletion) you don't want to have to go and mark every component (and then open up a race condition where some system might try to add a new component to a "deleted" object which then would not receive that deletion flag).
3. If you want to register your object with a live game editor, including metadata about creation time, name, etc., you need a place to store all that. This could just be an extra component, but then you need to have special code to always enforce that this component is created for every game object, and to ensure it is never deleted unless the whole object is. Much easier to just have this be part of an explicit game object instance.
4. You indeed may want a collection of all components for a single object stored somewhere for various reasons, and a real game object instance is an ideal place for that.
5. If you plan on having high-performance networking, you're going to need a centralized system for communicating changes between components, linking updates (you're likely going to have a single highly-compressed "packet" type to update position and velocity, despite those being properties of two different components), and so on. While you will most certainly have a Networking component, if you don't have a game object class you're just going to end up duplicating all that functionality into the Networking component anyway.
6. Message broadcasting, while not necessarily the best idea in the first place, works a lot better with a central object to manage where to broadcast messages to. Otherwise you are again stuck trying to deliver the message to every possible component pool for a particular object, even though maybe only 5% of the components are used by that particular game object.
7. Sometimes you have behavior that works in a composable manner, and it's just way easier to use a component system to attach those logic objects to a game object, rather than trying to shoehorn everything into a separate system.

**Some reasons you might consider a pure entity system design:**

1. Works better with databases and distributed systems where centralization is a huge bottleneck. Likewise it also can help with some threaded engine models (though not the correct models, in my experience) since it removes contention on a central object.
2. Simplifies decisions of when and where to put logic vs data, and ensures that your design is clean and understandable. Traditional systems allow an equal amount of cleanliness but requires discipline to avoid piling on hacks and inappropriate object coupling.
3. More obvious on how to implement in a language that does not natively support traditional OOP, such as JavaScript, while still being easy to implement in native OO languages like Java, C#, or C++. Fits better with a purely functional design as well as with purely procedural designs.
4. Enforces a data-driven approach to object design, which is generally a very good thing.

Obviously I'm a bit biased towards component-based design rather than entity systems, but that bias comes from actually having built fairly complex component-based games and engines and having solved problems that I can't solve as easily or naturally in a pure entity system.

**tl;dr** -- Entity systems take many existing good practices from component-based design and throw away everything else (good or bad) and replace them with a purely data-driven approach to game object design. Understand the problems entity systems try to solve and apply those lessons to traditional OO component-based design. Real-life hybrid systems that apply different solutions to different problems are usually superior to academic systems that attempt to use a single design pattern to solve every problem.
> 3 votes

---
Tags: component-based, oop
---


# Question
Title: Introducing generic commands in text-based interactive fiction game
Writing a compact text-adventure engine I was thinking about possible commands a player could use. For each location i have special commands described in the text but what about generic commands like

* examine
* open / close
* trigger
* ...

So here are my questions concerning this:

1. Is there anywhere a good enumeration of commands which should be mandatory? If no, what commands would you expect in such game?
2. Concerning usability, should I suppose that the player knows the commands so he can try to use them from the beginning or should I implement tutorial-like explanations which unlock the usage of those commands?

# Answer
You can find a good list of commands in many places in the IF community. You could try downloading Inform 7, TADS 3, ADRIFT, QUEST, and so on and looking at their default commands. There's a less comprehensive list in this guide, http://inform7.com/if/anth/IntroductionToIF.pdf .

Your second question is much less clear-cut. Some IF games successfully implement an optional tutorial mode for beginners. Just make sure an experienced player can turn these hints off.
> 3 votes

# Answer
Concerning your second question: Definitely add a tutorial!

Assume that none of your players has ever touched an IF game before, then make sure that they can still play yours. In my opinion this is particularly important for command line IF games because of their unintuitive user interface. If you don't add a tutorial, your audience will be limited to players with prior IF experience, and -- if you're lucky -- a couple of nerds with a high threshold for frustration.

Here are two videos that provide good insights on how to design good tutorials: http://extra-credits.net/?s=tutorial
> 0 votes

---
Tags: rpg, text-based, user-experience, interactive-fiction
---


title: Before multiplayer match setup

text:
# Question
Title: Before multiplayer match setup
I am implementing a before-match setup in following way:

1. Users request a multiplayer match (click "*New Game*" button or similar)
2. After enough users request the match – connection is established
3. Users are then moved into **Select level** view
4. On that view, there is "*Become Master*" button, which an user can use to become Master
5. The Master has ability to select level to play
6. After clicking "*Become Master*" – the users vote – simple popup appears "Accept User X becoming Master?"
7. If \> 50% agrees, user X becomes master.
8. Master then selects level he wants. After 10 seconds, game starts – all users are moved to **In-game view**, to play selected level.

**Question:** I am wondering if I am not doing this too complicated? Shouldn't I randomly choose the master, or somehow make selection mechanism simpler?

# Answer
There are several potential problems with your protocol: First, if several players want to become Master, there can be several polls, which might be annoying for some players. Second, and more important, if no player gets \>50% of the votes, your protocol does not yield a Master at all.

I would suggest to give your players a couple of seconds to decide whether or not they want to be the Master. Then let them vote for any of the contenders. The player with the most votes becomes the Master. If there is a tie, I would recommend to choose a player randomly, but you can also have another poll as a tie-breaker.
> 1 votes

# Answer
**Why not just have users vote on the level or other selectable options instead of the master?**

Many times it might be hard to get over 50% of the players to vote on anything; so there may never be a master in most games.

**What you should have is the ability to vote on a level and the level or options with the most votes will be played regardless of what percentage of votes have been cast.**

If there is a tie then choose randomly between the tied options.
> 4 votes

---
Tags: multiplayer, user-experience, matchmaking
---


title: Limit rotation heading by cone/angle

text:
# Question
Title: Limit rotation heading by cone/angle
What is a fast way of limiting the heading vector to a certain angle so that it turns in greater distance relative to the limit.

A smaller cone/angle should make the object take a far bigger curve to traverse to reach its goal where a larger cone/angel allows the object to rotate faster in the direction of its goal.

If there are some vector tricks i'll be glad to know them!

# Answer
This approach is familiar with the people in CNC machining: the CNC bit is carving a path on a metal surface. Characteristic to this process are some terms: feedrate - this is actually the speed at which the metal is "plowed" by the rotating head of the tool and direction of advance - this is your vector indicating the direction the bit will advance from its current position.

There are some common-sense limitations: the faster the metal is eaten away, the less the change in the advance direction. Again, imagine a car through a curve. If it's going slowly, it can negotiate quite tight corners, while when it's going fast, it cannot without straying from that curve and leaving the road which spells disaster.

Your problem is 100% depicting these scenarios. The mathematical skills you need involve the cross product (rotate the current advance direction to allow the object to home in on a target), axis-angle rotation and a transfer function (which is nothing more than a function that decreases with the speed of the object and tells how big your cone's angle is - just like a tolerance).

Some fast details:

* the discrete case involves a *currentPosition*, a *targetPosition*, a *speed* and a *maxTurnAngle* plus the *currentDir* (current direction of advance)
* at each step you compute the angle between *crrentDir* and *targetPosition* \- *currentPosition*. This angle tells you by how much you should rotate *currentDir* to make the object go toward the target. Now you know your *maxTurnAngle* and you would like an estimate for how much you can turn. The idea is to safely divide the *maxTurnAngle* by an amount proportional to your speed. Then rotate *currentDir* against the cross product of *currentDir* and *tgt - pos* by that scaled angle. That should give you an idea.
> 1 votes

---
Tags: mathematics, vector, movement
---


# Question
Title: Entity component system - where did attributes and behaviors come from?
I recently spent quite some time understanding and building a component-based system. I got stuck on a few problems and after searching for quite some time ran across this answer which is talking about behaviours and attributes.

From what I understand, attributes are an entity's data; I thought that's what the component is? And what are behaviours? Is it another term for *Entity Processing System*?

# Answer
Attributes and behaviors are just a different way of talking about components and systems.

* Attributes == Components
* Behaviors == Systems

They can be the exact same at the code level, it's just a different way to talk about them that might help people better understand them.
> 5 votes

---
Tags: entity-system
---


# Question
Title: Where can I find the library for org.newdawn.slick.opengl.Texture
I started making a game in Java, and someone on stackoverflow recommended me LWJGL. I found some examples, and they worked. Later I wanted to test sprites and every example that I found that loads images imports `org.newdawn.slick.opengl.Texture`. I can't find that library anywhere. Is there a better alternative, or where can I find this one?

# Answer
The example you were looking at uses Slick2D along with LWJGL. You can download the library here or the full distribution here. Slick2D is used primarily for 2D games, however, even in 3D games it is widely used for loading textures.
> 7 votes

---
Tags: java, lwjgl
---


# Question
Title: Java applet game design no keyboard focus
`THIS IS PROBABLY THE WRONG PLACE. POSTED IT``HERE (STACKOVERFLOW)`

I'm making an applet game and it is rendering, the game loop is running, the animations are updating, but the keyboard input is not working. Here's an SSCCE.

```
public class Game extends JApplet implements Runnable {

    public void init(){
        // Initialize the game when called by browser
        setFocusable(true);
        requestFocus();
        requestFocusInWindow();  // Always returning false
        GInput.install(this);    // Install the input manager for this class
        new Thread(this).start();
    }

    public void run(){
        startGameLoop();
    }

}

```

And Here's the GInput class.

```
public class GInput implements KeyListener {

    public static void install(Component c){
        new GInput(c);
    }

    public GInput(Component c){
        c.addKeyListener(this);
    }

    public void keyPressed(KeyEvent e){
        System.out.println("A key has been pressed");
    }

    ......

}

```

This is my GInput class. When run as an applet, it doesn't work and when I add the Game class to a frame, it works properly.

Thanks

# Answer
Try overriding `Component.processKeyEvent` in the Applet class. Also you may need to call `enableEvents(AWTEvent.KEY_EVENT_MASK);` in the initialization. I have not tested this with Applets, but generally this has been the most robust way of handling keyboard in Java that I am aware of.
> 1 votes

# Answer
Specify what key should be pressed to print your message.

```
public void keyPressed(KeyEvent e){
    int key = e.getKeyCode();

    if(key == KeyEvent.VK_A)
       System.out.println("A key has been pressed");
}

```
> 0 votes

---
Tags: java, architecture, input
---


title: How to get started with a game engine?

text:
# Question
Title: How to get started with a game engine?
I'm a 3rd year Computer Science student and I would like to get started with building a game engine or at least tinkering with making one. I am curious if there are any good resources to use to get started. I get the idea behind different pieces in the engine, but I'm not really sure about how they fit together. Is there anything out there to help teach me the skeleton of a game engine? So far I've been playing with the idea of a game engine that uses modules built in a circular linked list so that each can do it's computing and then pass move to the next piece of the engine to work.

# Answer
> 1 votes
To be honest I think the best resource here will be to simply pull apart some existing games and engine to see how they work. There is nothing like seeing first hand how a running production engine work. Its also a hell of a lot more fun than reading a book cover to cover.

You could start with Unity - I personally really love its high-level component-based game development design. It is arguably regarded as one of the best designed engines in the industry in terms of getting your game from zero to market. The core rendering components are hidden from you in this closed source engine however, so you won't learn much where the hardcore rendering is concerned.

For the really core components of an engine I would go take a good look at Orge. Download the source and build it. The examples that come with Ogre will provide you with the entire end-to-end process, and there is some really cutting edge stuff going on in Ogre development right now too (Procedural terrains, DX11 support, etc). Almost all the key components are represented in Ogre and its scene managers are actually pretty well designed.

# Answer
> 1 votes
I found this website to be quite handy if you're thinking of heading down the directx path: http://rastertek.com/tutindex.html They seem to have a well organised structure and, while they're mainly working on the rendering side of things, it might be worth checking out?

Also, "Frank D. Luna" has a really good range of books for DirectX programming (new directx 11 book published recently) which heads more into the game-engine side of things.

---
Tags: education
---


# Question
Title: Should I distribute shaders in a compiled form or in plain text?
Having an application that uses shaders that have been wrote in GLSL, what is the best strategy for the distribution in the real world and for the desktop and mobile?

I'm aiming to distribute this in a binary form or as plain serialized text, i would like a good suggestion on this.

# Answer
> 15 votes
The main rationale for using binary shaders is if compiling the text shaders is too big of a workload for your target device. Binary GLSL shaders don't have a standardized format, so you'd need different ones for each GPU/driver you plan to support. I'd recommend you distribute the shaders in source form and then on the first run cache them into binary form and subsequently load from there. Then again I'd first test if you really have a performance bottleneck there to justify using the binaries at all.

One thing to consider is also an offline text shader optimizer that can have a great effect with crappy mobile shader compilers.

---
Tags: opengl, shaders, opengl-es, glsl
---


title: Problem with sounds in XNA

text:
# Question
Title: Problem with sounds in XNA
I get this error when I'm trying to play a sound in XNA: Error 1 Audio file cash-register.wav contains non-PCM data. What is PCM data?

# Answer
> 2 votes
PCM stands for Pulse-Code-Modulation and is a way to digitally represent analogue (sound) data. The problem you're having is that your WAV file contains invalid data. Did you just rename a .mp3 file to .wav? Or did you use a program to convert the data? If so you should check the converter settings and make sure that only the sound data is converted and that all meta-data is discarded.

---
Tags: xna
---


# Question
Title: Inputting cheat codes - hidden keyboard input
Okay, here's what I want to do - when the player is at the main menu, I want them to be able to type in cheat codes. That's the only place I want it to work. I don't want to give them a text box to type into. Rather, I want them to simply type in a word (let's say "cheat", just for simplicity sake) that activates the cheat code. I only need to capture keyboard input when the window is in focus. What can I do to accomplish this?

# Answer
> 4 votes
You know your keywords. So store those in a string array. Store every key press into a char array and read the sequence. Allow a time out that clears the array. Compare your char string to any of the cheat keywords. When a match is found you call your cheat function.
your game should have states ( like MENU,INGAME, whatever) it's simple a matter of "if" menu is active.

# Answer
> 1 votes
Given the complete lack of implementation details provided, I'd simply say that you get the keyboard state just like you would during your normal game play, you remember which keys were pressed in order, and if the player is in the menu and a cheat code is recognized, you do stuff.

---
Tags: xna, c#, input
---


# Question
Title: Order array of points in counter clockwise
I happened to see an answer to "Sort array of points in clockwise", could you please elaborate the 4th point of that answer:

* sort points relative to their a value, using qsort for instance.

How do I do the above step?

I'm looking for an algorithm to sort list of points in counter-clockwise.

# Answer
Not familiar with the referenced article, but what I would do is:

1. Find the center of the point cloud
2. Use atan2 with the difference between each point and the center to find the angle each makes with the center
3. Sort by angle. You can either store the angle calculated in step 2 with each point (a Z value in a 3d coordinate created from each 2d coordinate is a convenient way to do this) or just skip step 2 and recalculate the angle in your sort comparer
4. Done!
> 0 votes

# Answer
The full quote from that answer is (I added the numbers for easy reference):

1. let `P[0], P[1], ... P[n-1]` be the list of points to sort
2. let M be the barycenter of all points
3. compute `a[0], a[1], ... a[n-1]` such that `a[i] = atan2(P[i].y - M.y, P[i].x - M.x);`
4. sort points relative to their `a` value, using `qsort` for instance.

The "`a` value" part of step 4 is referencing step 3. So, in step 4 it's saying "sort the points array based on the values in the array you made in step 3 (using something like quick sort)."

Now, if sorting that array of values will get you the clockwise order of points, then sorting it in reverse order will give you the points in a counter-/anti-clockwise direction.

Hopefully that clears it up a bit for you.
> 1 votes

---
Tags: 2d, algorithm
---


# Question
Title: Resolving bounding box collision detection
I'm working on a simple collision detection and resolution method for a 2d tile-based bounding box system. Collision appears to work correctly, but I'm having issues with resolving a collision after it has happened.

Essentially what I'm attempting to do is very similar to this approach. The problem I'm experiencing is that because objects can be traveling with both horizontal and vertical velocity, my resolution code causes the object to jump incorrectly.

I've drawn the following annotation to explain my issue. In this example, because my object has both horizontal and vertical velocity, my object (which is heading upwards and collides with the bottom of a tile) has it's position altered twice:

* To **correctly** adjust it's vertical position to be beneath the tile.
* To **incorrectly** adjust it's horizontal position to be to the left of the tile.

Below is my collision/resolution code in full:

```
function intersects(x1, y1, w1, h1, x2, y2, w2, h2)
{
    w2 += x2;
    w1 += x1;
    if (x2 > w1 || x1 > w2) return false;
    h2 += y2;
    h1 += y1;
    if (y2 > h1 || y1 > h2) return false;
    return true;
}

for(var y = 0; y < this.game.level.tiles.length; y++)
{
    for(var x = 0; x < this.game.level.tiles[y].length; x++)
    {
        var tile = this.game.level.getTile(x, y);
        if(tile)
        {

            if(
                this.velocity.x > 0 &&
                intersects(this.position.x+dx+this.size.w, this.position.y+dy, 1, this.size.h, x*tileSize, y*tileSize, tileSize, tileSize)
            )
            {
                this.position.x = ((x*tileSize)-this.size.w);
                hitSomething = true;
                break;
            }
            else if(
                this.velocity.x < 0 &&
                intersects(this.position.x+dx, this.position.y+dy, 1, this.size.h, x*tileSize, y*tileSize, tileSize, tileSize)
            )
            {
                this.position.x = ((x*tileSize)+tileSize);
                hitSomething = true;
                break;
            }
            if(
                this.velocity.y > 0 &&
                intersects(this.position.x+dx, this.position.y+dy+this.size.h, this.size.w, 1, x*tileSize, y*tileSize, tileSize, tileSize)
            )
            {
                this.position.y = ((y*tileSize)-this.size.h);
                hitSomething = true;
                break;
            }
            else if(
                this.velocity.y < 0 &&
                intersects(this.position.x+dx, this.position.y+dy, this.size.w, 1, x*tileSize, y*tileSize, tileSize, tileSize)
            )
            {
                this.position.y = ((y*tileSize)+tileSize);
                hitSomething = true;
                break;
            }
        }
    }
}

if(hitSomething)
{
    this.velocity.x = this.velocity.y = 0;
    dx = dy = 0;

    this.setJumping(false);
}

```

# Answer
There's a couple of issues with the posted code. Your collision-checking loop looks something like this:

```
for(Y) {
    for(X) {
        if (collision) {
            hitSomething = true;
            fixPosition();
            break;
        }
    }
}

```

The break only breaks out of the X loop, it continues on the Y-loop. The block gets moved to the correct column, but it still intersects with a tile on the next row, so the block then gets moved again. So the first thing to do is to put the entire thing in a function, and replace the `break` with `return`.

Secondly, you always check X-intersection before Y-intersection. You have kind of "fixed" it by checking the leading edge of the moving object, but it still will detect the left/right edge before the top/bottom edge. I'd rather see an unbiased collision detection by checking `intersects` on the full box, and then based on the relative position of the two objects, deciding which way to fix the position and then bounce the velocity.
> 1 votes

---
Tags: 2d, collision-detection, bounding-boxes
---


title: How can I customize an FPS game?

text:
# Question
Title: How can I customize an FPS game?
I want to create a customized (modded) fps game where I can change the look and feel of the game to match my intended theme.

Some of the things I would like to do:

* Create a custom map (terrain).
* Add custom sound effects
* Change AI (For example, running away instead of actively looking for combat).
* Change menus and add some storyboard.
* Script events in game (like a countdown until game over)
* Change the models of the NPC's.

What options do I have? Is there any platform/game/engine/whatever that allows one to do the things above in a reasonable way?

I work as a programmer so I'm not afraid of coding some part of the project, but to save time it would be nice to work in some high-level way (like scripting or configuration files).

# Answer
Why not look into the free Unreal Development Kit?

You can stick to the high level stuff or you can get down and dirty with the code. It includes an FPS demo.

The map editor is a ton of fun to play with too.
> 4 votes

# Answer
I'm not too big into FPS games so only one thing comes to mind that would allow such extensive modding in a short time, and that's Bethesda's Fallout 3. I've seen quite a few mods for it and everything in your list is possible given you're willing to put in some effort. It's not going to do everything for you but it will speed up the process.
> 1 votes

# Answer
If you want a completely free solution, where you can also feel free to publish your work without warring about royalties and fees, you can use the Blender game engine and you can create your own game right inside blender and export it as a standard application.

Blender is a completely free open source 3D modeler with advanced capabilities and it's written in C++ for the biggest and offers internal API for Python.
> 0 votes

---
Tags: scripting, first-person-shooter, modding
---


title: Convenience of mySQL over xml

text:
# Question
Title: Convenience of mySQL over xml
Currently I use XML to store specific information to correctly load a few things such as a list of specfied characters, scenes and music, Once more I use JAXB in combination with standard compression/decompression(ZIP) functionality to store a list of extrenous data. This data is called to add functionality to the character, somewhat like Skills in an RPG. Each skill is seperated into its own XML file with a grandlist which contains the names of each file with their extensions omitted and zipped in folder that gets encrypted.

At first using xml was working fine however as the skill list grow i worry about its stability. I was wondering if I should begin storing the data in mySQL. Originally I planned to simply convert everything to JSON over xml but i think possibly mySQL would be a better move.

Can anyone inform me of the key difference and pros and cons of each I guess i'm looking for the best way to store the data more conviently and would be easier to operate on. The data is mostly primatives and strings and the only arraylist of values i have i can just concat into a single field and parse later

Edit:

If I am going in the right direction with XML would it make sense to convert it to JSON and use maybe Kyro or EclipseLink JAXB (MOXy)

# Answer
Databases have a quite different use case than file formats like XML.

**File-Formats like XML**:

* Are saved once and loaded once per application start-up.
* Since they are loaded once the access time after the loading is extremely fast.
* Used for serialization and deserialization as well as configuration files.

**Databases**:

* Are for the most part constantly in memory.
* Changes to the database apply directly. That means that if the application which is writing the database unexpectedly shuts down all changes except the last very few (or even those too, if the database is external) are applied either way.
* Access time is quite slow in comparison as queries need to be parsed, hashes be calculated and other stuff.
* Due to the other attributes they are used as "Persistance Layer" for long running applications which constantly change (servers in most cases).
> 10 votes

# Answer
If this is just simple, local information, then storing it in any kind of "database" is massive overkill, let alone something like MySQL. SQLite *might* be appropriate.

These data seem to be for game concepts. So don't forget: you need to *author* this data. It's a lot easier to hand-edit XML/JSON/etc than it is for some kind of database. You can even develop tools to validate XML, thus making sure that values are within acceptable ranges. If you use something like a Lua script, you can even have dependent properties, where changing one value can change it globally across all scripts.

Considering how easy it is to author text, and how hard it is to author databases (unless you want to write a specialized editor program), I see no reason to use databases for this at all.
> 5 votes

---
Tags: java, xml, jmonkeyengine, sql
---