# Question
Title: Java: AI to make a mob face the player working half-way correctly
While creating some basic AI for my "ghost" mob that is just up for testing at the moment, I thought of allowing it to face the player, depending on the player location. I get it to work correctly, but it doesn't act exactly as I want it to. Here is the current code I use for when getting the ghost to face the location of the player:

```
if (player.getX() < this.getX())
    dir = 3;
else if (player.getX() > this.getX())
    dir = 1;
else if (player.getY() < this.getY())
    dir = 0;
else if (player.getY() > this.getY())
    dir = 2;

```

It will switch viewing position as I want along the x-axis, but along the y-axis I have to be exactly lined up for it to face me as so (the sprite below the first one is the player, I am just using the same sprite for the ghost at the moment):

As long as I am down there I would like it to face that location, but if I adjust one pixel this happens:

For the mapping, I want it to act similar to this, positions will change within a certain range is what I really want though, so if I were to move to the left side of the ghost, it would switch to that view, but if I were to stay at the bottom, I want it to stay facing that way:

My problem is that I want the ghost to face the player depending on the location, and I just can only get it to face the way I want it to on the x-axis, and not how I want on the y-axis, I have to be exactly lined up by the pixel for the y-axis for the ghost to face the player vertically. How would I accomplish this?

# Answer
> 4 votes
You need to figure out if the distance on the x-axis is larger or smaller than the distance on the y-axis, and then make the sprite look along the axis which is longer.

```
double dist_x = player.getX() - this.getX();
double dist_y = player.getY() - this.getY();

if (Math.abs(dist_x) > Math.abs(dist_y)) {
    if (dist_x > 0) {
        dir = 1;
    } else {
        dir = 3;
    }
} else {
    if (dist_y > 0) {
        dir = 0;
    } else {
        dir = 4;
    }
}

```

---
Tags: java, 2d, ai
---


# Question
Title: How Do Objects Not Clip Out the Back of Thin Walls When Put Through a Portal?
In *Portal* or *Portal 2*, let's say you pick up a cube and put it most of the way through a portal on a very thin wall. The cube should clip outside the backside of the wall. How does *Portal* do this, or how can this be done in general?

# Answer
You're looking for a form of antiportals combined with portal rendering. Portal rendering is an old technique for breaking the world apart into sectors and only rendering the objects (or pieces of objects) within a given sector at a time and using visibility sets to figure out which portal to render. Antiportals are a technique by which you cull objects (or individual faces or vertices) which are occluded by a solid plane. Note that traditional portal rendering would not cull the objects halfway through a portal, though antiportals could be used for this. This you can generate an antiportal for each "portal" in the game and then use it to draw only the visible half of the object on the "outward" side of the portal.

There are a few ways to do this. The most obvious "brute force" way is to simply clip the whole object at the polygon/triangle level against the portal. This would not have been an uncommon approach in years past with low-poly models were Portal written back then, but it's *probably* not what a modern engine would do.

Another option is to use GPU clipping. This can be a combination of vertex clipping and fragment culling. The position of any fragment can be calculated in the fragment shader when rendering in many rendering engines. This position can be compared against the antiportal's plane and then only drawn if it's on the front side (easily determined with a dot product).

While it doesn't go into any great depth on how the portal rendering works, you may find the Narbacular Drop technical design document of interest. This is the student game that inspired the original Portal, whose team members were hired by Valve to implement the portal mechanics of Portal in Source. See also this Gamasutra article. The rendering is mostly a well-known solved problem and the real trick of making Portal actually work was the physics, which is a much more interesting and challenging problem to solve.
> 6 votes

---
Tags: clipping, portals
---


title: How are done "snake" particles?

text:
# Question
Title: How are done "snake" particles?
I thought that particles were basically GPU-powered sprites. After looking at the following demo, I'm not totally sure of that anymore : http://vimeo.com/18715688

How are done those snake-like particles ? I don't see any defect in the shape, and I assume that there is not a particle for each pixel unit of a snake.

# Answer
> 4 votes
A sprite is only the simplest type of particle. It's also possible for particles to have more complicated geometry. There's no reason in principle a particle can't have an arbitrarily complicated mesh, aside from performance constraints. A particle can also have procedural geometry, which can be animated over time just like the rest of a particle's attributes.

It's also possible for multiple particles to be attached together for either simulation or rendering purposes. E.g. for simulation you could put springs between particles, and for rendering, instead of generating a mesh for each particle you could have each particle just contribute a set of vertices, with triangles stretching between multiple particles. A 1D string of particles, each attached to the next, is commonly used in games for rendering things like sparks and trails. Another example is a cloth simulation - basically a 2D grid of particles with spring constraints between them, where the particles also serve as vertices for a triangle mesh.

It looks to me like this is what you have in those videos. I would guess that each "snake" is actually a 1D particle string, where each particle has a ring of vertices, and triangles are stretched from one ring to the next to create a tube, which is what you see rendered. Each particle independently controls its position, orientation and radius according to its rules (which may well include some type of springs between adjacent particles, to keep the whole snake together).

---
Tags: particles
---


# Question
Title: Can you help me solve the paradox that has confused me about the glViewport and glOrtho functions?
suppose that I have an image that I want to apply as a texture on a geometry (at time we don't consider texture mapping but this image has a certain width and height here it is a 512x512 image)
I want the image be drawn at the center of the window so I have set the window coordinates as follows:

```
glOrtho(-oglWindowWidth/2, oglWindowWidth/2, oglWindowHeight/2,-oglWindowHeight/2, -1, 1);

```

and then drew the geometry:

```
float x0 = -ImageWidth/2; // top left corner of image
float y0 = -ImageHeight/2;
float x1 = x0 + ImageWidth; // bottom right corner of image
float y1 = y0 + ImageHeight;

glBegin(GL_TRIANGLE_STRIP);
{
    glVertex2f(x0, y1);
    glVertex2f(x0, y0);
    glVertex2f(x1, y1);
    glVertex2f(x1, y0);
}
glEnd();

```

It's true and what I reach as the result is:

Meaning that the coordinates of the center of both the image and window is (0,0) and the image will be drawn at the center of the window
But since I need the viewport, I used this code after drawing the geometry:

```
GLint iViewport[4];
glGetIntegerv(GL_VIEWPORT, iViewport);

```

and reached the result: **(0,0,573,543)**
now I think that the line of code: `glOrtho(-oglWindowWidth/2, oglWindowWidth/2, oglWindowHeight/2,-oglWindowHeight/2, -1, 1);` says that:
**left of window : -573/2 = -286.5
right of window : 286.5
top of window : -543/2 = -271.5
bottom of window : 271.5**
But the `Viewport` tells:
**left of window : 0
right of window : 573
bottom of window : 0
top of window : 543**
Note that if I set the `Viewport` by something like the following code:

```
glViewport(-oglWindowWidth/2, oglWindowHeight/2, oglWindowWidth, oglWindowHeight);

```

I won't get the true result. I mean the geometry will not be drawn at the center of window as shown in the photo?
How can I solve the paradox having two different coordinate values for the bottom left of the image by two different codes?

# Answer
> 5 votes
Window coordinates - the coordinates in which the viewport is specified using `glViewport` \- are not the same as the view space coordinates that you pass to `glOrtho`. Window coordinates are *always* measured in pixels from the lower-left corner of the window, while view space coordinates are entirely up to you and can be defined however you like.

You can think of `glOrtho` as a function that lets you define your view space by saying where the corners of the viewport should be in view space. On the other hand, `glViewport` lets you say where the corners of the viewport should be in actual pixels in the window (or in an offscreen render target).

When you submit a vertex (in view space, since you don't have a modelview matrix yet), it first gets transformed to what are called normalized device coordinates, using the projection matrix specified by `glOrtho`. Then it gets transformed from there to window coordinates (i.e. pixels) using the viewport specified by `glViewport`. Then it gets sent off to be rasterized.

Now, you happen to be setting up your `glOrtho` call in such a way that your view coordinates are also measured in pixels. But that's just a choice you're making. You're also setting it up so that the origin of view coordinates is at the center of the window. That's another choice you're making. That choice doesn't affect the definition of window coordinates, though; they're still measured in pixels from the lower-left corner of the window.

---
Tags: opengl, coordinates, viewport, visual-studio
---


# Question
Title: Why don't we use the whole color depth for normal maps?
All normal maps I've seen are pinkish or bluish. It seems like only a small color range is used. Why do game developers give away so much precision?

# Answer
The colors in a normal map represent the normals at each point. If a normal is `(x, y, z)`, the corresponding pixel in the normal map will have each of `x`, `y`, and `z` mapped from the range `(-1,1)` to `(0,255)` to get the red, green, and blue components respectively.

Now the z-axis is typically used as the direction away from the surface. A perfectly flat surface, with normals `(0, 0, 1)` all over, will have `x` and `y` both mapped to `128`, and `z` mapped to `255`. That means the resulting color is `(128, 128, 255)`, which is the sky blue you see often in normal maps.

The bumps in a surface deviate away from this normal, removing a little bit of the blue component and giving it to the red and/or green components (depending on which direction the bump is facing). Generally, the bumps in surfaces are not particularly exaggerated, so the normal map remains mostly blue. You will see magentas and cyans for the bumps that face along the x- and y-axes.

If you found the normal map for a surface with harsh bumps in it, such as a brick normal map, you'll see that the edges are very much red-ish and green-ish.
> 12 votes

# Answer
It's true that many tangent-space normal maps have only a limited range of colors. Object-space or world-space normal maps would have a wider range of colors, but if we're only using tangent-space normal maps in our game (as most developers do), it's a quite legitimate question to ask why we don't choose an encoding that trades off the range that we're not using to gain more precision.

For example, instead of mapping \[-1, 1\] to \[0, 1\] for each component, we could decide we're going to map \[-0.5, 0.5\] to \[0, 1\] for the XY components, and \[0.5, 1\] to \[0, 1\] for the Z component. That would give us twice the precision.

The answer is we usually don't *need* more precision, and using the standard mapping gives us the range to handle any conceivable normals.

However, sometimes we do need more precision. On surfaces that are nearly smooth but not quite and have very subtle bumps, the combination of the \[-1, 1\] range plus DXT compression can certainly yield visible banding due to poor precision of the normals. In games I've worked on we added a per-material "normal map strength" parameter that would let you effectively adjust the encoding for a specific texture, so you could use a smaller range like \[-0.5, 0.5\] or \[-0.1, 0.1\] if you wanted, and thereby get much more precision.

An example of the kind of surface we'd use this on is a car hood, or a glass window on the side of a building (which is not quite flat, but very slightly warped). Both of these are hard, shiny surfaces with quite subtle curvature, which means you can easily see any imperfection in the normals due to their effect on cubemap reflections. Adjusting the normal map encoding for more precision vastly improved the appearance of these surfaces.

Nevertheless, they were the exception rather than the rule, and the default \[-1, 1\] encoding was quite sufficient for almost all surfaces in the game.
> 7 votes

# Answer
Who says we do not? You are limiting your thought process to Tangent Space Normal Maps, which (generally) always point *away* from the surface they are mapped onto. There are also World / Object Space Normal Maps, which contain every color of the rainbow because they are not related to the surface's coordinate space.

As a fun experiment, you should multiply a tangent space normal map by the TBN matrix and output the resulting color instead of normal lighting. Notice how the colors dramatically change, since they are now in object space (or view space depending on how you created your TBN matrix)?

You're not done though, now that the normals are in object/view space you will probably have quite a few vectors that have negative values. You need to bias and scale the colors so that negative values occupy the lower half of the color space and positive values occupy the higher (if you actually want to visualize the normal map correctly, that is).

*If you do not want to do the experiment yourself, you can see the difference between world space and tangent space in the image below*:

Tangent space normal maps are in a special coordinate space that ensures positive Z is always normal to the surface. Since XYZ is usually encoded into RGB and most surfaces are relatively flat (e.g. the dot product between the normal the texture provides and a vector tangent to the surface at any point is pretty close to 0) B dominates the color space in tangent space.

In world/object space, there is no dominant color, but these normal maps do not like to be deformed. Ultimately when tangent space normal maps are used, either lighting is done in tangent space or the normal map is transformed into world/view space before lighting. By deferring this transformation (or avoiding it altogether) until render time, objects can be rotated and texture coordinates can be deformed without invalidating the normal map. World space normal maps are usually reserved for static world geometry, and may be used for the normal G-Buffer in deferred shading.
> 5 votes

# Answer
You can store just two components of a normalized normal map in an RG texture and trivially recompute the third component. I don't know why this isn't more common other than the performance hit of the square root operation in doing this.

```
1 = sqrt(x^2 + y^2 + z^2)
z^2 = 1 - x^2 - y^2
z = sqrt(1 - x^2 - y^2)

```
> 1 votes

# Answer
We actually do use the full colour-depth.

First of all, normals should be unit-length, otherwise we need to do an expensive (and unnecessary) renormalization in the fragment shader.

Let's assume that you're looking at a texture face-on, as if in an image editor.

* A normal of {0,0,1} is the unit-length normal that's pointing towards you, which translates to a normal map colour of {128, 128, 255}.
* A normal of {0,0,-1} on the other hand points *away* from you, and that's a colour of {128, 128, 0}.
* Normals of {1,0,0}, {-1,0,0}, {0,1,0}, and {0,-1,0} are at right-angles to your view direction, and you can work out the colours yourself.

So already, for just the six cardinal directions (up/down/left/right/front/back), we need values of 0, 128 and 255 in each of the R, G and B channels. They're obviously not the only 6 directions something can be pointing in, so we also need intermediate values. That's the full colour-depth.

The reason why most normal maps are chalky-blue is that most of the time they encode normals that are pointing towards the viewer (my first bullet-point above), and most of the rest of the time they encode normals that are pointing more-or-less towards the viewer. But they don't *have* to, and without using the full colour-depth they'd lose the ability to point in any arbitrary direction.

This is actually nothing to do with any notion of "precision", it just comes from the direction normals tend to point in when encoded in a normal map.
> 1 votes

---
Tags: textures, lighting, normal-mapping
---


# Question
Title: GLSL: define a constant for both vertex and fragment shader
I have a constant for defining an array in the vertex shader. I want to use this constant also in the fragment shader to define another array of the same size. Naive attempts fail (simply use the constant of the vertex shader in the fragment shader or using a `#define` from the vertex shader). Is this somehow possible?

The only idea I can come up with is using something like an include statement, which seems to be added (source), but I didn't yet find the time to implement this.

Thank you in advance!

# Answer
There is a reason why `glShaderSource` and `glCompileShaderProgram` both take an *array* of strings. It's so that you can effectively insert code before your actual shader text or otherwise implement your own "include" system.

The issue here is that you now need to break your shaders down into pieces:

1. The header preamble. The first thing in the first string needs to be a version declaration. Following that should be any extensions of note.
2. Any collective definitions, like the ones you're trying to add to the shader.
3. Your actual shader text.
> 2 votes

# Answer
Vertex and fragment shaders are two separate programs that are compiled independently of each other. Any definitions that you want to use in both shaders have to be included in the source of both shaders; definitions do not carry over from one shader to another.

I assume most developers implement some kind of include system - whether it's by using the `ARB_shading_language_include` extension, or by passing shader source files through the C preprocessor before compiling them, or some other method.
> 1 votes

---
Tags: glsl
---


# Question
Title: Why is it possible to encounter a texture coordinate greater than 1 or less than 0
I'm studying a text about `texture mapping` and in the `preparing to draw` session, I read:

**Define the texture wrapping parameters. This will control what happens when a texture coordinate greater than 1.0 or less than 0.0 is encountered:**

```
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,wrap);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,wrap);

```

**where wrap is:**
**GL\_REPEAT : specifies that this pattern will repeat (i.e., wrap-around) if transformed texture coordinates less than 0.0 or greater than 1.0 are encountered.**

**GL\_CLAMP : specifies that the pattern will “stick” to the value at 0.0 or 1.0.**

But there's no explanation what is the reason of encountering such texture coordinates?
For example suppose that I have just drawen a rectangle and I want to apply an image as a texture on it, is it possible to encounter such coordinates?

# Answer
> 5 votes
Not all textures use texture coordinates that come from the mesh data. For example, with projective texturing, you transform the world into the space of the texture. Well, a lot of that world falls outside the \[0, 1\] range of the texture. Without some sort of clamping mode in place, you're going to get problems.

# Answer
> 10 votes
Precisely, to repeat a texture.

So, if you have a quad, and the texture coordinates go from 0 to 1, the texture will be drawn once. If the coordinates go from 0 to 2 and wrap is set to `GL_REPEAT`, then the texture will be drawn twice.

Try it and see it by yourself

# Answer
> 5 votes
Yes, you can encounter texture coordinates greater than `1.0` and smaller than `0.0`.

This depends completely on the model, you loaded. Normally, for each vertex there is position, normal, and texture coordinate stored. In most mesh file formats, the texture coordinate is not restricted to any range.

This is used to repeat a texture. For example, to span a texture four time between a quad of vertices, the texture coordinates would be `0,0`, `0,4`, `4,0` and `4,4`. Without texture wrapping, you would need additional vertices to split the surface into 4 times 4 sub surfaces with each the texture coordinates `0,0`, `0,1`, `1,0`, `1,1`. Fewer vertices results in better rendering performance.

Typically, it is not desired that the user notices the edges of a repeated texture. Therefore, repeated textures are tileable in most cases. Than means, the right edge fades seamlessly to the left one and the top edge to the bottom one. This way, the transition is smooth and hopefully not notices by the user.

A more advanced, but related topic is, to cleverly obscure the fact that the same texture was repeated multiple times. For example, blending repeated textures of different size, for example a wall texture and a dirt decal, is a common technique.

---
Tags: c++, opengl, textures, image, visual-studio
---


# Question
Title: OpenGL ES - DrawCalls count - bottleneck?
I am newbie to OpenGL ES (so far, I used mainly DX11). Now for my scene, I have about 100 draw calls. I can use instancing, but only about half of objects can be instanced, so draw calls count would be about 50 - 60 / frame. Every object is max. 700 triangles (I use low-poly models)

What is some kind of limit of drawcalls per scene (targeting iPhone 4 like performance devices) ? So far I am running my code via ATI GLES on Windows, but there is a lot of power from my CPU and GPU.

Or is there a way, how to find bottleneck of my application ? I know gDebugger is for OpenGL, but with ES version it behave sometimes weird (a lot of warnings in calls I dont have in my code, so I suspect them to be from ATI layer code).

# Answer
Draw calls by themselves are not always the bottleneck, it is what happens between them that is. Generally when you issue a draw call, the command buffer (state changes, data uploads, etc.) is evaluated and the expense of changing many states is actually deferred until this point. For instance, if you issue the same draw call back-to-back the second draw call will be significantly less expensive since there are no state changes. Because of this it is difficult to definitively say "keep your draw call count below X."

The story has traditionally been different in Direct3D, where pre-Windows Vista draw calls invoked a user-mode to kernel-mode context switch. Before D3D had a user-mode front-end (Windows Vista+) every draw call would cause an expensive context switch in addition to the expense of deferred state setup. When people optimize to minimize draw calls, this is probably why.

It is more effective to minimize state changes, which usually has a side-effect of reducing draw calls too. You'll want to develop a batch processor that sorts your geometry to minimize state changes - generally textures are the most important state change to minimize.

If you are seeing a lot of errors in gDEBugger, you may want to run your Windows software in an OpenGL debug context and enable debug output. This is an OpenGL 4.x-era feature, but if your driver supports the OpenGL ES extension it almost certainly has ARB\_debug\_output as well. Debug output will warn you when you do things like use misaligned data structures, which is handy for performance testing. See this answer for more details.
> 6 votes

# Answer
I wouldn't consider "700 triangles" as "low poly" for ES. Try to see if you can get your poly count even lower. Then make the poly count lower than that. I mean really decimate it.

Anyway, you need to run some experiments. I've been meaning to test this too, but haven't yet. At a certain point the *pixel shader* will likely be what limits your frame rate. Mobile devices don't have a very high fill rate, if you're alpha blending or trying to use bloom effects, that will be your limitation. I could not use bloom even on iPad 4 simply because it dropped the framerate by far too much (for even only relatively little geometry).

So anyway, run profiler on an actual device. Instance your model and be sure you compile in release mode and watch the frame rate in Xcode. You'll find the limits by testing.
> 2 votes

---
Tags: performance, opengl-es2
---


# Question
Title: GLSL - Declaring global variables outside of the main function scope
Does it help to declare variables outside of your main function scope in GLSL? Do these variables actually get reused and is it more efficient?

Here is the code in question:

```
varying vec2 vposition;
uniform float seed;
uniform float top;
uniform float bottom;
uniform float phi;
uniform float theta;
uniform float scaledPI;
uniform float yn;
uniform float ym;
uniform float rx;
uniform float ry;
uniform float radius;

const float PI = 3.141592653589793238462643383;

float left;
float right;
float mscaled;
float xn;
float xm;
void main() {
    float t = vposition.y * yn + ym;

    if(t <= 0.0 || t >= PI){
        left = phi - PI;
        right = phi + PI;
    }else{
        mscaled = scaledPI / (1 - abs(Math.cos(theta)));
        mscaled = mscaled < PI ? mscaled : PI;
        left = phi - mscaled;
        right = phi + mscaled;
    }
    xn = (left - right) / ((-rx / 2.0) - (rx / 2.0));
    xm = left - ((-rx/2.0) * xn);
    float p = vposition.x * xn + xm;

    vec3 coords = vec3( sin(p) * sin(t), cos(t), cos(p) * sin(t) );
    float nv = surface( vec4( coords, seed ) );
    gl_FragColor = vec4( vec3( nv, nv, nv ), 1.0 );
}

```

# Answer
I think I get what you're trying to ask. I assume your primary concern are the non-uniform variables defined outside of `main()`:

```
float left;
float right;
float mscaled;
float xn;
float xm;

```

Let's take a look at how the GPU and GLSL work. The GPU does not have a stack or a call activation records. There is not a way to simulate scope or local variablaes in GLSL like a C compiler can do on most CPUs. All that exists are the registers, which are either uniform registers, shader stage inputs, outputs, and the local register file unique to that shader invocation.

In other words, as there is no such thing as a function or the stack or a heap, all variables declared anywhere live in a register. Whether they're local to some scope in GLSL or global to the whole file makes no difference. They're just registers.

However, the register allocator is not part of the GLSL standard. Different OpenGL implementations can have varying levels of quality when it comes to converting high-level GLSL code into the low-level machine code the GPU understands. One of the more complicated parts of a compiler (GLSL or otherwise) is *register allocation*. This is the part of the compiler that determines which registers a given variable occupies. C has it a bit harder as it usually has to deal with very tiny register files (especially on x86) and it has to deal with register spilling (moving variables to the stack) and aliasing (saving variables back to RAM before calling functions) and odd instructions which demand the output be in a particular register (x86's `idiv` for instance). GPUs have a large-ish register file on account of having no stack or heap, so the allocator can be simpler.

However, the register file is not infinite. If you have more variables than registers supported by your hardware the compiler will have to try fit all your variables in the registers. This usually requires some form of *liveness range* checking. That is, if you use a variable `xn` for one calculation then never use it again, the compiler can determine this and then know that the register occupied by `xn` could be used by another variable later on, thus allowing more variables than there are registers (so long as there's not too many live variables at once).

The compiler might not do this, however. It doesn't have. Or it might do it only in some cases. Scopes given simpler compilers a much easier problem to solve. All the registers allocated to local function variables can be reused after that function exits because it knows the variables are dead. Global variables have no such easy guarantee. Hence, some less capable compilers may not optimize their lifetimes as well, and the global variables will always eat up a register. This won't make anything *slower* but it may on some drivers limit the size of the shader you can write.

In general, I would highly recommend keeping all variables localized. Keep the definition as close to the use of the variable as makes sense. This applies to all programming languages, not just GLSL. I would also recommend making every "variable" const in every case you possible can. It can again be a hint to certain less-capable compilers that certain optimizations are possible, and more importantly, it makes your code more self-documenting and easy to maintain.

And of course, here's your obligatory "just profile to test and find out for sure" advice. Write your shader with and without your globals and profile it. Any and all performance advice online should be mistrusted and assumed to either be steeped in supposition or out of date.
> 42 votes

---
Tags: glsl
---


# Question
Title: Drawing a textured 3D object breaks SFML text render
I writing a OpenGL game using SFML.

I'm using the push/pop function to combine OpenGL with SFML like the tutorial SFML+OpenGL but, when I added textures to my model, the SFML text rendering appears broken and wrong rendered.

The simplified loop I used is:

```
while( true ){
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
    glUseProgram( programID );

    // Draw the 3d textured object
    glActiveTexture( GL_TEXTURE0 );
    glBindTexture( GL_TEXTURE_2D, tex_2d0 );

    object.draw();

    window->pushGLStates();

    window->setView( view );
    window->draw( text );
    window->setView( window->getDefaultView() );

    window->popGLStates();

    window->display();
}

```

My 3d model is draw right but something in the glActiveTexture/glBindTexture mess up the text in the SFML part.

If I add:

```
glActiveTexture( 0 );
glBindTexture( GL_TEXTURE_2D, 0 );

```

And the end of my OpenGL rendering code, nothing is fixed anyway.

# Answer
> 3 votes
SFML but it can only saves/restores OpenGL 2.x states. We must disable what we enable in +3.x states. It works adding:

It's fixed adding at the end of own drawing something like:

```
glBindBuffer( GL_ARRAY_BUFFER, 0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
glBindTexture( GL_TEXTURE_2D, 0 );
glDisableVertexAttribArray( 0 );
glDisableVertexAttribArray( 1 );
glUseProgram( 0 );

```

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


# Question
Title: 2D engine that uses Flash Platform classes?
I want to develop a 2D game for Android, but, I want to use Flash Platform's framework APIs, ex: `Sprite`, `Shape`, `Graphics`, `Bitmap` .. etc as I have already wrote my game in AS3 ..

Is there a 2D engine for Android that uses Flash Platform's framework APIs?

If not, does Unity use Flash Platform's framework APIs?

I know that I can Adobe AIR to port the game to android, but, I want it a native code based to avoid Adobe AIR player as a requirement ..

Any guidance?

# Answer
> 1 votes
There is the brand new http://www.openfl.org/.

It uses the language Haxe which is based off of AS3 (the only difference I found is that constructors must be called `new` and not the class's name). It's great because it compiles to Android, iOS, blackberry, flash, html5, windows, max, and linux. :D

When it compiled to Android it converts the Haxe files to C++ and then uses the NDK to bind everything together. It is HIGHLY optimized so the speed of Haxe generated code is very comparable to code written by hand.

A few popular flash game engines have been ported over as well. eg. (HaxePunk port of FlashPunk and haxe-flixel port of flixel).

For windows the best IDE for it is flashdevelop hands down. For linux it's vim with some plugins and I'm not sure for mac (sorry)

The website for the haxe language is here http://haxe.org/

---
Tags: unity, 2d, actionscript-3
---


# Question
Title: Is there a library that handles hexagon tiled 2D maps?
It would represent a map that is semi-square of arbitrary size. It would have a simple system for representation of the map coordinates, such as 0101 (first column, 1st hex). I'd want the map to be able to tell me the distance between two points and what other hexes lay between those two points, as a list or array.

I don't care as much about the language, but C# or Python would be ideal.

Does one exist?

# Answer
Not a library but more of a tutorial. Looking though the tutorial it seems to do everything you requested. It uses C# / XNA.

Article: Hexagonal Coordinates « Sgt. Conker
> 4 votes

# Answer
The Cocos 2D library has support for rendering hex tile maps. I have not used it, but the library has been around for years and seems quite popular.

That might be more for rendering than for doing calculations on the hex map though. Fortunately what you ask for is quite simple to implement anyway, especially if you use a good x/y coordinate system for your hexes. See: http://www-cs-students.stanford.edu/~amitp/gameprog.html#hex
> 4 votes

# Answer
Pieter Geerkens (who is here on stackexchange) has a C# library for hexagons.
> 4 votes

# Answer
I believe the *Java* version of the *Tiled Map Editor* supports hexagonal maps. Have a look for yourself at: http://www.mapeditor.org/
> 3 votes

---
Tags: 2d, maps, hexagonal-grid
---


# Question
Title: Multipass shaders and switching between passes
As mentioned here Effects should be avoided in DX11. If I understand correctly, that includes techniques and passes defined in \*.FX files. So when doing a multipass shader (like the always-mentioned toon shader) I should create 2 separate shaders (for 2 passes), set the first one, render geometry, set the second one, render the geometry again. Correct so far?

But what I'm concerned about is that whether or not the technique/passes in Effects are just a syntactic sugar and offer no performance improvement whatsoever. Or the whole Effects in general. Do they?

GLSL version 4.20 or sth about that has subroutines which allow to switch the function in the shader and avoid changing the shader which **does improve performance**. Is there anything similar in DX?

**Edit:** Here \[link\] it says:

> Since performance is crucial in shader programs, avoiding a conditional statement or a shader swap can be very valuable. With subroutines, we can implement the functionality of a conditional statement or shader swap without the computational overhead.

Also this post seems to confirm it.

# Answer
Techniques and passes in an effect file are just syntactic sugar. Internally, the effect system is creating a separate shader for each pass of each technique. It also does things like managing constant buffers for you. The Effects 11 source is out there now, so you can look in there and see exactly how it works.

As for switching shaders, the common wisdom is that it's good practice to sort your draws by shader in order to reduce state changes to the minimum possible. I haven't seen any recent studies of just how much performance is at stake, though.

I'm not that familiar with GLSL subroutines, but they sound similar to D3D11 dynamic linking (which I'm pretty sure basically no one uses). Internally, I wouldn't be at all surprised if the graphics drivers are simply compiling a separate version of the shader for each GLSL subroutine or each D3D11 class interface, so I wouldn't take it for granted that these actually reduce the cost of state switching.
> 2 votes

---
Tags: shaders, directx11
---


title: How to shoot lasers from Ship(XNA)?

text:
# Question
Title: How to shoot lasers from Ship(XNA)?
I want a code which allows me to shoot multiple lasers from my Ship. Its a 2D game and the laser TEXTURE2D moves in a straight line. My Solution: I use `List<> class` of my `Laser` Class.

```
List<Laser> laserlist = new List<Laser>();

```

Can anybody tell me another solution other than using `List<> class`? I am new to XNA.

# Answer
> 0 votes
It sounds like your question might be more to do with what the best use of particular Collections is in C#. Lists are usually the easiest way to have a dynamic set of objects; there are some specializations for particular optimizations (if you have a collection of thousands that needs a fast access time)

Some other possibilities for you to know, but there's no need to change course:

Set\< Typename \> : The most distinct differences that come to mind are that Sets are unordered, so that you don't know which order they'll be in when you iterate. It's also, by definition, impossible to have the same object listed in a Set twice.

Typename\[\] (array) : Useful if you know exactly how many of the type you can have at most, or if you have a reasonably good guess and want to maintain performance (since you need to initialize them with a particular size).

Dictionary\< Typename1, Typename2\> : If you want to be able to access, say, a Laser, by its name, then you could initialize a Dictionary, and then retrieve the one you want with `dict["lasername"]`. Doesn't sound too useful for your case, but keep it in mind.

---
Tags: xna, textures
---


# Question
Title: Variable sized cube texture stretching problem
I have a 1x1x1 cube made in Blender with a simple UVW mapping. It represents a 3D platform of variable size.

The thing is that this cube gets resized a lot, and I want to draw a "border" of a fixed-length on each cube.

Another problem is that I am using Static Geometry, so I have to use a shader (I am using openGL, so I have to use GLSL).

So far I made this (note that the second platform is big, so it has larger borders):

What would you recommend to achieve this effect?

# Answer
Either use a geometry shader (or possibly some vertex/fragment shader magic) to generate the border from each vertex of the cube, or write a function that generates a new box with a fixed border size.

By scaling a box, you scale the whole box. There's no magical way of scaling the border separately. And it's a box, which should be simple enough to generate. There's no need to import it as a mesh from Blender. If you want a fixed border regardless of box size, you have to have separate geometry for it.

At the very least, use nearest neighbor filtering instead of linear to avoid the blurry edge on the border.
> 3 votes

---
Tags: 3d, ogre, uv-mapping
---


# Question
Title: Handling creation of enemy sprites in a level
I am trying to build an RPG tile-map based game. Currently I am going to set enemy sprites that will be repeating their motion in fixed path. Suppose that I have a level map, which has got width 3 times greater than actual applet visible to user.

Now my question is that how should I handle creation of enemy sprites? I have got two options in my mind:

1) Create all enemies at a time on level load (I don't want to follow this approach as it will take up extra memory).

2) Create enemies till the level map is visible to user. Load new enemies as user goes further. I want to follow this one but I don't have any idea.

Can someone give me hints to follow this step and tell me approach usually followed by game developers?

# Answer
Usually you would define an area, which surrounds the current view of the user and is somewhat larger (e.g. 2 or 3 times larger). At startup you load all the enemies in that area. As the user moves you can preload enemies, that enter this area and unload enemies that leave it. This way you have a somewhat upper limit of enemies that need to be loaded and can create arbitrary big worlds.

The key here then is to find the exact size of that area, so that the user never sees an enemy popping up in the current view (that is the reason why simply using the viewport does not suffice). If the enemies move rather slow, the area can be smaller. On the other hand, if enemies can move at high speeds, the area needs to be larger.
> 2 votes

# Answer
Viewports.

Viewports are essentially virtual cameras cameras that look at your scene (2D or 3D). Viewports are always designated by a view matrix, a set of coordinates for location and rotation of the camera (3x3 in 2D and 4x4 in 4D). Viewports allow you to only view a section of the scene. Often times the draw API culls (does not render) anything outside of the viewport (does not draw what it cannot see). For your application you can let the API handle this. More advanced applications use something called Frustum Culling, which allows more control over what is not rendered.

Viewports are an integral part of openGL and DirectX. You did not mention if you are directly using these or an API like LWJGL. Either way, they all have access to viewports.

Also since you are looking at a 2D plane, you need an orthographic presentation. In a 3D world, the distance between a 2D plane and the camera is greater at the edges of view than the center. (If the camera is a pyramid, the distance between the top and a base edge is greater than the distance between the top and the center of the base.) In an orthographic presentation all points on a 2D plane are equidistant from the camera.
> -1 votes

---
Tags: java, sprites, level-design
---


title: How do you know when you need C++?

text:
# Question
Title: How do you know when you need C++?
How do I know when I need to use c++, instead of Java, C#, pythonor something else? All I read is that "when you do real game making" you use C++. I put the word "real" because that is the feeling I get after reading many articles.

The games in question are for the desktop, Windows in particular. No genre.

# Answer
> 16 votes
**Portability**

C++ is a highly portable language. There are C++ compilers for almost every platform. Even languages which are in theory as or more portable, like Python, may have no standard implementation for a particular platform. For instance, to write a Python game for the XBox, you would at least need to write a C++ loader around libpython since there is no way to directly run Python code on the XBox. The same goes for most other languages. Note that you will generally have to port an OS-specific layer for each platform with C++, but then this is no different than needing to port another language's interpreter or standard library. Your target platforms may mandate or strongly encourage the use of C++.

**Compatibility**

Just about every single notable middleware, library, and OS provides a C or C++ API. In order to use these libraries from other languages, at the bare minimum a wrapper must be written. Sometimes these wrappers are not trivial to write. There's a lot of time and money to be saved by being able to drop in Scaleform, Havok, SpeedTree, or so on to your game which you will have a tougher time doing if you're writing in Java or Ruby or somesuch. The features you want to support and the amount of money you're willing to spend independently developing them may push you towards C++.

**Legality**

Some platforms have artificial restrictions making other languages less attractive. The XBox360 does not allow JIT compilers due to security concerns, automatically eliminating some languages/implementations like V8, most Java VMs, LuaJIT, Pypy, and so on. iOS bans any JavaScript runtime other than the one bundled (which is not the same one that Safari uses, notably, giving Apple's first-party applications a distinct advantage), barring the use of v8, and for a time had license language that would have barred *any* scripting language (though that language was relaxed). iOS also lacks any Flash/ActionScript runtime. There are other, more esoteric restrictions that can matter. You may be barred from using an option you prefer more than C++.

**Familiarity**

The experienced game developers in the industry typically know C++ very well but may be somewhat "deficient" when it comes to today's popular Web/FOSS favorites. If you're making a game you may need to plan for the future and think about what it'll be like trying to find an experienced games developer down the road. You may find it easier with C++ simply because there simply *aren't* any 10-year games industry veterans whose games experience is primarily with, say, Scala. HR concerns are eased with C++.

**Control**

Games often need to do tricky things, and a game engine is some of the lowest-level software you can write besides kernels, graphics drivers, and compilers (though they can often have elements of all three). Keep in mind that pretty much every other popular language today is likely running thanks to C++. The popular JavaScript runtimes are all C++. The most popular Java VMs are written in C++. Python and Ruby and Lua and so on are written in C. Some languages aim to be self-hosting, but boot-strapping them (which you'd need to do on some platforms) still generally requires C. The analogy a professor of mine had used goes something like: "Ruby or Python or JavaScript is like an elegant easy-to-drive luxury car and C++ is like an incomprehensibly complicated tank with a car factory in the back." This issue will not come up often at all (many games never have issues here), but in those rare cases when it does come up, it's easy to regret not choosing C++. You can always tack a scripting language onto C++, but it's somewhat harder (though not impossible) to plug C++ into many managed languages like C#. You won't often get backed into a corner with C++.

**Learning & Career Growth**

Assuming you're making a game to learn and maybe get a job (and this topic is related to Familiarity) there are a *lot* more resources on games programming for C++ programmers. The vast majority of "Write games in Java" books or the like are geared towards incredibly simplistic platformers and card games that don't even have the sophistication of most NES titles. You're going to have an easier time finding learning materials on how to do things - and do them right - using C++ as a base. Additionally, while there *are* many jobs in gaming using JavaScript or Java or Python or such, they're mostly limited to mobile/social games and not the kind of AAA titles most aspiring game developers hope to work on some day. Getting a job almost requires C++.

**Good Enough**

The advantages of other languages are usually given as them being easier to learn, more concise to code in, safer, and so on. However, while C++ is not at all great by any stretch of the imagination in those departments, it's not *terrible*. If you're a developer who already has C++ experience, there's little reason to bother switching. Other options can be better in many instances, but only somewhat, and generally not enough to be worth throwing away years of experience or expensive tools and libraries. This is less a reason to choose C++ and more a reason not to choose something else if you're already a C++ developer. It's easy to get into the habit of always wanting "the new shiny" but it often just isn't worth the hassle. This applies to languages, operating systems, libraries, tools, and so on. Use what works and only switch up when there is a very clear and concrete benefit to doing so. Choose C++ when you don't have a strong reason not to.

**Efficiency**

This topic was left last on purpose. Yes, C++ can be a good deal faster than most other languages if used properly. This almost certainly does not actually matter in practice. Even for the Big Guys, the runtime efficiency gains of C++ over Java are barely of importance. The things that kill performance in games are typically just as likely to kill performance for you in C++ as in any other language. Some languages, such as Java, do make it harder to deal with modern CPU caches on the like, but you can get by. Unless you're making the next Grand Theft Auto and targeting the last generation of consoles, you probably don't need C++ for efficiency's sake. Massively complex games on consumer hardware essentially require C++.

# Answer
> 5 votes
The idea behind this is, that C++ can be faster.

C++ has no automatic memory management (less overhead, but potential memory leaks yay!), direct pointer access (so we can do l33t pointer manipulation to squeeze out that last bit of performance. This is simply not possible in java, since java does not allow pointer access in the first place. segfault anyone?).

C++ is statically typed language that is compiled to machine code. C# and Java are statically typed languages, that are compiled to byte code, which is interpreted /JIT-compiled by a VM. Python is dynamically typed scripting language which is interpreted at runtime.

Compiling translate the code to machine code, which is then run directly by the CPU. Byte code has to be read and executed by an interpreter. Same goes for scripting language, but since byte code is simpler and compiled at runtime performance isn't as bad as interpreting the scripting language.

In commercial games multiple languages are used. The core engine is written in C++ for performance reasons and static type checking. Some stuff even in assembler! The gameplay is written in a scripting language as lua or python, because this code isn't as performance critical and productivity/ease of development is more important. That's why scripting language are dynamically typed. Some safety is traded for flexibility which increases developer productivity. Script code, that is too slow, can still be moved to C++ later on.

So if you're asking, if you should use C++ for your own hobby game project. Don't do it. You will have to deal with a lot issues you simply won't have using Java, C# or Python. Manual memory management, inclusion guards, cryptic error messages (try using C++ templates...), artificial split between header files and source files (god why?! I know why btw.), issues like not being able to define float constants in header files (have I mentioned cryptic error messages?) etc. make C++ a pain in the a\**. C++ is in my opinion a quite dated language with a lot of unnecessary cruft. Don't use it, if you don't have to.

If you're looking for a job in the games industry, I think you will have to learn to C++. But there are some hugely popular games written in other languages e.g. Minecraft (java).

# Answer
> 1 votes
At the end of the day make any game or application in any language you want that will get you the result you are looking for. If you can put together your application in C# and there is no performance limitation then there is no need to choose a 'real' language.

What you are running into are the limitations of some development environments. Java and C# are managed languages and so you do not have direct code access, its going to be run in its own little environment. C# has made huge improvements on execution speed and resource management to make it more Viable but you will find developers have a general bias against Java because of its large amount of overhead.

C/C++ is closer to the hardware but dumps a lot of the management on your own shoulders. This can let you better utilize the resources because you can specialize them to your needs as opposed to the general case environments you will find in the languages listed above.

I can not really speak to Python as I have not tried to use it to make a game, just tools and quick little scripts and the like. Overall though, the first part of this answer is the important part. A completed project always wins hands down over just debating about a project that is never completed.

Hope this helps.

# Answer
> 1 votes
That's a pretty general question. You can write games in every language. Main reasons for C++ I can think of are first of all performance (C++ is simply way more close to the hardware than many other languages). Also you have complete control over the whole application: you have to write everything for yourself, e.g. garbage collection. Also when integrating special hardware, you might often have C or C++ drivers, but no drivers for Java, for example.

# Answer
> 0 votes
When you want a: close to the hardware/operating system (without being Assembly) or low-level/non-abstracting/non-interpreted/forces-you-to-things-its-way; language.

---
Tags: c++
---


title: Explaining vector problem

text:
# Question
Title: Explaining vector problem
I'm trying to simulate a centipede game, and I'm doing the snake movement. I have seen that piece of code, but can't get it, I know it gets the different between the current, previou's nodes positions, but what is the point of multiplying by the normal vector ?

```
for ( int i = 1 ; i < nodes.size(); i++ )
    {

    Vec2f diff =  nodes[i-1].m_Pos-nodes[i].m_Pos;

    float length = diff.length();
    Vec2f norm = diff.normalized();
    nodes[i].m_Pos+=(length - 5)*norm;

    }

```

# Answer
In mathematics, a vector is said to be normal to a surface if it is perpendicular. In other words, normal vectors always point directly away from something.

Multiplying a scalar by a normal vector will get you a vector that represents displacement in the direction of the normal. Often normals have a handy property that they are unit-length, so if you want to move 5 units in the normal direction, nothing more than a multiplication is necessary. If it is not the case that the normal is unit-length, then an expensive normalization will be required.

Now, I am concerned by the naming in this code snippet. **Norm** actually has a *different* meaning from **normal**. In many contexts, the norm is actually the length, size or extent. A vector's norm, for instance, is a scalar that represents its length.

The fact that directly above the variable named `norm` is another variable named `length` and `norm` is declared as a vector rather than a scalar give enough context clues to indicate that `norm` is probably short-hand for normal, but this is poor naming.
> 1 votes

---
Tags: mathematics, vector
---


# Question
Title: Is there a need to set the parameters again when updating a texture?
Suppose that I'm developing the class COpenGLControl here in code guru to use it for showing a 2D texture in an MFC CPictureControl. and after applying some filters on the image, I will update the texture to show the filtered image on the picture control.

I have set a rule for the clients of my class as follows:

Call function `setImageWidthHeightType` just first time of calling `OnTimer` and after setting `pImage`
`pImage` is the rastetr data that will be provided by another classes that have been developed using OpenCV and GDAL libraries
for the next calls of `OnTimer` and when updating `pImage` there's no need to call this function. If you do so, your client code slows down because the function `InitializeTextureObject()` is called in the `setImageWidthHeightType` function
For second and more calls of `OnTimer` you should call `updataTextureObject()` function after setting `pImage`. In the first call of `OnTimer` and before calling `setImageWidthHeightType`, the function `updataTextureObject()` should not be called and if so, the program will encounter an unhandled exception because there you still don't have any texture object to be updated.

any way I have used the following codes for the functions that are mentioned above:

**OpenGLControl.h**
allocate texture name which will be an `unsigned integer`

```
GLuint texture;

```

**OpenGLControl.cpp**
Generate just one texture and bind it to the target:

```
void COpenGLControl::InitializeTextureObject()
{
    wglMakeCurrent(hdc, hrc);
    glEnable(target);
    glGenTextures(1,&texture);
    glBindTexture(target,texture);
    glTexParameteri(target,GL_TEXTURE_WRAP_S,GL_REPEAT);
    glTexParameteri(target,GL_TEXTURE_WRAP_T,GL_REPEAT);
    glTexParameteri(target,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
    glTexParameteri(target,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
    glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_REPLACE);
    glPixelStorei(GL_UNPACK_ALIGNMENT,1);
    glTexImage2D(target,level,internalformat,ImageWidth,ImageHeight,border,format,type,&pImage[0]);
    wglMakeCurrent(NULL, NULL);
}

```

the question that roses up is that
Is there a need to set the parameters again when updating texture because of using `wglMakeCurrent(NULL,NULL)` at the end of the function above?
In other words should I write the function `updataTextureObject()` as this:

```
void COpenGLControl::updataTextureObject()
{
    wglMakeCurrent(hdc, hrc);
    glEnable(target);
    glBindTexture(target,texture);
    glTexParameteri(target,GL_TEXTURE_WRAP_S,GL_REPEAT);
    glTexParameteri(target,GL_TEXTURE_WRAP_T,GL_REPEAT);
    glTexParameteri(target,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
    glTexParameteri(target,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
    glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_REPLACE);
    glPixelStorei(GL_UNPACK_ALIGNMENT,1);
  glTexSubImage2D(target,level,xOffset,yOffset,ImageWidth,ImageHeight,format,type,&pImage[0]);
    wglMakeCurrent(NULL, NULL);
}

```

Or just as this:

```
void COpenGLControl::updataTextureObject()
{
    wglMakeCurrent(hdc, hrc);
    glTexSubImage2D(target,level,xOffset,yOffset,ImageWidth,ImageHeight,format,type,&pImage[0]);
    wglMakeCurrent(NULL, NULL);
}

```

What way is the correct one?

# Answer
No, `wglMakeCurrent (NULL, NULL);` will not cause you to lose any state. What it *will* do is make any OpenGL call in the thread where you did this an invalid operation (until you make a device + render context current again).

So if you were to try to setup state during a period in which your calling thread has no current context, then you would have issues with state tracking. But in this code, I see no such situation.

Getting to your question about which function is valid, I am leaning towards ***neither***.

This is because some other part of your application may have changed the currently bound texture between the time you called `InitializeTextureObject (...)` and `updataTextureObject (...)`. At the very least you need to bind your texture before attempting to issue `glTexSubImage2D (...)`.

There is an extension called Direct State Access that avoids the nightmare of having to bind most OpenGL objects to modify their state. This is probably too advanced for you right now, but it is something to consider in the future. OpenGL's bind-then-modify design is quite frustrating at times.
> 1 votes

---
Tags: opengl, textures
---


# Question
Title: How to implement throw curve with virtual height in a 2D side-view game
I am working on a 2d side-view soccer game that looks like this image:

But now I stuck on how to implement parabola pass ball. I have found many questions corresponding to my problem:

But they all just tell how to draw parabola in simple 2d space. In my game, except for the normal `x,y` there is also a virtual height coordinate, so the final viewing position of the ball is:

`world position + current_height * Calc_Scale`. (**Calc\_Scale** is **0.3f**)

Currently I did it the following way: I calculate the pass time(T) and distance(D) from point **A** to **B**

```
the pct = current_time / T
current_height = D * (4* pct - 4 * pct* pct)

```

Unfortunately, it looks bad...

UPDATE: @ashes999 I tried quadratic equation like `current_height = D * (4* pct - 4 * pct* pct)`, it is not good(I am continuing to try different factors).I am pretty sure sin/cos can not work here, for example, player A is in(300, 200), B is(300, 800), the ball will make a direct line beyond B's head then drop to B's feet(or head), and this can not be done by cos/sin way, And I am thinking can this be done by some sort of projection, I just calculate the **x,y,z** then project z value into **y** axis?

```
void RSSoccerBall::Pass(const vector2d& target, double force)
{
vector2d DistVec(target - m_vPosition);
m_PassDistance = DistVec.getLength();
if(m_PassDistance > MaxShortPassDistance)
{
m_CurrentPassTime = 0.f;
m_PassTime = TimeToCoverDistance(target, m_vPosition, force, true);
}
}

void RSSoccerBall::update(float dt)
{
//for parabola calc
if(m_CurrentPassTime < m_PassTime)
{
m_CurrentPassTime += dt;
float pct = m_CurrentPassTime / m_PassTime;

m_Height = m_PassDistance * 0.7 *  (4 * pct - 4 * pct * pct);
}
vector2d    exactViewPos = m_vPosition; //m_vPosition is the 2d world position
exactViewPos.y += m_Height;
//render football at exactViewPos;
...
}

```

@Mario, These are my code ,I have used an extra variable to store height. - Determing an object's position along a curve over time this is where the equation from

I do not want the top of the arc always to be at 50% distance traveled, because player A and B probably not in same Y value, if B's Y value is higher than A's Y, the top of the arc will be exceed 50%. I found a wiki link: - http://en.wikipedia.org/wiki/Range\_of\_a\_projectile describe Ideal projectile motion on uneven ground, but the formulas are complicated for me to convert into current situation(we have start point, end point, start velocity, travel time)

Can anyone give me some pointers how to accomplish that?

# Answer
Your actual view of the ball or playing field shouldn't really matter in this.

* First of all, you'd mostly want a constant/fixed horizontal velocity for the ball. You can add air resistance to this, but it wouldn't really change anything, as you'll just have to add it to the equation.
* Ignore the actual height of the shot for now.
* Having a target distance as well as a velocity, it's rather trivial to calculate the travel time of the ball: `t = d / v`
* Now for making a nice arc you'll just have to set your initial vertical velocity right. You'll want the top of the arc to be at 50% distance travelled.
* To achieve this you'll need your gravity to completely negate that velocity once you arrive at half the distance. So for this you'll have to apply the max velocity the ball may achieve when falling down for the time it needs to travel there: `vy = -g * 0.5 * t`

Here's a simple jsFiddle showing you the overall idea. Note that the height of the arc depends on the time the ball needs to reach its target. Click anywhere in the playing field to kick the ball at that position. For a bit more accurate model (with friction), click here.

---

In case I haven't been clear enough:

* Behind the scenes your playing field should be a real 3D representation of the playing field.
* Only for drawing you collapse everything to the 2D representation that is shown on screen.
* This way you won't have to worry about any weird side effects, like doing complicated math, and you won't have to worry any fake height for your ball.
* Since the ball is the only element that can go into third dimension, you can simplify the whole game to be 2D (top-down playing field; only behind the scenes) and store your ball height in an extra variable.
> 4 votes

---
Tags: 2d, physics, cocos2d-x
---


# Question
Title: Increase Precision on multiplayer location drawin
I'm building a multiplayer snake-like game with Javascript. I'm having problems with the precision of the opposite players location not reacting fast enough. Which in turns makes the worm "crash", but only for some players, where the change in position happened too late due to latency.

My current game logic sends the change in direction, eg: "Up","Left" as soon as player #1 reacts.

Player #2 then receives Player#1 new direction, and sets his worm to now travel "up" (the direction received).

Since this introduces latency and that the change in direction might be applied too late, i'm wondering what other possibilities is available?

One might be to send current coordinates, or have the game loop on the server aswell, to make sure all movement changes is synced properly.

# Answer
> 2 votes
The best you can do is to make sure that you send as little data as possible while making sure that it's worth sending. As for the coordinates - I'd say that you can give it a try as I don't really understand why you haven't done that by now. So try sending both the direction and coordinates to the server which in return sends it to the other players. I guess that you could try checking the data on the server to make sure that no one is sending fake data or manipulated data.. ie.. check if the direction and location are a possible option for the player before sending them to the other players..

---
Tags: multiplayer, online, platform
---


# Question
Title: Can you use python, c and c++ in udk without plugins?
Im pretty new to game engines and i was wondering if I could use python, c and c++ in udk. I've tried getting the answer all over the internet but the answers i do find aren't very clear. So am i able to use the aforementioned languages without the use of plugins or special downloads, and please mention any other languages already built into udk.

# Answer
> 2 votes
For the majority of everything you should be doing in UDK, gameplay wise, you will be coding in UnrealScript. UnrealScript is its own language which resembles Java and C++. You can control the player, the camera, create and modify items, and even extend the editor with custom Kismet actions among other things with UnrealScript. It's really powerful and will likely fit most of your needs. The biggest thing I've seen people be limited on with UnrealScript / out of the box UDK is networking since there is a limit of 64 players per server.

That being said there is a feature called DLL Bind which allows you to call functions from DLLs. This is then implemented by calling the methods from UnrealScript code. This is how you can go beyond the hard limitations of the engine without getting access to the source code, but you'll be starting from scratch and rather limited to how you implement your custom systems because you are bound to calling these methods from UnrealScript as much as possible.

Outside of this, if you actually want to view / write source code for UDK in C/C++ you have to purchase a full Unreal Engine license which is generally way out of anyone's price range with the exception of those with AAA budgets.

So to finally answer your question: you can kind of sort of use other languages (C/C++ being the main ones) but you really should stick to UnrealScript.

---
Tags: c++, python, c
---


# Question
Title: what's the best way of panning in a 2D scene
Up to know I have used this functions to create a 2D scene (for showing images) and to pan on it ( in fact it's a customization of the class COpenGLControl here in codeguru) :

```
void COpenGLControl::OnSize(UINT nType, int cx, int cy)
{
wglMakeCurrent(hdc, hrc);
CWnd::OnSize(nType, cx, cy);

if (0 >= cx || 0 >= cy || nType == SIZE_MINIMIZED) return;
oglWindowWidth = cx;
oglWindowHeight = cy;
// Map the OpenGL coordinates.
glViewport(0, 0, oglWindowWidth, oglWindowHeight);

// Projection view
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Set our current view perspective
glOrtho(-oglWindowWidth/2, oglWindowWidth/2, oglWindowHeight/2,-oglWindowHeight/2, -1, 1);
// Model view
glMatrixMode(GL_MODELVIEW);
wglMakeCurrent(NULL, NULL);
}

void COpenGLControl::OnDraw(CDC *pDC)
{
wglMakeCurrent(hdc,hrc);
// If the current view is perspective...
glLoadIdentity();
glScalef(m_fZoom,m_fZoom,1.0);
glTranslatef(m_fPosX, m_fPosY, 0.0f);
wglMakeCurrent(NULL, NULL);
}

void COpenGLControl::OnMouseMove(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
int diffX = (int)(point.x - m_fLastX);
int diffY = (int)(point.y - m_fLastY);
m_fLastX = (float)point.x;
m_fLastY = (float)point.y;
if (nFlags & MK_LBUTTON)
{
    m_fPosX += (float)0.5f * diffX;
    m_fPosY -= (float)0.5f * diffY;
}
OnDraw(NULL);
CWnd::OnMouseMove(nFlags, point);
}

```

**pressing left mouse button and draging on the window, will cause the image to pan**
In fact the COpenGLControl classis for 3D scenes and the disadvantage of this way for 2D scenes is that when I zoom in, I feel the speed of `pan` is more than the time that I zoom out?
I mean **zooming in** increases the speed of pan while **zooming out** decreases it.
Do you know of any way better for continuous panning in a 2D OpenGL scene?

# Answer
> 2 votes
I can think of two ways to solve the bug.

1) Instead of simply adding the difference to the current position you add a modifier, that is dependent on the zoom value. The modifier decreases, when you zoom in and increases when you zoom out. The modifier should be related to the inverse of the zoom factor, if not the inverse itself. Reason: the pan speed increases when you zoom in, so you simply counteract on that behavior.

2) Instead of using a real 2D scene with ortho you could actually make a 3D scene. The camera looks at a 2D plane, which is your scene. Panning is still just adding the difference to the translation. For zooming, however, you move the camera nearer or further away from the 2D plane. This should avoid the bug, which stems from the fact that you actually scale the scene when zooming instead of moving the camera.

ad 2) Placing items in the scene and so on should still be as easy as in real 2D. You can place the scene on the z=0 plane, and use the usual 2D coordinates for positions and so on.

---
Tags: opengl, 2d, visual-studio
---


title: How to use elapsed game time for timing

text:
# Question
Title: How to use elapsed game time for timing
I want that my ship shoots beam after every 2 seconds. How do I make that happen? and also I want that after 50 shots I want to give 10 seconds to reload the gun. I know both of my problems can be solved by `gameTime.ElapsedGameTime` but how should I use it?

# Answer
> 4 votes
You can use `gameTime` in the following manner along with 2 accumulator variables to store the time since the last shot and the number of shots taken since reload.

`gameTime.ElapsedGameTime.TotalSeconds` represents the elapsed time since the last time the Update method was called (the time since last frame). If you accumulate each of these times (add them up each frame), they will eventually add up to the 2 second interval that you want to wait until your next shot. Once the shot has been fired, reset that accumulator back to zero and wait for it to add up to 2 again.

Additionally, you can keep track of the number of shots each time a shot was fired and when that number gets to 50, reset that `timeSinceLastShot` accumulator to -8. That way, it will take 10 seconds before the accumulator reaches the 2 second mark to initiate a new shot.

```
//class scope field
int numShotsFromCurrentMagazine = 0;
float timeSinceLastShot = 0f;

//in the update method
timeSinceLastShot += (float)gameTime.ElapsedGameTime.TotalSeconds;

if(timeSinceLastShot > 2f)//if it's been 2 seconds since this was reset to zero, initiate another shot
{
  Shoot();
}

if(numShotsFromCurrentMagazine == 50)
{
  timeSinceLastShot = -8f;//since magazine is empty, set accumulator to -8 so it will be 10 seconds before it gets to the required 2 and initiate the next shot
  numShotsFromCurrentMagazine = 0;//reset the magazine.
}

//stand alone method
void Shoot()
{
  //code that shoots beam here
  numShotsFromCurrentMagazine += 1;
  timeSinceLastShot = 0f;
}

```

---
Tags: xna-4.0
---


# Question
Title: Cascaded Shadow Maps: clipping against scene bounds
I just implemented an initial version of CSMs based on the MSDN articles Common Techniques to Improve Shadow Depth Maps and Cascaded Shadow Maps.

I fit the shadow projection to the view frustum, and do not clip against the scene bounds, because in Common Techniques to Improve Shadow Depth Maps it is stated:

> It is also possible to clip the frustum to the scene AABB to get a tighter bound. This is not advised in all cases because this can change the size of the light camera's projection from frame to frame. Many techniques, such as those described in the section Moving the Light Texel-Sized Increments, give better results when the size of the light's projection remains constant in every frame.

However, in the paper from the Nvidia SDK the frustum is further clipped against the scene bounds to achieve a maximum used area for the shadow map.

This confuses me. Did the guys from MSDN miss something, is the Nvidia paper simply older or am I not understanding the Nvidia approach correctly?

**Edit:** I was right in not understanding the Nvidia approach, basically not at all. I confused the crop matrix with a clipping against scene bounds.

# Answer
The MSDN statement is correct; it's usually not useful to clip to the scene bounds.

First of all, in a "real" use case you probably have a large game world where the scene is much bigger than the view frustum, so clipping to the scene bounds won't even do anything. In a small scene, such as in a test world, you could get better shadow resolution by clipping to the scene bounds, but it wouldn't be representative of the shadow resolution you'd get in a larger world.

And, as they mention, depending on how the clipping is done, the shadow resolution might change as the camera rotates around. (It would also change if the scene is animated in such a way that its bounds change over time.)

I didn't see anything in the NVIDIA paper about clipping to the scene bounds.
> 1 votes

---
Tags: graphics, shadow-mapping
---


# Question
Title: Are there any pathfinding algorithms that would handle different movement types?
I'm developing a bot for a BattleTech board game simulator http://en.wikipedia.org/wiki/BattleTech, it is turn based.

The board is divided into hexagons, each one has a different terrain type and elevation. You drive a robot which moves over them, to destroy other robots.

I only know Dijkstra and A\* pathfinding algorithms, but the problem is that there are 3 types of movements: walk, run and jump several hexagons (each of them have their own rules). Walk and run are almost the same.

The best path could be a combination or each movement type. Here is an example of map http://megamek.info/sites/default/files/isometric\_view.png

**Do you know a good algorithm for this complex pathfinding or a way to combine A\* results for each movement type?**

# Answer
> 10 votes
Both Dijkstra and A\* can add different costs to the edges (=connections) from one tile to another. They also allow to connect two nodes (=tiles) with more than one edge, each one with a different cost.

The alternative jump-mode would mean that there is an alternative direct edge from each tile to each tile in jump distance. But because a mech can either walk or jump in a turn, the cost for using this edge would be the move points of a whole turn, plus the remaining points of the current turn when there already was a move this turn.

According to your description, the decision for walking vs. running does not make much of a difference regarding path choice, but it rather seem to be a strategic decisions to make. The actor definitely can walk when the destination can be reached in the current turn without resorting to running. But otherwise there are many factors to factor in, like:

* current heat level and likeliness of being involved in combat before being able to cool down
* difficulty of any shots which need to be fired this round
* how strategically important it is to reach the destination quickly

There is no hard rule for making this decision. The best you can do is to use a heuristic approach. Assign positive or negative point values to all circumstances, add them up, and see if the result is positive or negative.

There is also another factor in pathfinding you should account for: Under some conditions it could make sense for a mech to avoid ending its turn at certain locations. When in a danger area, using three turns to get from A to B but ending each one in cover might be better than using only two, but being exposed at the end of each. Or maybe not. It depends on the circumstances and the exact game mechanics. This, again, is a strategic decision you have to make based on heuristics. You could represent this by adding an additional cost to edges which end the turn on a dangerous tile to discourage the AI from making this move.

---
Tags: ai, movement, path-finding
---


# Question
Title: Full map image loading, vs individual tile loading
I want to make a isometric tile game in java, like a lot of strategy games out there. What is the best approach to loading the map for this game? Would it be better practice to load one single image for the whole map, or would it be better to make images for each tile and render each tile using a int array?

# Answer
Its way easier to use a spritesheet. Then just draw a section of the sprite sheet based on an array. This way you only load one image for the entire tilemap. Look into programes like Tiled if you want to tool to build tilesheets.

Tiled.
> 2 votes

# Answer
If you use multiple textures, you will need to switch them in rendering. This process is expensive. You better use a single texture and use a index to represent each tile, with that index and tile size, you can calculate UV Textures to apply in your tile meshes.
> 1 votes

---
Tags: java, rendering, tiles, tilemap
---


# Question
Title: timezone independant Date.now() for node.js game
I have a game I'm working on using node.js and socket.io. The issue I'm having, is I'm trying to have it so that players execute whatever actions they inputed about 50ms in the future, giving everyone a chance to stay relatively in sync.

I've got frame-independant code running, which works well until a client has a different time than the server.

to predict when the client should act out movement code from the server, I use

`Date.now() >= command.timeStamp`

The issue I'm having is that the client isn't in the same timezone as the server, for instance someone I'm testing with is just one minute above/below my server time, resulting in commands being 900 milliseconds in the past or future, which is non-ideal.

Is there some way I can use a common timestamp across clients and server?

# Answer
> 2 votes
Your game timing system should have its own internal clock that is started when the game begins (this can be setup by the server to force clients to be the same). Have you considered using this internal timer? It would be valid, and the same across all clients.

# Answer
> 0 votes
Yes, you can use unix time on all the clients, or you can use the same time zone on all the clients, likely UTC, Javascript has a function to help with this.

# Answer
> 0 votes
The correct answer to your underlying question may be to just *not use* `Date.now()` and instead use `requestAnimationFrame` or `performance.now()` on the client and `process.hrtime()` on the server. The former two are much newer and less widely supported but can give you more accuracy than `Date.now()` can, which is a serious issue for most Web games (especially if the game is real-time or uses canvas animations). `requestAnimationFrame` at least is in the current versions of all major browsers, though still prefixed for a few of them. The NodeJS one has been available for some time.

See https://stackoverflow.com/questions/6875625/does-javascript-provide-a-high-resolution-timer for some more information, as well https://developer.mozilla.org/en-US/docs/Web/API/PerformanceTiming.now and https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame.

For NodeJS (I'm unclear if you're timing in the server or the client portion), you can't use `requestAnimationFrame` obviously. You have http://nodejs.org/api/process.html#process\_process\_hrtime or https://npmjs.org/package/performance-now (which wraps the former) for NodeJS timing.

---
Tags: javascript, node.js, websocket
---


title: Button - change texture after click

text:
# Question
Title: Button - change texture after click
I need to make a button with texture. After button is pressed I want to change texture of button permanently. For example on/of sound button. I tried this but it changes image only while I hold button.

Thanks

```
mSoundButton  = new ButtonSprite(30, 30,
                    ResourceManager.getSoundButtonTR(),
 //tiled texture region with image for sound on and sound off
                    ResourceManager.getEngine().getVertexBufferObjectManager()) {
        @Override
        public boolean onAreaTouched(TouchEvent pTouchEvent,
                                     float pTouchAreaLocalX,
                                     float pTouchAreaLocalY) {
            if(pTouchEvent.isActionDown()) {
                SFXManager.toggleSoundEnabled();
                this.setCurrentTileIndex(1);
            }
            return super.onAreaTouched(pTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY);
        }
    };
    mScene.registerTouchArea(mSoundButton);
    mScene.attachChild(mSoundButton);

```

# Answer
> 2 votes
this solution works for me:

```
mSoundButton  = new ButtonSprite(30, 30,
                                     ResourceManager.getSoundButtonTR(),
                                     ResourceManager.getEngine().getVertexBufferObjectManager(),
                                     new ButtonSprite.OnClickListener() {
                @Override
                public void onClick(ButtonSprite pButtonSprite, float pTouchAreaLocalX, float pTouchAreaLocalY) {

                    SFXManager.toggleSoundEnabled();
                    mSoundButton.setCurrentTileIndex(SFXManager.isSoundEnabled() ? 0 : 1);

                }
    });

```

---
Tags: android, andengine
---


# Question
Title: Setting a displacement or offset between Snake segements
I have a problem in maths or I do not know. I have drawn few circles that simulates the body of a snake, the head of the snake moves and others should follow. but the is no offset or displacement between the circles, because the current code sets the previous position of the nodes to the current, when I add few numbers to both x, y axis, the body segments get distorted. How do I set the offsets between the segments?

```
for ( int i = 0 ; i < nodes.size(); i++ )
{
    if( i == 0 )
    {
        // Do calculations for new position

        //Set position and previous position
        nodes[i].m_PrevPos.x = nodes[i].m_Pos.x;
        nodes[i].m_PrevPos.y = nodes[i].m_Pos.y;

    }
    else
    {
        nodes[i].m_PrevPos.x = nodes[i-1].m_Pos.x;
        nodes[i].m_PrevPos.y = nodes[i-1].m_Pos.y;
        nodes[i].m_Pos.x = nodes[i-1].m_PrevPos.x;
        nodes[i].m_Pos.y = nodes[i-1].m_PrevPos.y;
    }
}

```

I would like also to check the head's node velocity for example:

```
 if ( nodes[0].m_Pos.x < 5 )
    {

        nodes[0].m_Vel.y = -2;
        nodes[0].m_Vel.x = 0;

        if(nodes[0].counter--<1)
        {
            nodes[0].m_Vel.y = 0;
            nodes[0].m_Vel.x = -2;
            nodes[0].counter = 5;
        }

    }

```

# Answer
In fact you don't need to calculate offset for each part in each iterate.

just do it for first part. (How?)

```
for ( int i = nodes.size()-1 ; i >= 0; --i )
{
    if( i != 0 )
    {
        // Here Do not think about offset. just follow old position of next snake part
        nodes[i].m_Pos.x = nodes[i-1]m_Pos.x ;
        nodes[i].m_Pos.y = nodes[i-1]m_Pos.y ;
    }
    else
    {
        // Do calculations for new position "with a proper offset".
        // Is your question about how to calculate this offset ?
        nodes[0].m_Pos.x = .. ;// calculated position
        nodes[0].m_Pos.y = .. ;// calculated position
    }
}

```

About New head's position calculation;

Assume current head's position is (x,y). so new position simply can be calculate like this:

and more specific :
> 3 votes

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


# Question
Title: How to calculate where specular highlights converge with an anisotropic shader?
If you look at a rendering with an anisotropic shader applied you will notice that there are special spots on the 3D surface/mesh where the lights seems to converge, a point where a given vector radiates from or converges to.

For example:

The specular highlights seem to converge to the corner of the mouth.

Now given a 3D mesh I would like to calculate those points programmatically: what is the formula for that in linear algebra with vectors ?

# Answer
> 3 votes
Anisotropic lighting requires in addition to normal and texture coordinates also tangent and bitangent vectors for the geometry. These can be calculated from the texture coordinates or created in some other ways. The places where the anisotropic highlights converge are "singularities" of the tangent / bitangent vectors.

As an example see the picture below with anisotropic lighting. The center of the disk is the singularity. The circles with different shades of gray are coming from a 1D texture map, where the angle (V coordinate) is ignored and the radius (U coordinate) determines the sampling location. The tangent vectors follow the circles and bitangent vectors are always pointing outside from the center. These vectors are not uniquely defined in the center thus causing the singularity. Due to this the lighting highlights also converge to the center.

Note that for arbitrary surface with only the normal information anisotropic lighting cannot be used. This is because anisotropic lighting by definition behaves differently in one direction compared to another. E.g. in brushed metals it's defined by the brusing direction as illustrated in my example picture. It's possible to generate the tangents and bitangents out of nothing just like texture coordinates, but there is no single correct way to do that.

What comes to your actual question on how to find these spots algorithmically, that depends on what information you have available and how the anisotropy is defined for the model. If you have the tangent and bitangent vectors, you need to find out vertices where they are not uniquely defined. I don't have an algorithm for this, but I think one way would be finding overlapping vertices with the same coordinates but different tangent and bitangent vectors. In the given example the information might not be available, as it looks like it would converge in the mouth. However there is a hole in there, so the geometry of the singularity is actually missing and it's impossible to tell for sure if they would actually converge or just get very close to eachother if the mouth was there.

---
Tags: vector, 3d-meshes, linear-algebra
---


title: Large game project, local variables

text:
# Question
Title: Large game project, local variables
I'm hoping that some experienced programmers can give me their point of view. I'm writing a large game in Windows with dx11. So far, I've got global objects of the class that interfaces with dx11, the class holding the position of the camera, the terrain data class, and a few other classes. In future, if I kept going with this way, I'd also have objects for all the game data, and so on.

I'm thinking it might be best to rejig the code to only have local variables, because generally this is regarded as a Good Thing, but mainly because I personally have come to prefer using them. Here's some rough c++-ish pseudo-code of how I imagine local variables would be implemented:

```
WinMain()
{
  cDirectX dx;
  cCamera cam;
  cTerrain terrain;
  ...
  while (msg.message != WM_QUIT)
  {
    ...
    gameLoop(dx, cam, terrain, ...)
  }
}

void gameLoop(cDirectX &dx, cCamera &cam, cTerrain &terrain, ...)
{
  ...
  renderTerrain(dx, terrain);
  ...
}

```

Is this (very roughly!) a good way to organise such a project? I suppose WinMain is the only function where the locals can be instantiated?

The only disadvantage I can see is that top level function calls (by which I mean, functions like gameLoop(), functions at the bottom of the call stack) will have very long lists of arguments. Perhaps this doesn't matter.

Thanks, Paul

# Answer
> 4 votes
The thing that breaks complicated programs is not complexity. It's *dependencies*.

The main advantage of not using singletons, globals, etc etc is that it significantly reduces what I've termed "spidering dependencies", where global variables are used throughout the code. Making any modification to how those systems work fraught with the possibility that some other downstream system may be relying on a particular behaviour.

So, what you want to do is work on minimising dependencies between subsystems.

For example, I've seen many games where randomly within the physics system the global HUD subsytem will be retrieved and have data poked to it, or worse, animations in the HUD started from the physics system itself, meaning any change to the way the HUD spawns animations may break something in the physics engine!

There's a few ways to "fix" this. All solutions stem from clearly defining the boundaries for your subsystems, and understanding what data needs to flow in, and out of them.

I'm a big fan of asynchronous messaging as part of this solution, as it removes the concept of "immediate" from the game engine. You have to request things from other subsystems, which will be fulfilled at some point in the future. So your systems must be able to deal with an intermediate state. (eg: resource requests result in an intermediate "ghost" resource which is handed across while the actual resource is loaded).

I'm also a fan of using intermediate layers between subsystems, such as our HUD and physics engine. The HUD should never be responsible for changing game state directly (it should post an asynchronous message when *something* has happened which is then handled by the game state) and it should certainly not know about anything in the physics engine. Our physics engine still needs a way to, for example, post the speed of the player to the HUD. So we can achieve this by posting to an intermediate layer under a "key". the HUD can then query this layer using the same "key" to retrieve the data. The HUD then does not know, or care about how the data reaches this layer, just that the data is there.

So, TLDR: try and minimise dependencies. Removing the use of globals is a good step. However, if you're just making a small game this may be more overhead than it saves, but always focus on keeping unnecessary dependencies to a minimum!.

# Answer
> 1 votes
Well... as for DX instance, there will be only one (I suppose), so it should be declared globally. For the rest. Terrain should be part of some "model pool". So basicly, sou have all models at one place (this pool can again be globaly - as singleton). And you can obtain models from that pool. Camera goes with your scene management. Usually, there will be only one camera. But for some purposses (water, shadows etc.) you may have different camera (projective and view matrix resp.). In that case it will be better to have some kind of rendering manager, that will hold informations, what you are rendering and which camera to use.

In my engine, I do it this way:

```
SceneManager.setRenerer(dx); //I have engine multiplatform, so there also could be gl, gles...all rendering is done via abstract classes and main functionality is hidden for "user" of engine
SceneManager.addRenerableObject(terrain, "Terrain");
SceneManager.addRenerableObject(house, "House#1");
SceneManager.addRenerableObject(player, "Player");

SceneManager.bindPlayerToObject("Player")

SceneManager.UpdateCameras(); //each camera is updated based on binded player position and rotation

....

SceneManager.RenderAll();

```

---
Tags: software-engineering
---


title: Game Trailer Reference other Games

text:
# Question
Title: Game Trailer Reference other Games
I am currently developing a game that pulls in the basic ideas and concepts from 3 other games. I want to make a trailer, and can I put in the trailer something like this:

> Pulling Game Concepts from: ...Pokemon ...Fable ...and Harvest Moon

Can i do this? Or would I have to get permission to even reference them?

# Answer
> 3 votes
IANAL, this is not legal advice, gamedev.SE is not a good site for legal Q&A.

You may have noticed that most promotional material either avoids mentioning competitors, or avoids mentioning them by name.

Example (Colgate):

> "Tastes better than the leading competitor"

I believe this issue is covered on the Wikipedia article Comparative Advertising. While it's perfectly okay in most jurisdictions, usually there are strict standards on how factual or truthful the comparison is, and it must not be misleading. Of course this can be up to interpretation, so in order to avoid legal liability, most companies just avoid directly naming the comparison, even if it's blatantly obvious. Your competitors could have many reasons to stop you from mentioning them too, for example to avoid being associated with your product, or to control the image of their own product.

I know that sometimes it's very convenient to describe your product in terms of other products; "it's like Minecraft with an Angry Birds vibe and a Starcraft-esque lore!" your elevator pitch might go. Professionalism issues aside, you can try mentioning genres and game design buzzwords instead. Examples include *sandbox*, *persistent world*, *action role-playing*.

# Answer
> 0 votes
Using the names of other games should be OK under fair use, specifically nominative fair use. Where the qualifications for nominative fair use are one of the following situations:

> * The product or service cannot be readily identified without using the trademark (e.g. trademark is descriptive of a person, place, or product attribute).
> * The user only uses as much of the mark as is necessary for the identification (e.g. the words but not the font or symbol).
> * The user does nothing to suggest sponsorship or endorsement by the trademark holder. This applies even if the nominative use is commercial, and the same test applies for metatags.

Make it clear that you're not doing anything to suggest sponsorship or endorsement. You're just using the name of the game to identity those games. Also ensure you're not using their logos in your trailer. Use a plain text to display their names along with the text saying how users should compare your game to those ones. Look up how to properly use fair use of a trademark to ensure you're properly crediting the other games.

This fair use is something you'll regularly see at grocery stores, when an "off brand" product is asking shoppers to compare their product to a well known brand:

**See the lower right text:**

---
Tags: legal, trailer
---


# Question
Title: LibGDX Scene2D event handling and bounding box relative to the center of a TextureRegion
I'm experimenting with Scene2D to see if it fits fot the game I want to develop. Say I have an Actor with the origin in the center of its TextureRegion.

My setup method contains this code:

```
float width = WorldUtils.pixelsToMeters(Assets.bullet.getRegionWidth());
float height = WorldUtils.pixelsToMeters(Assets.bullet.getRegionHeight());

setPosition(x, y);
setOrigin(width / 2, height / 2);
setSize(width, height);
setRotation(angle);

```

Where `WorldUtils.pixelsToMeters(float)` is just a method to convert pixels to world units (basically 64px = 1 meter).

My draw() method is like this:

```
@Override
public void draw(SpriteBatch batch, float parentAlpha) {
    batch.setColor(getColor().r, getColor().g, getColor().b, getColor().a);
    batch.draw(Assets.bullet, getX()-getOriginX(), getY()-getOriginY(), getOriginX(), getOriginY(),
               getWidth(), getHeight(), 1, 1, getRotation());
}

```

This way the actor's position is equal to its center position. This simplifies a lot of stuff like moving the actor to a specific (x, y) in the game world. Otherwise everytime I have to use this actor's position I have to take in account for its screen representation's size... and it doesn't make much sense.

But the way I setup things come at the cost of messing up with event handling. From what I understand Scene2D event handling assumes I'm using (0, 0) as origin of the actor's bounding box. So when I touch/click on my actor during execution it can handle only the ones slightly up-right it real position (obviously).

Is there a way to fix this without touching the library code? I would like to handle certain objects with origin in the center and others with origin in the bottom-left corner.

Maybe I misunderstood how to setup my actor?

# Answer
> 2 votes
Answering my own question:

Looking at Actor's code, it seems to be as simple as overriding the default `hit()` method.

The original code is:

```
public Actor hit (float x, float y, boolean touchable) {
    if (touchable && this.touchable != Touchable.enabled) return null;
    return x >= 0 && x < width && y >= 0 && y < height ? this : null;
}

```

While my new code is:

```
public class NewActor extends Actor {
    @Override
    public Actor hit(float x, float y, boolean touchable) {
        if (touchable && getTouchable() != Touchable.enabled) return null;
        return x >= -getOriginX() && x < (getWidth() - getOriginX())
                && y >= -getOriginY() && y < (getHeight() - getOriginY()) ? this : null;
    }
}

```

It's worth mentioning that `hit()`'s x and y are relative to the Actor position, so I just translate the original bounds check by (-getOriginX(), -getOriginY()).

---
Tags: java, libgdx, events, scene-graph, bounding-boxes
---


title: Expandable player boundaries

text:
# Question
Title: Expandable player boundaries
I'm trying to plan how to implement non-fixed boundaries so the player can expand their controlled territory without using a tiled based system. Each pixel can be fought over for who controls it.

I will need to set the color for each pixel depending on who controls it so I'm thinking I'll have to check each pixel for who controls it every refresh?

I'm not sure what the best way to do this and I think performance would be an issue

Any suggestions?

# Answer
> 2 votes
Sounds to me like it's still a tile-based system, but with each pixel being a tile...

Regardless, caching is your friend.

Personally, I would split the map into regions, then cache each as an individual image. In your code, whenever control in an area shifts at all, set a flag saying that area needs to be updated. You'll have to experiment with different region sizes to determine what provides the best performance based on your game mechanics - if you end up with a single battlefield in the middle where all the change is happening, that's going to require different regions than, say, isolated pockets of resistance.

On the other hand, if you have most of your pixels shifting every frame, you may be better off checking every pixel every frame, and possibly skipping some frames if the performance is too unwieldy.

---
Tags: opengl, java, color, pixel
---