title: Does Big O really matter?

text:
# Question
Title: Does Big O really matter?
In academia worst case **Big O** is taught over everything else. Compared to space complexity, normal case analysis, simplicity over complexity, etc.

In particular to game programming and industry, what really matters most and why?

*References would be very helpful.*

# Answer
> 25 votes
As with *every other question* regarding "what's the One True Path", these are all tools in your toolbox and there are cases where big-O trumps everything, and places where it doesn't matter(tm).

You would "never" write a physics solver without being concerned about big-O. You wouldn't implement a sorting algorithm (for any but the smallest of datasets) without being concerned about it. If you're writing a networked game, you're going to be concerned with the way performance and network traffic scales per user.

You might not be so concerned about big-O when, well, I can't really think of a time but I'm sure there are some. :) Thankfully, most of the things that we do in games scale linearly; you want to read a file off of disc? It'll take an amount of time linearly proportional to the file size (discounting the constant factor of seeking and possible ramifications of sector size).

However, what if you want to find a specific entity in the entity list? That's a linear search each time you do it. If you need to find the player once for every entity in the world, this approach will kill you for all but the most trivial of games, and even then it's probably worth "optimizing" this lookup to be constant time (e.g. store off the index of or a pointer to the player somewhere), giving you more time to do other things that actually are visible to the player.

I guess that sums it up, though; any time the processor is doing something that isn't directly representable to the player, it's wasting time. Maximizing the amount of time that the processor is computing data that will be shown to the player is maximizing the *WOW!* you're giving the player.

# Answer
> 13 votes
My rule of thumb is that unless you're O(scary), your other issues are more pertinent.

My other rule of thumb is that data is king. Unless you profile your code with a realistic data set you're just making guesses.

*Edit:* To go into a little more detail, your big O isn't that important since (at least in my experience) most of your data sets are relatively tiny. You probably don't care about your upper bound of performance when you're working with a data structure with fewer than a few hundred elements. And if your lists have 100k+ elements then you really need to consider all aspects of your algorithms. That, and from my experience memory is more of a limiting factor than CPU speed. A faster memory hogging algorithm might not be as good as a leaner but slower one depending on your use cases.

# Answer
> 8 votes
Big O matters most of the time, but sometimes an apparently "worse" algorithm in theory turns out to be much faster in practice.

Check out a great example from Tony Albrecht: http://seven-degrees-of-freedom.blogspot.com/2010/07/question-of-sorts.html

You find this all over the place in games development where the number of items in the operation is either so large that a very different algorithm is quicker, or so small that a dumber algorithm is sufficient (or fits in cache so well it overrides the efficiency of the *better* algorithm).

The problem with Big O is that it's a generic designation of complexity of the task and doesn't take into account the complexity of modern target hardware, nor does it offer any insight into the setup time overhead.

In many cases, the best optimal solution is two step. In practice, games developers tend to tend towards low O algorithms but balanced against cost in time developing, or debugging. Once you have a reasonable solution you always have to look at how the hardware is handling the task, and how to let the hardware get more done in less time.

# Answer
> 7 votes
When I'm coding in-engine, I'm often only concerned with a fixed `n`: I've already got a spacial partition limiting the number of objects receiving `update()`, `physics()`, and `render()` to approximately those on screen and surrounding areas. The maximum batch size is usually pretty well-defined per-game, although it invariably is a little bit larger than you've planned.

In this case I'm not as much concerned with big-O as I am concerned with the constant factor multiplier and lower-order terms. For a function with runtime like `a*n^2 + b*n + c` (which is `O(n^2)`), I'm often much more concerned with reducing `a` and possibly eliminating `c`. A setup or teardown cost `c` may become proportionally large vs. a small `n`.

However, this is not to say that big-O (or more particularly big-theta) is a great code smell indicator. See an `O(n^4)` somewhere, or worse yet an `O(k^n)` geometric time, and it's time to make sure you're considering other options.

I'm generally much more concerned about big-O optimality and jumping through hoops to find algorithms with lower big-O when I'm dealing with data make tools. While the number of objects in a given level/streaming area generally is well-defined, the total number of objects/art assets/configuration files/etc across an entire game may not be. It's also a lot larger number. Even running a parallel data make, we still wait on the order of a minute (I know, whine whine -- data make for consoles can take hours -- we're mostly small handheld games) to go through a `jam data-clean && jam data` cycle.

To give a specific example: this got really out of hand with a background tile-streaming algorithm that streams 8x8 256-color tiles. It's useful to share streaming buffers between background "layers", and we might have up to 6 of them in a given level sharing the same buffer. The problem is that estimating the size of the buffer needed is based on the possible positions of all 6 layers -- and if they're a prime-number width/height/scroll rate, you quickly start getting into an exhaustive search -- which starts approaching `O(6^numTiles)` -- which is in the "longer than the universe will be around" category in many cases. Fortunately most cases are just 2-3 layers, but even then, we're up above half an hour runtime. At the moment, we sample a very small subset of these possibilities, increasing granularity until a set amount of time has passed (or we've completed the task, which may happen for small double-layer configurations). We bump this estimate up a bit based on prior statistics of how often we've been proved wrong, and then add a bit of extra padding for good measure.

One other fun example: on a PC game a while back, the lead engineer experimented for a while with skip lists. The memory overhead ends up causing more cache effects, which adds a sort of non-constant multiplier to the whole affair -- so they're really not a good choices at all for small `n`. But for larger sorted lists where searches are frequent, they provide a benefit.

(I often find that the naive algorithm is higher big-O, faster on smaller data sets, and easier to understand; the more interesting/complex ones (e.g. patricia trie) are harder for people to understand and maintain, but higher performance on larger data sets.)

# Answer
> 4 votes
It can be handy, but it can also be irrelevant. Take, for example, my most recent game, which is something of a Smash TV clone. Top-down game, monsters pour in from the sides, you shoot them.

Now there's a lot of clever ways to determine collisions. You can use KDtrees to partition out the space so you're not testing bullets against monsters that they couldn't possibly hit. And, sure, I could have been clever, and I could have done that.

But I was feeling lazy so I just compared every bullet against every monster. Even in the most hectic situations, the collision code was using far less than 10% of the game CPU at 60fps. Big-O: Unimportant.

Similarly, I had a 4x-style game where you built cities on islands, and sometimes the cities got destroyed. I could have been clever and tried to subtract the destroyed city's income from the income variables. But I didn't. I just wiped out the income and recalculated it from scratch every time something changed. Totally irrelevant in terms of CPU.

Big-O is just as important in games as it is in everything else: that is to say, utterly unimportant, right up until it becomes critical.

Go write some code. If it's too slow, then profile it.

# Answer
> 3 votes
Big-O analysis is important, but it's not the first thing to think about in game development. Since making games involved lots of complicated code, I'd always recommend **Code Simplicity** as the first criteria for an algorithm. Algorithms with complicated bookkeeping just waste your time.

I think it's really important that your game always run at 60 fps during development. When you dip below that, the first thing you do is run a profiler. Once you find the bottleneck, you attack it. A lot of the time you need to do non-coding stuff like tell level designers to put less stuff in an area (and give them them tools for that).

Sometimes you actually identify some code that needs to be sped up. I find this to be fun engineering! I wish I had more opportunities to do this. And of course you want to iterate changing one thing at a time and measuring performance. The tipical problems I find are:

1. Make sure you aren't calling new or malloc each frame (this is always the #1 problem)
2. Reduce work: fewer ray casts, less guys, etc.
3. Big-O algorithm type problems
4. Cache coherency: Put stuff in arrays rather than scattered memory
5. Don't use STL in debug mode. (and you always want debug mode to work)

# Answer
> 2 votes
Big-O notation is by definition asymptotic complexity - i.e., it shows how time scales when N (or whatever variables you have) gets "very" large. To re-iterate on Tetrad's comment (which I upped) "data is king". If N is "very large" in your specific situation, it matters, if N is "very small" it doesn't matter. Experience and practice will give you a feel for how to quantify "very large" and "very small".

Obviously, always profile first, and optimize last (unless you are doing a feature feasibility study).

# Answer
> 1 votes
The importance of Big-O in your software is O(N2). As N grows, the importance of having the right algorithm grows even more. :)

# Answer
> 1 votes
Big-O is just a guideline -- something that tells you the rough performance you can expect from an algorithm -- **and how you should expect performance to scale as you increase the size of the dataset**. You have to remember two main things with regard to Big-O:

1) If you have two algorithms that mostly do the same thing but one has a better O, you should probably go for that one (obviously)

2) Big O is concerned with **asymptotic analysis**. Big-O only really comes into play **when n is large**. For example, an O(n) algorithm can be very similar in performance to an O(n^2) one .. **for small n**. If you're talking about an algorithm that requires n^2 operations per vertex, but n=2 or n=3, then there **is not** much difference between an O(n^2) algorithm (taking 4 and 9 ops resp) and an O(n) one (2 and 3 ops resp.). However, if n=9, then you are suddenly talking about 81 operations for the O(n^2) algorithm and only 9 for the O(n) one -- a bigger difference -- and if n=100, then you are talking about 100 ops vs 10000 -- a much bigger difference.

So you must always consider Big-O in that light: it is meant to compare algorithms that do the same thing **based on worst case performance** ***as n gets large***. The differences between the algorithms may be all but negligible when n is very small.

# Answer
> 0 votes
I have no references but Big O is at least handy to be aware of when analyzing a problem and discussion. On the other hand, of course, if the O(log n) version has a way more involved O than the O(n) version it's a moot comparison. And as with everything, there's always a trade off. Space complexity could be an issue, although that could be expressed in O in general as well. Normal case analysis...less so, as you don't want outliers to spike either. Simplicity over complexity, in my opinion, is relatively useless in game development as speed is almost always an issue, so unless the simplicity leads to to speedups (but then it means your complex case was wrong for the wrong reasons) simplicity will have to go out of the window in favour of speed. But Big O is definitely useful, as failing to grasp it will fail to help you analyze possible solutions and their impact.

# Answer
> 0 votes
When you prototype a game function or an aspect of a game, you shouldn't worry about optimizing it **at all**.

In the course of prototyping it and learning about the idiosyncrasies of that functionality, the necessary optimizations will become obvious & will factor into the final design like 2nd nature... most of the time.

Don't sweat it.

# Answer
> 0 votes
It shouldn't be the be-all and end-all. But it does help sort out obvious issues which could cause performance hits; why use something in O(n^2) time, when you can do the same thing in O(log n) time?

I think it applies to games more than most other industries, since the market is the one who would most notice speed problems. Someone using a word processor won't care if there is a half-second delay for doing action X, but gamers will probably go 'omg omg game Y is so slow it takes ages to do action Z'.

# Answer
> 0 votes
In game (and most other) development, we are whining about one extra operation performed per loop:

```
for (int i = 0; i < array.length; i ++) { /* ... */ }

```

vs.

```
for (int i = 0, l = array.length; i < l; i ++) { /* ... */ }

```

Most modern games have physics, and you will find the n-body simulation problem. In a naive algorithm, it's O(n^2), but there is an optimization that makes it O(n log n) (but sacrifices some accuracy).

You could say, you are not programming gravity and particle interactions, but what about the team behavior of an army (of zombies) where they move dependent on others locations (in a more specific word: swarming)?

In a conventional collision detection algorithm, the time complexity is O(n^2), like the n-body. However, there is a better way: Separate the world to many small parts so only objects inside same part are collision- detected. See http://www.videotutorialsrock.com/opengl\_tutorial/collision\_detection/text.php .

If you game is scriptable, do NOT make the scripter write O(n^2) (and up) number-crunching algorithms in the script, such as searching the user's bag. Make a built-in function in the code instead.

# Answer
> -2 votes
In the real world only raw performance counts. Now, the Big-O of an algorithm might serve as a first indication of what to use, but depending on the hardware the implementation might be terribly inefficient. For example doing a linear search can often be faster then a binary search because you get linear memory access and no branches.

Also, because of the current direction in multi-threaded platforms and architectures, Big-O is losing a lot of significance as it's only taking into account the vertical scalability of memory or data touches per operation instead of also taking into account into how the algorithm scales with a larger number of threads.

---
Tags: software-engineering, algorithm
---


title: Class Responsibility

text:
# Question
Title: Class Responsibility
I have some head pain with putting some functionality in correct class. For example I have an operation like this:

1. player selects world space tile
2. game detects which tile is selected
3. game detects what objects it holds
4. game analyzes in what state is player. If it's in moving state - when it moves player to a selected tile. If it's in attack state - when player's character attacks nearby actor.

would it be right if i put code like that in PlayStateUI class?

# Answer
> 2 votes
You could put that all in the same class. It's really up to you. Alternatively, you can separate the user interface and the game logic into separate classes. For example, it looks like number 1 on your list is related to the user interface, while numbers 2 through 4 relate to game logic. Thus, you could put #1 into the PlayStateUI class and the rest into a PlayStateManager class.

---
Tags: c#
---


# Question
Title: OpenGL: Resizing Display and glOrtho/glViewport
I have researched this question from several sources and have yet to find a firm answer saying that "yes that is correct thinking" or "no, here is how it's done."

I am trying to ensure resolution independence with OpenGL rendering. The way I think I should go about it, is to create a projection using `glOrtho` with whatever I want the world coordinates to be. For example, `glOrtho(-50.0, 50.0, -50.0, 50.0, 1.0, -1.0)`. Next, set the viewport to the **screen resolution**, i.e. - `glViewport(0, 0, 800, 600)`. Finally, whenever the window is re-sized, make a call to `glViewport` with the updated screen resolution. This will scale your figures.

Is this the correct way to ensure that models take the same proportion of screen-space on different resolutions? Should I be using a projection equal to the resolution as well? I found some answers saying `glOrtho` should use the resolution of your window while others said it should/can be different.

Thoughts?

# Answer
What you have described is **entirely adequate and appropriate** to provide resolution independence. Anything you draw will indeed always take up the same proportion of your window.

However, if you do nothing more than this, you will have **aspect ratio** problems. For example, given the numbers you wrote, if you draw a circle, it will be squashed — wider than it is tall, because your horizontal scale is 800/(50+50) = 8 and your vertical scale is 600/(50+50) = 6.

**There cannot be any automatic solution to this problem**; you will have to choose what graphical result you want, and consider its effect on the gameplay. Some common examples:

* In a perspective-projection 3D game with no HUD, the usual simple solution (available in OpenGL as part of `gluPerspective`) is to fix the projection's field of view relative to the *vertical dimension*. This means that in such a game, if you resize the window horizontally, you will see more or less of the scene and the middle part of the image will not change at all.

The same idea can be applied to a 2D/2.5D view as well.

(Note that this allows the player to enlarge their field of view horizontally by making a wide but not tall window. This could be unwanted in a competitive multiplayer game.)
* If you have viewport-filling graphics with a fixed aspect ratio (for example, a non-scrolling 2D map, or a decorative border), or if you otherwise cannot change the layout, then you have to do something like having black bars on two sides to fill the unused space.

Or you can make graphics which have thematically consistent filler material around the edges that they can be *cropped* to fit the display without harming gameplay.
* If you have a HUD on top of other graphics, you can decide that each HUD element is fixed to a part of the window (top left, bottom center, etc.) and compute its coordinates; the 'stretching' of varying the aspect ratios gets absorbed by the 'white space' between HUD elements.

As to the specific mathematics of the matter, given that you are doing resolution independence, all you need to start out with is the aspect ratio, a single number: `width / height`. For example, if the window is square it will be 1; if it is 800 by 600 it will be 800/600 = 4/3 = 1.333̅.

For example, suppose you want the *orthographic* projection you have written to gain additional space on the left and right sides if the window is widened. You can do that like this:

```
float aspect = width / height;
glViewport(0, 0, width, height);
glOrtho(-50.0 * aspect, 50.0 * aspect, -50.0, 50.0, 1.0, -1.0);

```

This guarantees that, for windows at least as wide as they are tall, anything you draw with x and y coordinates within -50 to 50 will be visible.

On the other hand, if the window is narrower than it is tall, the -50-to-50 range will be cut off. Let's say you wanted to make sure that it is always visible (so that your content is at its maximum size if the window is square, but smaller otherwise); in that case, you simply do the same thing to the height instead of the width.

```
float aspect = width / height;
glViewport(0, 0, width, height);
if (aspect >= 1.0)
  glOrtho(-50.0 * aspect, 50.0 * aspect, -50.0, 50.0, 1.0, -1.0);
else
  glOrtho(-50.0, 50.0, -50.0 / aspect, 50.0 / aspect, 1.0, -1.0);

```

Note that in the second case we divide rather than multiply. This is simply because we computed the aspect ratio as `width / height` rather than `height / width`; take the reciprocal if you find it easier to understand that way.

Again, this is not the only way to manage aspect ratio; this is just a very simple one for making sure that your content is neither squished nor cut off. Figure out *what you want to happen* when your window is wide, tall, or whatever; then work out the mathematics of it.
> 20 votes

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


# Question
Title: Simple pass-through geometry shader with normal and color
I've written a very simple pass-through geometry shader. My input and output primitives are points. I also want to forward the color and normal from vertex shader to fragment shader through geometry shader. The shaders are compiled and linked flawlessly but the final color is very weird. I think there is something wrong with this forwarding. Can anyone point out the problem? Here are my shaders:

**Vertex shader:**

```
#version 330 compatibility

struct vData
{
    vec3 normal;
    vec4 color;
};

out vData vertex;

void main()
{
    vertex.normal = gl_NormalMatrix * gl_Normal;
    vertex.color = gl_Color;
    gl_Position = ftransform();
}

```

**Geometry shader:**

```
#version 330

layout (points) in;
layout (points) out;
layout (max_vertices = 1) out;

struct vData
{
    vec3 normal;
    vec4 color;
};

in vData vertices[];
out vData frag;

void main()
{
    int i;
    for(i = 0;i < gl_in.length();i++)
    {
        frag.normal = vertices[i].normal;
        frag.color = vertices[i].color;
        gl_Position = gl_in[i].gl_Position;
        EmitVertex();
    }
    EndPrimitive();
}

```

**Fragment shader:**

```
#version 330

struct vData
{
    vec3 normal;
    vec4 color;
};

in vData frag;

void main()
{
    gl_FragColor = frag.color;
}

```

# Answer
My refined and working code goes as follows:

**Vertex shader:**

```
#version 330 compatibility

out vData
{
    vec3 normal;
    vec4 color;
}vertex;

void main()
{
    vertex.normal = normalize(gl_NormalMatrix * gl_Normal);
    vertex.color = gl_Color;
    gl_Position = ftransform();
}

```

**Geometry shader:**

```
#version 330

layout (points) in;
layout (points) out;
layout (max_vertices = 1) out;

in vData
{
    vec3 normal;
    vec4 color;
}vertices[];

out fData
{
    vec3 normal;
    vec4 color;
}frag;

void main()
{
    int i;
    for(i = 0;i < gl_in.length();i++)
    {
        frag.normal = vertices[i].normal;
        frag.color = vertices[i].color;
        gl_Position = gl_in[i].gl_Position;
        EmitVertex();
    }
    EndPrimitive();
}

```

**Fragment shader:**

```
#version 330 compatibility

in fData
{
    vec3 normal;
    vec4 color;
}frag_in;

void main()
{
    gl_FragColor = frag_in.color;
}

```

Happy coding!
> 0 votes

---
Tags: glsl, geometry-shader
---


# Question
Title: How do I convert a 2D movement (from mouse) to a displacement along a 3d axis?
I'm making a small 3D scene editor (that only allow to modify objects positions).

Each object is draw with a 3d X/Y/Z axis :

How it works : user choose an axis (X, Y or Z) by left clicking on it, then, while holding left click, he move the mouse (to move object in the axis direction) . picking is already ok, but i'd like to know `how much` the object should be translated for the selected axis, depending 2D mouse movement.

For the example, on this picture, selecting X axis and moving mouse left-right should give a bigger displacement than moving it up-down (almost zero for this one)

It must be really simple but i cannot figure it out.

Input should be : mouse displacement since first left click(2D vector), selected axis vector (3d vector), modelview / projection matrix.

Output : amount (float or double)

# Answer
How do you want this to behave? There are different ways to do this.

A simple option is to just move the object by some fixed number of world space units for each screen space unit (pixel, say) that the mouse moves.

Another option is to take the vector of mouse movement and project it onto the axis of movement through the normal projection/camera matrices. Project the mouse movement vector via the inverse viewport, projection, and camera matrices (give it an initial Z of the near view plane distance, you should end up with an offset on the near plane). This gives you the mouse movement vector in world space. Project that vector onto the desired axis. This gives you the movement in world space. The object will move to where the user pointed, independent of what orientation the object is at. If the axis is mostly vertical, it takes vertical movement to move it.

You can also just take the start and end mouse point in screen space, project both, and from that calculate the world space movement vector. I don't, but you mighty find that easier.

Another option is to take a power of the mouse movement, so faster movements cause larger offsets.

Using a variant of the first option, you can also grab the pointer so that the user can continuously move his mouse (picking it up and back down). That's especially popular for rotation and scale controls.
> 5 votes

# Answer
I would probably project the selected axis endpoints into 2d space, subtract them to produce a 2d vector. Then take the dot product of the normalized vector of 2d mouse motion with the normalized first vector to determine the portion of movement that should be applied.

So basically, compute 2 vectors:

Va = normalized difference of the projected axis endpoints

Vb = normalized vector created from the mouse movement delta x and y

Va.Vb = |Va||Vb|cos@

Va.Vb / (|Va|Vb|) = cos@ -- which is the component of mouse movement that should be applied along the axis.

Just another option.
> 0 votes

---
Tags: 3d, mouse, picking, axis
---


# Question
Title: Mapping 3D object coordinates to 2D screen coordinates with perspective projection
Sort of following on from where this person was in their topic: Matrix for 2D perspective

What I have at the moment is a transformation matrix that's defined as follows: http://pastebin.com/GM6BhP0R -- The field projMat is just a 4x4 matrix.

I have an array of 3D points that I'm trying to map to the canvas and I'm doing that by first multiplying each vertex (3D point) by a view matrix, which I've just set to the identity matrix for the time being, although if I can get this set up that will be responsible for creating a camera with I suppose.

Lastly I take this newly transformed 3D point and I multiply it by the projection matrix as defined in the code sample above. I was hoping that this would give me the screen coordinates for the points, however there appears to be no depth to the points (e.g. points with a higher Z coordinate should start to taper in, while closer points shouldn't), so objects further away from the camera appear smaller. As I said though, after the transformations it appears to render the points in the same position irrespective of its Z coordinate. Here's how I'm rendering the points (in Java just in case you want to know):

```
for(int i = 0; i < vertices.length; i++) {
    Vector3f transPos = Matrix4f.multiply(projMat, Matrix4f.multiply(viewMat, vertices[i]));
    screen.drawPoint((int) transPos.getX(), (int) transPos.getY(), 0xffffffff);
}

```

As you can see here the inner multiplication just multiplies the vextex (point) with the view matrix, which is set to the identity, then the 3D vector that's produced by that is then multiplied by the projection matrix, which should set it to a perspective view.

If you can see where I've gone wrong I'd appreciate any help.

# Answer
was recently banging my head against the same wall and here is my projection code:

```
private function project( transform:Transform, input:IVector3, output:IVector2 ):IVector2
{
    var worldspace:IVector3  = Vector3.multiplyMatrix( input, transform.getMatrix(), new Vector3() );
    var cameraspace:IVector3 = Vector3.multiplyMatrix( worldspace, this.camera.transform.getMatrix(), new Vector3() );

    var devicespace:IVector3 = this.camera.toNormalDeviceSpace( cameraspace, new Vector3() );
    var clipspace:IVector3   = this.camera.toClipSpace( cameraspace, new Vector3() );

    return this.camera.toScreenSpace( clipspace, output );
}

```

*transform* is the transformation-matrix in world space of the 3Dobject the input vertex belongs to, *input* is the vertex I want to project and *output* is now irrelevant and implementation detail. First to arguments of multiplyMatrix are relevant, the third is output again.

The vertex is still in modelspace so I first convert it to worldspace. Then I want the position relative to the camera and transform the world space coordinates of my vertex to cameraspace. Converting to homogenous coordinates is next as RobCurr pointed out (my Vector3 implementation has a w component) and finally to clip and screen space.

```
// toClipSpace:
Vector3.multiplyMatrix( input, this.projectionMatrix, output );

// toScreenSpace:
output.x = this.viewport.width  * 0.5 + input.x * this.viewport.width  * 0.5 / input.z;
output.y = this.viewport.height  * 0.5 + input.y * this.viewport.height * 0.5 / input.z;

```

The perspective projection done in *toClipSpace* using a perspective transform matrix does not give me the screencoordinates yet and still stores the depth of each vertex in the z component. Just in the last *toScreenSpace* operation I convert the 3D point into a 2D point. Because I previously converted the vertex into normal devices space, zero is in the center of the screen and values range between +1 and -1. Simply dividing by z gives you the depth.

The reason behind doing the detour of first converting into normal device space is that you can flexible project on different resolutions and perform calculations without knowing the final resolution. Clipspace still keeps the z value seperate because you can then easily discard/clip any vertices not within the frustum of your camera.
> 1 votes

# Answer
Note that you will end up with a point in clip space, not screen space. You need another bit of math to convert the \[-1,+1\]x\[-1,+1\] values to \[0,width\]x\[0,height\] coordinates.

You can do this simply by converting \[-1,+1\] to \[0,+1\] (add 1, multiply by 0.5) then scale appropriately (multiply by width or height). This can be put in matrix form if that's easier for you.
> 1 votes

# Answer
I notice that you aren't using homogenous coordinates for your transformation. You are simply using a Vector3f which is strange as I didn't think you could multiply a 4x4 matrix with a 1x3 vector. Try changing your Vector3f's to Vector4f's and put a 1 in the fourth element. Multiply it as you did then take the resulting Vector4f and divide the x,y,z value by the fourth(w) value to produce the desired result.

Finally, do as Sean suggested and perform the conversion from clip space to screen space.

Hope that helps.
> 1 votes

---
Tags: matrix, coordinates, screen, perspective
---


title: Collision detection for Monotouch

text:
# Question
Title: Collision detection for Monotouch
What I want to have for my Monotouch 2D projects: simple collision detection and collision polygons working with UIViews

Sounds simple, isn't it? I've evaluated a lot of engines available on the market, but none of them gives me this simplicity without unnecessary overrun in my projects.

Box2D, monogame/farseer or Cocos2d seems to be good enough, but I don't really want to drag all that functionality to have 2 simple algs.

The question is: is there anything like this out there, or should I go and implement all this myslef?

# Answer
You can use Chipmunk bindings I wrote to manage UIViews collisions. I document that in this post. The bindings can be compiled with or without cocos2d. The latest version of the code is here
> 3 votes

# Answer
Answering my own question: it seems to be possible to use monotouch/monogame version of Farseer Engine without monogame itself. So, couple of changes to the code and this article http://www.cocoanetics.com/2010/05/physics-101-uikit-app-with-box2d-for-gravity/ will get me to the point I have everything I need plus some extras :)

problem seems to be solved!
> 1 votes

---
Tags: 2d, physics, monotouch
---


# Question
Title: How to use LuaJIT the same that Lua in a C++ program?
I'm using **Lua** in my **C++** program, as an library. But I read that **LuaJIT** is a better implementation.

Is it posible to replace with **LuaJIT** with little change? How?

# Answer
> 6 votes
Just replace the source files if you're compiling from source, or the DLL if you're using the precompiled one (preferred).

Per the Installation Guide:

> LuaJIT is API-compatible with Lua 5.1. If you've already embedded Lua into your application, you probably don't need to do anything to switch to LuaJIT, except link with a different library:

LuaJIT is meant to be a drop-in replacement for stock lua, so it should work just by replacing it

# Answer
> 2 votes
As **Panda Pajama** comment suggest. It's easy a drop-in replacement.

* Change include path to get LuaJIT lua.hpp file
* Downgrade code from Lua 5.2 API to Lua 5.1 API.
* Linked with LuaJIT library instead of lua library

The worst part was the downgrade to 5.1, specially the load of own function modules in lua State.

---
Tags: lua
---


title: CCSprite as an iVar

text:
# Question
Title: CCSprite as an iVar
So I built my first game app, and it was a lot of fun. I'm really trying to expand on some of the ideas, but I'm running in to some serious variable scope issue. What I want to do is encapsulate a CCSprite as an instance variable, and then modify it in my "HelloWorldLayer"

In my header:

```
@interface HelloWorldLayer : CCLayer
{
    CCSprite *mySprite;
}

```

and in my HelloWorldLayer.m I run into the problem where if I try to do something like

```
- (id)init
{
   CCSprite mySprite = [CCSprite initWithFile:@"spriteFile.png"];
}

```

I run into either

1. Memory management issues
2. Variable scope issues (overwriting etc.)

What I want to do is be able to declare the sprite, and then change certain properties in other methods such as ccTouchesMoved. How can I do this?

**P.S. I'm sorry if the code is a little rough around the edges, I have been writing Ruby for the last two weeks and I'm a little out of it with reference to objective.**

# Answer
> 1 votes
Your declaration is correct, however, your instantiation should not have the CCSprite class name in front. Just

`mySprite = [[CCSprite spriteWithFile:@"spriteFile.png"] retain]`

is fine. If you're using ARC, then you can leave out the retain.

I normally like to just use properties though so I can refer to them easier and also have the option of accessing the ivar from another class.

```
@interface HelloWorldLayer ()
@property (nonatomic, strong) CCSprite *mySprite;
@end

@implementation HelloWorldLayer
- (id) init {
    if ((self = [super init])) {
        self.mySprite = [CCSprite spriteWithFile:@"spriteFile.png"];
    }
    return self;
}

- (void) someMethodName {
    // You can do anything with the sprite anywhere else in the app.
    self.mySprite.position = ccp(200, 200);

    // You won't need to retain or release it anywhere in the implementation
    // as long as you're using ARC.
}
@end

```

# Answer
> 1 votes
mySprite is declared as member variable. You redeclared again in the init function as local variable so it won't overwrite the member variable. I suggest you should not redeclare it again as local variable as you will use it in somewhere else.

You will need to retain varible created from initWith, e.g.,

```
 mySprite = [[CCSprite initWithFile:@"spriteFile.png"] retain];

```

You will need to release it when you no longer use it.

---
Tags: ios, cocos2d-iphone, ccsprite
---


# Question
Title: Performace benchmark between a C++ and a C# renderer engine?
I want to create a performant 3d renderer for a tech demo at the university workshop. The engine will basically render a forested backdrop, in a small octrant.

I am thinking of writing the engine in a managed language, but I am in a dilema about a possible performace handicap.

Google search just gave some raw benchmarks, with C/C++ winning by vast margins. But I need some performance benchmarks, especially in these kind of softwares... (renderers)

Also, if there are performance slogs, what are their immidiate reasons ? (leaving out GC)

# Answer
> 7 votes
As always, it depends.

Generally speaking, an algorithm implemented in C# should not perform worse than in C/C++ *for arbitrarily large inputs*. Using a "fast" language is not a substitute for a good algorithm. As a concrete example, QuickSort in C# will always beat InsertionSort in C/C++.

Rendering itself is a non-issue. If you're using hardware acceleration, rendering itself will happen on the GPU, which doesn't really care about what language the host program is written in. If you can manage to have the majority of processing get done in the GPU, there will be little difference in the language you use to write your engine.

However, there are things that managed languages such as C# are not very good at, some of which are very relevant in game making. Specifically, memory handling is much slower in C# than in C/C++, because every memory access is checked by the runtime. For example, copying an array element by element is much slower in C# than in C/C++.

But fear not, C# offers several tools you can use to optimize specific pinpointed areas of your code. You may want to look into `unsafe`, `fixed` and in general, usage of pointers in C#.

If all fails, you can always write your specific high performance routines in C/C++ and call them from C# using P/Invoke. I did this when making a game engine with scripting capabilities in Lua: I made interfaces for my engine functions and called them from the scripting engine written in C, which used LuaJIT, which is blazing fast.

You can also use P/Invoke to call native high performance functions like `CopyMemory()` without having to write them yourself.

On the other hand, the development costs you can save yourself by writing a very complex program like a rendering engine, in C# may seriously outweigh the performance advantages you may get by writing it in C/C++.

So in my opinion, if you can write your program in C#, you should do so. Unlike other languages *(-cough- Java -cough-)*, C# offers you lots of options to optimize pinpointed bottlenecks, while maintaining a good high-level abstraction for the rest of the engine.

On the other hand, you should use C/C++ in the following cases:

* You know C/C++ *much* better than C#, and it's impractical to learn C# just for this project.
* You are working on a platform in which C# is not supported.
* You are running on a severely memory/cpu constrained architecture.
* Extensive memory-jockeying is central to your program, in which case it's simply not worth it writing few parts in C#.

---
Tags: c#, c++, performance
---


title: Torque2D createTileLayer

text:
# Question
Title: Torque2D createTileLayer
The script reference "manual" is not much of a help. When I look up `createTileLayer(tileCountX/tileCountY/tileSizeX/tileSizeY)` it doesn't say more than it creates a new `TileLayer`.

But, in what unit do I specify `tileSizeX/Y`? Do I have to clean-up (delete) the created `TileLayer` when my game exits?

*(There was no tag for Torque2D and I'm a little bit short on rep. points to create a new tag)*

# Answer
> 0 votes
The question seems a bit stupid now when I have learned more Torque scripting. For any one else finding them self a bit confused by the "documentation" I can simply explain it this way:

All units (except GUI interface) are in Torque units meaning they are independent of screen resolution.

For clean up, all objects are maintained by the engine and doesn't need to be destroyed before the game ends. In the majority of cases the engine also do the clean up for you if you want to delete an object during the game.

---
Tags: tilemap, scripting, torque
---


title: Is caching tiles like this a good idea?

text:
# Question
Title: Is caching tiles like this a good idea?
I have a 2d int array which represents tiles on level like this:

```
0000000000000000000000
0000000000000000000000
0000000000000000000000
1111111111111111111111

```

I have a tileset vector, where each element has it's own tileX and tileY value(position of a tile in a tileset image), collision data etc. So, when I draw a level each time I draw a tile, I ask about them like this:

```
draw(tileset[currentTile]->tx, tileset[currentTile]->tY, tileWidth, tileHeight);

```

But, as you can see, there will be lots of the same elements when I iterate through **for** loop, so do I need to keep lastCollisionData variable in level class to reduce time used to access each tile separately?

# Answer
Depending on how many times you need to traverse the list, as well as how big it will be in the long run, using something such as run length encoding could be valuable, but you have to consider the time required to encode the tiles each time there is a change to it. This is a situation where the trade off of more time spent up front, could increase performance during actual usage. If the performance hit is insignificant though, then it may not be necessary at all.

*edit* run length encoding is a process for identifying multiple values of the same time within a single run. For instance, rather than representing 00000000 as so, it could be represented as 80, where 8 represents the number, and 0 the value. Of course this takes time up front to perform the encoding, and may not save you time depending on how you are using the data.

http://en.wikipedia.org/wiki/Run-length\_encoding
> 0 votes

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


# Question
Title: Sprite Animations in XAML for Windows Phone 8
I'm developing a 2D game for windows phone. It will feature rather simple 2D graphics and animations. I can get most things done using XAML an storyboards for animations. The performance is fine as long as the images are cached and I don't use standard user-controls (doesn't seem to work well with animations) and stick to using only canvases and images. I really like how simple it is to create basic animations using storyboards.

However, I'm not sure how far XAML and storyboards will get me. Specifically, I have no idea to do sprite-animations. Is there a way to do sprite animations in XAML?

Is it a bad idea to try create a 2D game in XAML?

# Answer
> 1 votes
Depends on if you are using a sprite strip or separate images for each frame? Apparently if you use separate images then you could get some flickering happening, especially at load time. However if it is a sprite strip then you can implement it by modifying the Clip and RenderTransform of the source image in your DispatchTimer. Here is a website that explains:

http://www.cnblogs.com/Jax/archive/2010/02/26/1673899.html

---
Tags: 2d, animation, sprites, windows-phone-8
---


# Question
Title: Proper use of Dynamic Vertex Buffers for rapid update
I am creating a C#/SharpDx/DirectX10 application to plot line charts in a fast way.

I have a prototype which uses Dynamic Vertex Buffers and fills a fixed-size buffer, say 1M vertices, with new data per frame.

I'm finding sometimes the vertex buffer is filled with new data while the GPU is still drawing the last batch (especially on slower GPUs). Here is my code to create, map, fill and flush a vertex buffer. I wonder if I'm using it in the right way?

```
// Declare the re-usable buffer (once)
SharpDX.Direct3D10.Buffer d3d10Buffer = new SharpDX.Direct3D10.Buffer(_d3d10Device,
        new BufferDescription(size,
        ResourceUsage.Dynamic,
        BindFlags.VertexBuffer,
        CpuAccessFlags.Write,
        ResourceOptionFlags.None));

// ...

// Per-frame, map the buffer, write vertices and draw + Flush()
DataStream vertexBufferStream = d3d10Buffer.Map(MapMode.WriteDiscard,
        SharpDX.Direct3D10.MapFlags.None);
vertexBufferStream.Write((float)someValue);
vertexBufferStream.Write((float)anotherValue);
// lots of writing ...

// Then immediately draw
d3d10Buffer.Unmap();
vertexBufferStream.Dispose();
_d3d10Device.InputAssembler.SetVertexBuffers(0,
       new VertexBufferBinding(_d3d10Buffer, 16, 0));

_d3d10Device.Draw(); // Assumes shaders and topology have been applied
_d3d10Device.Flush();

```

So I'm wondering, am I doing this the right way? The MSDN Documentation tells me not to call Flush, but I don't want to overwrite my (shared) dynamic vertex buffer when the next frame begins.

I also saw on the SharpDX website that MapFlags and MapMode have enumerations to prevent overwrite, would MapMode.WriteNoOverwrite and MapFlags.DoNotWait help in this scenario?

# Answer
You're mapping with write-discard, so this isn't a problem at all (and the Flush is definitely not needed). If the buffer is currently in use for drawing the driver will just hand you a new block of memory when you map, and release the old memory when it's drawing has finished. Really clever drivers will actually keep the old block lying around and reuse it as a subsequent "new block" some frames later, so that instead of allocating/releasing memory each frame it's just continually cycling through the same few blocks - a classic multi-buffering approach but all handled for you automatically by the driver: neat!
> 2 votes

---
Tags: c#, directx, directx11, directx10, sharpdx
---


# Question
Title: What are the hidden cost while deploying game with Unity3D?
I just started learning Unity3D. I created a small 2D game, and I want to host for Windows, iPhone, iPad, Android, Windows 8, Xbox and even on websites.

I created it using **free Unity3D editor.** Now I want to host all these game on my website.

I will purchase iPhone, Android, and Windows 8 developer accounts. Apart from that, do I need to purchase any license in order to deploy the game on my website?

I can lots of license here: https://store.unity3d.com/

If I later purchase Unity Pro, then do I need to purchase any extra licenses?

And will that Unity logo always appear while starting the game?

# Answer
> 4 votes
I suggest you to have a look at this page, that shows license features comparison.

You can deploy to `iOS`,`Android` or `Flash` buying the related licenses without buying `Unity3D` pro license. The pro license has more features than the normal one. Buying it it's more a matter of features than target platforms.

> I created it using free unity3d editor. Now I want to host all these game on my website.
>
> I will purchase iphone, android and windows 8 developer account. Apart from that, do I need to purchase any license in order to deploy game on my website.

You need `iOS` and Android license to target those platforms. AFAIK you can use a `Unity` plugin to play game in your browser without a specific license (for the `Flash` one you have to pay)

> If I will purchase unity pro then do I need to purchase any extra license?

For anything else than pc platform or web using `Unity` plugin yes, you need to purchase the platform specific license.

> And will that unity logo will always appear while starting game.

To remove it you need `Unity` pro license.

# Answer
> 0 votes
You will need Unity's iOS and Android licenses as well if you plan on releasing on those platforms.

# Answer
> 0 votes
If you were already immersed in XNA then an option would be to port it using MonoGame which is a replacement for the now expiring XNA. Going that route you could likely still use dev kits such as FlatRedBall and then you would just have to tweak the code for the various implementations (iOS and Android) plus pay the cost for the dev accounts for each of those platforms. That is usually less than $100, but for iOS you will still need a Mac in the end regardless... must pay the apple tax.

MonoGame itself is free however it is still under fairly intense development so it is not for the faint of heart.

# Answer
> 0 votes
Unity's store page should be straight forward. If you want to deploy on iOS you need an iOS license. If you need/want features from Unity Pro, you need the Unity Pro license (or if you don't qualify for their indie license).

The only other costs associated with deploying to the various platforms are the developer licenses from Apple/Google to actually deploy your app on their app stores.

---
Tags: android, unity, xbox360, licensing, ipad
---


title: how to make animation for a 2d game

text:
# Question
Title: how to make animation for a 2d game
I've started working on a 2d game. I wanted to know how animation usually works in 2d games - I know one way is to make a sprite sheet with frames of the animation, but you wouldn't see big sprite sheets on an actual professional game. is this on purpose or is there a different way of creating animation?

# Answer
To understand how 2D animation works, you should understand how textures are mapped to a surface. When you pass in vertex data along with a texture to the graphics card, UV coordinates are passed in with it, to specify a (usually) normalized position on the texture that the vertex is located at. For instance, when rendering a sprite to a single billboard, you would usually pass in uv coordintes like so.

Vertex01: (0,0), UV: (0,0) Vertex02: (0,1), UV: (0,1) Vertex03: (1,0), UV: (1,0) Vertex04: (1,1), UV: (1,1)

This would map the entire texture to the billboard, which is fine for a single image, but if you want to use a sprite sheet for animation, then you would want to map to a portion of it only.

So lets say you have 4 sprites of even size on a sprite sheet, and you wanted to map the first frame of the sheet to a billboard, these UV coordinates would allow you to do map only 1/4 of the texture to the billboard.

Vertex01: (0,0), UV: (0,0) Vertex02: (0,1), UV: (0,0.25) Vertex03: (1,0), UV: (0.25,0) Vertex04: (1,1), UV: (0.25,0.25)

So if you wanted to change the frame on this billboard, you would update the UV coordinates based on the dimensions of the frame.

On top of this system, you would need to implement the animation framework that updates the animation, at the frame rate you want. Keeping track of the time since the previous frame update, you can ensure you are only changing frames every n milliseconds to achieve the framerate you want.
> 0 votes

---
Tags: 2d, animation
---


# Question
Title: How do I set up in-app purchasing in iOS?
I am using Unity and I developing an app for iOS. How do I implement in-app purchases that work world-wide?

# Answer
> 6 votes
Apple provides a framework for in-app purchasing in StoreKit. You can read the docs on it here. From their documentation:

> Store Kit communicates with the App Store on behalf of your application. Your application uses Store Kit to receive localized information from the App Store about products you want to offer in your application. Your application displays this information to users and allows them to purchase items. When a user wants to purchase an item, your app calls Store Kit to collect payment from the user. Figure 1-1 shows the basic store model.

How to implement in-app purchasing is more involved than the format here permits, but the general areas that you're going to need to learn about are:

* Retrieving Product Information from the App Store
* Making a Purchase from the App Store
* Adding a Store to Your Application
* Verifying Store Receipts
* Testing your store
* Auto-renewable subscriptions (possibly).

Here are some additional resources you may want to look at:

---
Tags: c#, unity, ios, monetization
---


# Question
Title: Why doesn't glBindVertexArray work in this case?
From my understanding of what `glBindVertexArray` does and how it works, the following code should work fine:

First init:

```
    glGenVertexArraysOES(1, &_vertexArray);
    glBindVertexArrayOES(_vertexArray);

    glGenBuffers(1, &_buffer);
    glBindBuffer(GL_ARRAY_BUFFER, _buffer);
    glBufferData(GL_ARRAY_BUFFER, kMaxDrawingVerticesCount*sizeof(GLKVector3), NULL, GL_DYNAMIC_DRAW);

    glGenBuffers(1, &_indexBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, kMaxDrawingVerticesCount*1.5*sizeof(GLuint), NULL, GL_DYNAMIC_DRAW);

    glEnableVertexAttribArray(GLKVertexAttribPosition);
    glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(GLKVector3), BUFFER_OFFSET(0));

    glBindVertexArrayOES(0);

```

And later add new geometry:

```
glBindVertexArrayOES(_vertexArray);
glBufferSubData(GL_ARRAY_BUFFER, 0, (GLintptr)_data.vertices.length, _data.vertices.bytes);
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, (GLintptr)_data.indices.length, _data.indices.bytes);
glBindVertexArrayOES(0);

```

However, it doesn't work (there is screen output, but it looks like the buffers were changed between each other). Binding the vertex array is not enough for the vertex/indices buffer to get bound? Because, if I do this:

```
glBindVertexArrayOES(_vertexArray);
glBindBuffer(GL_ARRAY_BUFFER, _buffer); <-- note this line
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexBuffer); <-- note this line

glBufferSubData(GL_ARRAY_BUFFER, 0, (GLintptr)_data.vertices.length, _data.vertices.bytes);
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, (GLintptr)_data.indices.length, _data.indices.bytes);
glBindVertexArrayOES(0);

```

Everything works/looks as expected. I find it strange, since the vertex array should have taken care of the buffer binding. Otherwise, what's the purpose to have a vertex array if you still have to bind all the buffers?

# Answer
The behavior you're seeing is correct. Consider the case where you're using two vertex streams:

```
glBindVertexArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 1);
glVertexAttribPointer(...);
glBindBuffer(GL_ARRAY_BUFFER, 2);
glVertexAttribPointer(...);
glBindVertexArray(0);

```

Now what? The VAO was designed to store whole arrays of bindings, specifically for drawing. It can't substitute for buffer binding semantics in functions that modify buffer state, because it's not clear which buffer should be bound. The first? The last?

Bind the VAO to draw. Bind the VBO to modify the VBO.
> 4 votes

# Answer
```
glBindBuffer(GL_ARRAY_BUFFER, _buffer); <-- note this line

```

What about it? As has been stated many, *many* times before, the association between a buffer object and a vertex array is made by `glVertexAttribPointer`, ***not by `glBindBuffer`***. Therefore, if you want to *change* that association, you must bind the buffer ***and*** call `glVertexAttribPointer`. Because *that* is what gets stored in the VAO.
> 1 votes

# Answer
If you're having errors, maybe this

```
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, (GLintptr)_data.indices.length, _data.indices.bytes);

```

is incorrect. `glBufferSubData` requires size in bytes. You haven't allocated the buffer size explicitly as bytes so i'm guessing that sending just the length is not intentional.

EDIT:

Another thing is, you're using OpenGL ES2 and AFAIK it doesn't have VAOs, is that an extension? Are you sure that it's working properly?
> 0 votes

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


# Question
Title: Creating A Bounding Box around each item in a list XNA 4.0
I have asked a similar question before except i am more experienced and have more understanding of XNA. I have bullets that shoot whenever you press RightTrigger. I am having trouble though creating bounding boxes around each bullet in the list though. I want to have this so you can shoot the man and when he is hit he will die, except for some reason no bounding boxes are being drawn. I have updated this now because im trying the same method in a platformer after i gave up on the shooter game because i gave up on it because i couldnt get the collision detection right. Now im trying this method again and am having trouble. The thing is, it does work but only on the last ground piece added to the list. Here is the code for the collision detection in the Game1 class:

**OLD CODE (DISREGARD)**

```
public bool hitBullet()
    {

        foreach (Bullets bullet in bullets.bulletAmm)
        {
            bulletRect = new Rectangle(
                (int)bullet.position.X,
                (int)bullet.position.Y,
                bullet.size.X,
                bullet.size.Y);

            manRectangle = new Rectangle(
                (int)man.position.X,
                (int)man.position.Y,
                man.pistolTexture.Width,
                man.pistolTexture.Height);
        }

        return bulletRect.Intersects(manRectangle);
    }

```

**NEW CODE (PAY ATTENTION)**

```
 public bool HitGround()
    {
        foreach (Ground newGround in ground.groundAmmount)
        {
            groundRectangle = new Rectangle(
                (int)newGround.position.X,
                (int)newGround.position.Y,
                newGround.shortTexture.Width,
                newGround.shortTexture.Height);

            iceBoyRectangel = new Rectangle(
                (int)iceBoy.position.X,
                (int)iceBoy.position.Y,
                iceBoy.texture.Width,
                iceBoy.texture.Height);
        }

        return groundRectangle.Intersects(iceBoyRectangel);
    }

```

now the same method of

```
    foreach (Bullets bullet in bullets.bulletAmm)

```

or foreach(Ground newGround in ground.groundAmmount);

works for updating and drawing each bullet which works. but not for the bounding boxes. Any suggestions?

**EDIT 1:**

i noticed now that this method works sometimes, but only for about 1 in every 20 bullets which makes this even stranger.

**EDIT 2:**

i thought that i had solved this issue but it turns out i havent. I have updated the code to what it is now.

# Answer
If I understand your question, your bullets update and draw fine, but the collision detection only works sometimes (1 out of 20 or so).

It could be what's called tunneling, where during one frame the bullet is not yet to the man & then the next frame the bullet is past the man (no longer intersecting, has gone right through). This happens especially when bullets move fast (many pixels per frame). In these cases you need to use a sweep test instead of a simple test.

If that sounds like your issue, here is a good helper for that: http://www.gamasutra.com/view/feature/131790/simple\_intersection\_tests\_for\_games.php?page=3
> 2 votes

---
Tags: c#, collision-detection, xna-4.0, bounding-boxes
---


title: AI remembering obstacles without a grid

text:
# Question
Title: AI remembering obstacles without a grid
For some research purpose I've build a small tanks game where you have 1 tank controlled by a player and one or more NPC tanks.

Now I want these NPC tanks to navigate through a field which they have no knowledge of. They can detect obstacles if they are in a certain range. If they detect those obstacles they should save them in a certain data construct that's easy to query. So that they can take them in account in pathfinding.

Now here is where I'm stuck : if my field would be a grid (level discretized in tiles) it would be quite easy for me, I would just save which tiles the obstacle is on.

But I haven't really worked with a grid, my tanks just move forward a few pixels depending on their speed, so a tank can be located on any pixel combination. Is this bad game design?

I could probably make a grid just for my obstacles, but that restricts a bit the kind of obstacles I can have.

Any suggestions/tips ? Please ask more information if needed, I was not really sure what to include.

# Answer
The following is a 3D AI approach, but is easily translated to 2D (I dont know which you're using)

In our engine we have a dynamic path-node grid where a AI entity navigates through the node grid with A-star. When we then drop an object or is manually placing objects into the scene we update the path-nodes when there's a collision (not everytime its colliding but on enter or on exit) within the area.

So an octree or quadtree is recommended to speed things up. So Im driving my tank and the tank get's notified that it has been placed in another quadtree-node. Next we check all path-nodes which is also within the same (new) quadtree-node as the tank and we update the path-nodes however we want. If it was I tank I would set the path-nodes to a "Blocked" state and no other tank will be able to navigate through those nodes.

One important thing to note is that the path-nodes we're leaving must be reset, so we're not driving around and just blocking path-nodes, leaving a trail behind us.

If your not familiar with A-star. Here's one in 2D: http://xnatd.blogspot.se/2011/06/pathfinding-tutorial-part-1.html
> 1 votes

# Answer
Take a look at the Tiled Map Editor. Tiled is an open source tool for creating maps in a TMX (xml) format. Tiled is more frequently used (as the name suggests) for maps on a fixed tile grid, but it doesn't have to be. I'm discussing Tiled not to recommend a particular product, but to illustrate a concept. First, here's a little sample map I created using an object layer with a few polygons.

And here's an excerpt from the associated XML file that specifies the left polygon:

```
  <object x="335" y="285">
   <polygon points="0,0 322,9 236,156 -229,32 -252,-192 -166,-185 -84,-87 -49,-78"/>
  </object>

```

As you can see, this sort of approach doesn't restrict you to a fixed grid. If you create your maps using an editor like this, you'll need to read and parse the maps into your application. So, for example, you might have a polygon object, that takes the data from the polygon--the various points--and loads it into your scene.

I think you'll find that whatever approach you use to store your map for navigation purposes, it's worthwhile to use **the same approach** to store the map in the tank "ai".

In other words, if your map loads a series of polygons, lines, etc., you can have each tank maintain its own representation of the map--essentially, a subset of the map used to generate the level. This way, when a tank "learns" about a particular object, say a polygon, you don't have to recreate or reform the polygon under some separate data structure, you simply add that polygon object to the tank's "knows about" collection.
> 1 votes

---
Tags: ai, grid
---


title: Voice recognition libraries - C++

text:
# Question
Title: Voice recognition libraries - C++
I need to implement voice recognition in my game, the target is that the user speaks into the microphone and the game responds accordingly to some commands.

What libraries could help me with such task? I need them for C++ and as lightweight as possible to plug into the game(it will be used in mobile games).

An ideal usage would be having it capture input sound or receiving the audio samples, and outputting strings with the recognized text.

Thanks

# Answer
Voice recognition is more difficult than you think it is. At least, you need dictionary (file containing thousands of words). Check this link https://stackoverflow.com/questions/2817663/sound-sample-recognition-library-code
> 1 votes

# Answer
You can use Google voice recognition with Android device. You can also setup a server and send the voice recognition request to Google's server for device such as iOS. It requires internet connection but it provides the best result. The encoded audio file is small so the latency is minimal.

Since you only has a few hundred words you can also try Sphinx3 and OpenEars.

Dragon Speech Recognition is an option but it requires commercial license. Dictionary can be provided for better result.
> 1 votes

---
Tags: c++, sound, voice
---


# Question
Title: How can I normalize a vector if I am handling movment of each axis seperatley?
I am writing a 2D tile based game engine in XNA, and I've recently fine-tuned my collision detection using the answers provided here and more specifically here.

The tile based collision detection now works flawlessly and fixed all the small problems I had with my previous code. However, implementing this forced me to rewrite how movement was handled. Instead of moving the player all at once and then resolving each collision along the smallest axis of intersection depth, it now updates and resolves on the X and Y axes separately.

This is fine, but now my diagonal movement is much faster than my horizontal and vertical movement and I am unsure of how to normalize it.

I'm sure I'm just overlooking something simple, is there a straight forward way of doing this?

```
    public void HandleInput()
    {
        //Set horizontal and vertical values accordingly based on direction of key presses
        int horizontal = InputHelper.IsKeyDown(Keys.A) ? -1 : (InputHelper.IsKeyDown(Keys.D) ? 1 : 0);
        int vertical = InputHelper.IsKeyDown(Keys.W) ? -1 : (InputHelper.IsKeyDown(Keys.S) ? 1 : 0);

        //If there is movement update sprite position, round the position to nearest pixel and then check for collision
        if (vertical != 0)
        {
            sprite.Position += Vector2.UnitY * sprite.Speed * vertical;
            sprite.Position = new Vector2(sprite.Position.X, (float)Math.Round(sprite.Position.Y));
            HandleCollisions(Direction.Vertical);
            UpdateSpriteAnimation(Direction.Vertical, vertical);
        }
        if (horizontal != 0)
        {
            sprite.Position += Vector2.UnitX * sprite.Speed * horizontal;
            sprite.Position = new Vector2((float)Math.Round(sprite.Position.X), sprite.Position.Y);
            HandleCollisions(Direction.Horizontal);
            UpdateSpriteAnimation(Direction.Horizontal, horizontal);
        }
    }

    private void HandleCollisions(Direction direction)
    {
        // Get the player's bounding rectangle and find neighboring tiles.
        Rectangle playerBounds = sprite.spriteBounds;
        int leftTile = playerBounds.Left / Engine.TileSize;
        int topTile = playerBounds.Top / Engine.TileSize;
        int rightTile = (int)Math.Ceiling((float)playerBounds.Right / Engine.TileSize) - 1;
        int bottomTile = (int)Math.Ceiling(((float)playerBounds.Bottom / Engine.TileSize)) - 1;

        // For each potentially colliding tile,
        for (int y = topTile; y <= bottomTile; ++y)
        {
            for (int x = leftTile; x <= rightTile; ++x)
            {
                Vector2 depth;
                //If this tile is collidable, and it intersects sprite bounds
                if (tileMap.CollisionLayer.GetCellIndex(x, y) == 0 && TileIntersectsPlayer(playerBounds, GetTileBounds(y, x), direction, out depth))
                {
                    //Resolve the collision along the given axis
                    sprite.Position += depth;

                    // Perform further collisions with the new bounds.
                    playerBounds = sprite.spriteBounds;
                }
            }
        }
    }

```

# Answer
To expand on what Trevor was saying, when you hold down just a vertical or horizontal button then your net movement is only 1 * speed, but if you hold down a vertical plus a horizontal key then your net movement is sqrt(1+1) * speed. So what you need to do is to normalize the horizontal and vertical values by dividing them by the sqrt of the sum of the squares of them. Or you can just put the values into a Vector2 and normalize it.

So change your lines where you retrieve vertical and horizontal and do this instead:

```
Vector2 move = new Vector2(InputHelper.IsKeyDown(Keys.A) ? -1 : (InputHelper.IsKeyDown(Keys.D) ? 1 : 0) , InputHelper.IsKeyDown(Keys.W) ? -1 : (InputHelper.IsKeyDown(Keys.S) ? 1 : 0));
Vector2.Normalize(move);

```

Then use move.X wherever you would have horizontal and move.Y wherever you had vertical.
> 3 votes

# Answer
Math doesn't care how you store your variables; you normalise vectors in exactly the same way, regardless of whether you put their values into a single object, or separate variables.

Length = sqrt( axisX * axisX + axisY * axisY (... + axisZ * axisZ, etc) ).

Then divide each axis by the length you've calculated.
> 1 votes

---
Tags: xna, c#, collision-detection, xna-4.0, movement
---


# Question
Title: Where to find market research info on adventure games?
Looks like adventure games are on the rise again. There were several great releases in 2012, including brilliant and highly acclaimed Walking Dead from TellTale.

Is there a market research that proves the new rise of adventure games? Bonus points for revenue estimates and such. I'm particularly interested in mobile games segment, but everything else is of interest as well.

# Answer
Here is an analysis of Kickstarter projects for games 2012:

http://www.slideshare.net/ICOPartners/kickstarter-and-games-september-2012

The final few slides provide a percentage split per game category, and interesting for you is a comment on slide 15 - "RPGs and Adventure games are still very much dominating"

Edit: Another article http://www.vgchartz.com/article/250252/weekly-sales-analysis-30-june-2012-spec-ops-spider-man/ for global sales across all platforms, compiled during 2012, shows 4 of the top 5 slots are held by RPG and Adventure games.

Edit2: Alexander, if time is no question for you, then please make use of "App Annie" (google it), and Distimo provide reports too. You could contact Distimo or AppAnnie via email and ask them a question or two on this matter. Good luck!
> 3 votes

# Answer
There probably is market research data available that one could use to draw correlations to a renaissance of the adventure game genre. Such data would hardly constitute *proof*, though. The best proof would be in the sales and profit/loss numbers directly from the publisher or developer (which aren't typically released, unless they are buried amidst the earnings reports of large public publishers).

The market research data in question is generally not freely available (sometimes a subset of it is), but you can contact various market research firms (these guys, these guys, or these guys for example) to see about purchasing some.
> 2 votes

---
Tags: marketing, business, adventure-games
---


title: Unity3D Camera constantly moving

text:
# Question
Title: Unity3D Camera constantly moving
I'm trying to make my own first person camera controls in unity that use both thumbsticks on a joypad. I have this working fine. However, when I move the right thumb stick (the one uses to look left / right & up / down the camera begins to constantly update.

Here is my joypad movement code:

```
   // Update is called once per frame
void Update()
{

    float speed = transform.localEulerAngles.y + Input.GetAxis("LeftRight") * sensitivityX;

    rotationY += Input.GetAxis("UpDown") * sensitivityY;
    rotationY = Mathf.Clamp(rotationY, minimumY, maximumY);

    transform.localEulerAngles = new Vector3(-rotationY, speed, 0);

}

```

To control the left thumb stick, I've simply attached the my script to a first person character controller Unity provide.

I know my code is updating every frame, but I assumed that it would only update as and when I press the right thumb stick. If that isn't the case, is there a way I can limit it to only increment when I move the right thumb stick?

# Answer
> 3 votes
Your code looks fine, so I assume the problem is somewhere else. The one I can think of: these axes have very small "Gravity" value in Input Manager (i.e. "Speed in units per second that the axis falls toward neutral when no buttons are pressed", from this page in Unity Manual).

---
Tags: c#, unity, camera
---


title: Packaging a Java game for Linux

text:
# Question
Title: Packaging a Java game for Linux
I'm just about finished developing a small Java/Lwjgl-based game. For Windows users, I intend to use Launch4J to package the game into a nice .exe. For Mac users, I'll be using JarBundler to produce a nice .app.

What do I do for Linux users? So far I've been distributing beta versions as a .jar file, a lib folder and a shell script for invoking the jar with the right virtual machine parameters. But this is less than pretty. Is there a cross-distro way of providing a single clear way to start the game?

# Answer
> 1 votes
Making a script and putting it somewhere like /usr/bin is the standard way of doing this. Look into .deb packages if you want to package it nicely.

---
Tags: java, lwjgl, linux, distribution
---


# Question
Title: What is the point of caling Draw() as often as possible?
From the MSDN page:

> Update and Draw are called at different rates depending on whether IsFixedTimeStep is true or false. If IsFixedTimeStep is false, Update and Draw will be called sequentially as often as possible. If IsFixedTimeStep is true, Update will be called at the interval specified in TargetElapsedTime, while Draw will continue to be called as often as possible.

What is the point of calling Draw potentially more often than Update? Why is Draw not upper-limited to the number of Update calls?

# Answer
Here Shawn Hargreaves talks about GameTime in XNA. This posts was the best explanation of this problem I was able to find when looking into this concept for myself.
> 5 votes

# Answer
After reading the article floAr linked, I also wondered why the author of that article seemed to contradict the MSDN page in places, and I started experimenting on the XNA shooter tutorial a little with the following findings:

* Draw is called as often as Update if possible, but not more often, contrary to the MSDN statement about fixed time stamp
* If *IsFixedTimeStep == false*, then *TargetElapsedTime* gets ignored as expected, but Update, and therefore Draw, are still capped at the monitor refresh rate and not unlimited as the MSDN page suggests. To get more Update FPS than the monitor refresh rate, you have to disable monitor refresh rate synching or use a fixed time stamp and set the value lower than the default 16.6 milliseconds.
* By using a StopWatch-controlled empty while-loop, I simulated a very expensive Update method.

+ When *IsFixedTimeStep == true* and the delay would approach but not surpass *TargetElapsedTime* (for example delay = 16.1, target = 16.6), the Drawing FPS would rapidly fall behind Update FPS. If the delay was even slightly above the target (e.g. 17.0 and 16.6), the update FPS were as expected by the set delay, but the drawing FPS would go way below that. So not only drawing was slow, there was a disconnect between updating and drawing, which makes for severely lagging gameplay.
    + When *IsFixedTimeStep == false*, there is no disconnect, because even for large values of delay, the drawing FPS was the same as the update FPS. Both are slow, but they are equally slow.

So in essence, without completely breaking the XNA game loop by calling Draw whenever you feel like it, you can only influence the number of calls per second to Update, and Draw will be called at most once per Update under any circumstances.
> 2 votes

---
Tags: xna
---


# Question
Title: When to use ShapeRenderer & SpriteBatch in libGdx?
As a beginner(in GdxLib+Android), i found that for rendering particular screen, we can render that using both ways then when to use specific ones? & **What is the best option for Updating the smaller part/region of the screen**?

# Answer
per documentation `ShapeRenderer` isn't efficient and shouldn't be used intensively.

> Renders points, lines, rectangles, filled rectangles and boxes. This class is not meant to be used for performance sensitive applications but more oriented towards debugging.

That being said, I asked for opinions on its real impact here, but since I've got no answer yet, I decided to give a try. It's working nice so far but if you can use a texture, I'd say to go with that. (I'm not using a texture because I'm writing a small library and don't want to include non code).
> 5 votes

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


# Question
Title: Why is there such a problem to create realistic eyes in games?
I mean, even the latest demo from ps4 possibilities or any demo, you can see that the person is not real if there are eyes involved. E.g. if you only see the skin, you may be mistaken, but not if you see the eyes.

Why is it so difficult to achieve believable eyes in game development?

# Answer
I think it is because eyes are **always wet**. It is almost impossible to simulate wet surface with classic hardware reasterization techniques (I don't mean simulating water, but an object with very thin layer of water).
> 0 votes

# Answer
Eyes are just balls. There's nothing expressive about a ball. What's expressive are the muscles around the eye, which not many games model. For example, think about the squint of anger, or the relaxed eyelids when you're bored.
> 5 votes

# Answer
I think we are much more sensible to the look of eyes than any other type of "surface" as we are acustomed to see them from a close distance and look at them alot. Water or other surfaces may look differently depending on many factors, like water color, depth, lighting from above, lighting from under the water. We don't recognize errors there because it is hard to say if it looks right or not.

Additionaly eyes are very hard to render as they reflect/refract lights on multiple layers, have moving parts and are not perfect spheres.
> 3 votes

# Answer
Eyes are hard to do because of their complexity. They have a complex motion and a complex structure. This makes duplicating their aspect and motion hard to do in a "resource-friendly" manner.

Also, it might just not be that eyes are so badly done as compared to other stuff as it is more an issue of the fact that eyes are amongst the most studied parts of humans and what's around us. Maybe milk is not properlly done as well, heck, maybe it's worse than with eyes. Milk surface is tricky, there's lots and lots of sub-surface scattering and such. But since people tend to look more (and are more familiar with the aspect of) eyes than milk, it might just make so that eyes rendering is more criticized than milk rendering.

Also, at a supperficial glance, eyes seem easy. I mean they're just a shiny ball with some concentric cirles of various colors "painted" on, right :) ? This might lead the junior 3d artist into over-simplifying the task and making just that, a shiny ball with concentric textures that completly lacks, for example the subtle light sparkle that happends in every (living) eye.

Finally, eyes are small. Think XCOM Enemy Unknown (the 2012 version). 80% of the time you're in high-above-3rd-person view, you don't really see the eyes. But sometimes the camera zooms and changes angles so that you get a close-up portrait of the character. In such a setup (which is quite often), details which are not often seen from up-close (such as eyes) are intentionally left "un-detailed" so as to speed up development and conserve resources.
> 2 votes

# Answer
I fully agree with you, in most games the eyes look "dead".

Well eyes have a lot of reflection and refraction in them. That level of reflection would take up a lot of processing time. I suppose that developers would rather use that processing power to rather make the water more detailed in it's reflection. Also you're going to need relatively detailed textures for the eyes and considering it's such a small space, you're spending a lot of processing in a very small space.

If you're talking about the movement of eyes. I think some games have gotten it pretty good. Movement is also not that hard as you just have the eye ball look at an object (point an axis at the object) you want to look at. Having said that I have played some modern games, where not even this is done.
> 1 votes

---
Tags: 3d, art
---


title: When/where to update components

text:
# Question
Title: When/where to update components
Instead of my usual inheritance heavy game engines I'm toying with a more component based approach. However I have a hard time justifying where to let the components do their thing.

Say I have a simple entity that has a list of components. Of course the entity does not know what these components are. There might be a component present that gives the entity a position on screen, another one might be there to draw the entity on screen.

In order for these components to work they have to updated every frame, the easiest way to do this is to walk over the scene tree and then for each entity update each component. But some components might need a little bit more management. For example a component that makes an entity collidable must be managed by something that can oversee all collidable components. A component that makes an entity drawable needs someone to oversee all other drawable components to figure out the draw order, etc...

So my question is, where do I update the components, what is a clean way of getting them to the managers?

I have thought about using a singleton manager object for each of the components types but that has the usual drawbacks of using a singleton, a way to alleviate this is a bit is by using dependency injection but that sounds like overkill for this problem. I could also walk over the scene tree and then gather the different components into lists using some sort of observer pattern but that seems a bit wasteful to do every frame.

# Answer
> 15 votes
I would suggest starting by reading Mike Acton's 3 big lies, because you violate two of them. I'm serious, this will change the way you design your code: http://cellperformance.beyond3d.com/articles/2008/03/three-big-lies.html

So which do you violate?

Lie #3 - Code is more important than data

You talk about dependency injection, which may be useful in some (and only some) instances but should always ring a great big alarm bell if you use it, especially in game development! Why? Because it is an often unnecessary abstraction. And abstractions in the wrong places are horrible. So you have a game. The game has managers for different components. The components are all defined. So make a class somewhere in your main game loop code that "has" the managers. Like:

```
private CollissionManager _collissionManager;
private BulletManager _bulletManager;

```

Give it some getter functions to get each manager class (getBulletManager()). Maybe this class itself is a Singleton or it is reachable from one (you've probably got a central Game singleton somewhere anyway). There's nothing wrong with well defined hard-coded data and behavior.

Don't make a ManagerManager which lets you register Managers using a key, which can be retrieved using that key by other classes that want to use the manager. It's a great system and very flexible, but where talking about a game here. You know *exactly* which systems are in the game. Why pretend like you don't? Because this is a system for people who think code is more important than data. They will say "The code is flexible, the data just fills it". But code is just data. The system I described is far easier, more reliable, easier to maintain and a lot more flexible (for instance, if the behavior of one manager differs from other managers, you only have to change a few lines instead of reworking the entire system)

Lie #2 - Code should be designed around a model of the world

So you have an entity in the game world. The entity has a number of components defining its behavior. So you make an Entity class with a list of Component objects, and an Update() function which calls the Update() function of each Component. Right?

Nope :) That's designing around a model of the world: you have bullet in your game, so you add a Bullet class. Then you update each Bullet and move on to the next one. This will absolutely kill your performance and it gives you a horrible convoluted codebase with duplicate code everywhere and no logical structuring of similar code. (Check out my answer here for a more in-detail explanation of why traditional OO design sucks, or look up Data Oriented Design)

Let's take a look at the situation without our OO bias. We want the following, no more no less (please note there's no requirement to make a class for entity or object):

* You have a bunch of entities
* Entities comprise of a number of components which define the entity's behavior
* You want to update each component in the game each frame, preferably in a controlled way
* Other than identifying components as belonging together, there is nothing the entity itself needs to do. It's a link/ID for a couple of components.

And let's look at the situation. Your component system will update the behavior of *every* object in the game *every* frame. This is definitely a critical system of your engine. Performance is important here!

If you're familiar with either computer architecture or Data Oriented Design, you know how the best performance is achieved: tightly packed memory and by grouping code execution. If you execute snippets of code A, B and C like this: ABCABCABC, you will not get the same performance as when you execute it like this: AAABBBCCC. This isn't just because the instruction and data cache will be used more efficiently, but also because if you execute all "A"s after one another, there is a lot of room for optimization: removing duplicate code, precalculate data that's used by all "A"s, etc.

So if we want to update all components, let's not make them classes/objects with an update function. Let's not call that update function for each component in each entity. That's the "ABCABCABC" solution. Let's group all identical component updates together. Then we can update all A-components, followed by B, etc. What do we need to make this?

First, we need Component Managers. For every type of component in the game, we need a manager class. It has an update function which will update all components of that type. It has a create function that will add a new component of that type and a remove function that will destroy the specified component. There may be other helper functions to get and set data specific to that component (eg: set the 3D model for Model Component). Note that the manager is in some ways a black box to the outside world. We don't know how data of each component is stored. We don't know how each component is updated. We don't care, as long as the components behave as they should.

Next we need an entity. You could make this a class, but that's hardly necessary. An entity could be nothing more than a unique integer ID or a hashed string (so also an integer). When you create a component for the Entity, you pass the ID as argument to the Manager. When you want to remove the component, you pass the ID again. There may be some advantages to adding a bit more data to the Entity instead of just making it an ID, but those will only be helper functions because as I've listed in the requirements, all entity behavior is defined by the components themselves. It's your engine though, so do what makes sense for you.

What we do need is an Entity Manager. This class will either generate unique IDs if you use the ID-only solution, or it can be used to create/manage Entity objects. It can also keep a list of all entities in the game if you need that. The Entity Manager could be the central class of your component system, storing the references to all the ComponentManagers in your game and calling their update functions in the right order. That way all the game loop has to do is call EntityManager.update() and the whole system is nicely separated from the rest of your engine.

That's the bird-eye view, let's take a look at how the component managers work. Here's what you need:

* Create component data when create(entityID) is called
* Delete component data when remove(entityID) is called
* Update all (applicable) component data when update() is called (ie not all components need to update each frame)

The last one is where you define the components behavior/logic and depends completely on the type of component you're writing. The AnimationComponent will update the Animation data based on the frame it's at. The DragableComponent will update only a component that is being dragged by the mouse. The PhysicsComponent will update data in the physics system. Still, because you update all components of the same type in one go, you can do some optimizations that are not possible when each component is a separate object with an update function that could be called at any time.

Note that I've still never called for the creation of a XxxComponent class to hold component data. That's up to you. Do you like Data Oriented Design? Then structure the data in separate arrays for each variable. Do you like Object Oriented Design? (I wouldn't recommend it, it will still kill your performance in a lot of places) Then create a XxxComponent object that will hold the data of each component.

The great thing about the managers is encapsulation. Now encapsulation is one of the most horribly misused philosophies in the world of programming. This is how it should be used. Only the manager knows what component data is stored where, how a component's logic works. There are a few functions to get/set data but that's it. You could rewrite the entire manager and its underlying classes and if you don't change the public interface, no-one even notices. Changed physics engine? Just rewrite PhysicsComponentManager and you're done.

Then there's one final thing: communication and data sharing between components. Now this is tricky and there is no one-size-fits-all solution. You could create get/set functions in the managers to allow for instance the collision component to get the position from the position component (ie PositionManager.getPosition(entityID)). You could use an event system. You could store some shared data in entity (the ugliest solution in my opinion). You could use (this is often used) a messaging system. Or use a combination of multiple systems! I don't have the time or experience to go into each of these systems, but google and stackoverflow search are your friends.

# Answer
> 3 votes
> In order for these components to work they have to updated every frame, the easiest way to do this is to walk over the scene tree and then for each entity update each component.

This is the typical naive approach to component updates (and there's nothing necessarily wrong with it being naive, if it works for you). One of the big problems it has you actually touched on -- you're operating through the interface of the component (for example `IComponent`) so you know nothing about what it is you just updated. You likely also don't know anything about the ordering of components within the entity, so

1. you're likely to update components of differing types frequently (poor code locality of reference, essentially)
2. this system doesn't lend itself well to concurrent updates because you aren't in a position to identify data dependencies and thus split out the updates into local groups of unrelated objects.

> I have thought about using a singleton manager object for each of the components types but that has the usual drawbacks of using a singleton, a way to alleviate this is a bit is by using dependency injection but that sounds like overkill for this problem.

A singleton isn't really needed here, and so you should avoid it because it does carry the downsides you mentioned. Dependency injection isn't overkill -- the heart of the concept is that you pass things that an object needs to that object, ideally in the constructor. You don't need a heavyweight DI framework (like Ninject) for this -- just pass an extra parameter to a constructor somewhere.

A renderer is a fundamental system and it probably supports creating and managing the lifetime of a bunch of renderable objects that correspond to visual things in your game (sprites or models, likely). Similarly, a physics engine likely has lifetime control over things that represent the entities that can move around in the physics simulation (rigid bodies). Each of those relevant systems should own, in some capacity, those objects and be responsible for updating them.

The components you use in your game entity composition system should just be wrappers around the instances from those lower-level systems -- your position component could just wrap a rigid body, your visual component just wraps a renderable sprite or model, et cetera.

Then the system itself that owns the lower-level objects is responsible for updating them, and can do so in bulk and in a way that allows it to multithread that update if appropriate. Your main game loop controls the crude order in which those systems update (physics first, then renderer, or whatever). If you have a subsystem that doesn't have lifetime or update control over the instances it hands out, you can build a simple wrapper to handle the update of all the components relevant to that system in bulk as well, and decide where to place that update relative to the rest of your system updates (this often happens, I find, with "script" components).

This approach is occasionally known as the outboard component approach, if you're looking for more detail.

---
Tags: component-based
---


# Question
Title: How to display an image stored in GPU video memory
My platform is Windows PC and C++. I am using an image buffer in GPU video memory via CUDA. Is there any way to directly send the content to GPU for display? Currently, I am getting the content into system memory and then use API function (such as GDI, OpenGL. DirectX) to send it back to GPU for display. I wonder if there is a faster way to do this.

# Answer
You can bind a CUDA array as a texture, and then use that texture for rendering. There are restrictions on valid texture formats, and limits imposed on CUDA arrays to make this all work, but it does.

The specific API call in CUDA varies by which graphic API you're using, but look for "register resource."

Basically, create the texture with the appropriate image data like you wanted to render it (say, with D3D's `CreateTexture` or GL's `glTexSubData2D`). Register the texture with CUDA using the appropriate API (`cudaGraphicsGLRegisterImage` for OpenGL). Bind the registered texture to a CUDA array (`cudaBindTextureToArray`).

Do the same for your render buffer (output texture, FBO bound in GL or `RenderTarget` bound in D3D, using slightly different methods to bind/map it to CUDA - see the docs). Run your kernel. Bind the output texture for rendering in API of choice. Render using it as source, e.g. as a full-screen quad.

A not-great but not-terrible article with OpenGL integration with CUDA is on 3dgep.com.
> 4 votes

# Answer
Maybe this might not be of use to you, but Direct Compute will let you create a UAV (which can be used to calculate stuff onto, aswell as render to the display.

Direct Compute is staright forward and isent much of hassle to implement. i have used this myself when doing GPGPU stuff.
> 1 votes

---
Tags: gpu, cuda
---


# Question
Title: Getting a 2D "pixel" cloud to follow a mouse
I'm working on a 2D game trying to get a "cloud" of a few hundred tiny cubes or discs to follow my mouse cursor without overlapping each other.

However, using the physics engine introduces performance sluggishness as the number of discs grows and the collision detection is generally wonky.

Is there an easy way to optimise the engine for this kind of thing? If not, would I be better off just switching the engine off and writing something of my own? (Clutching at straws here, but:) Are there any good resources or examples on how to do this?

# Answer
Yes, using a physics engine for that would be a little overkill. I suggest you implement a flocking algorithm. The basics of which are:

* Separation: Steer to avoid crowding local flockmates
* Alignment: Steer towards the average heading of local flockmates
* Cohesion: Steer to move toward the average position of local flockmates

You can see it in action here and get some details on its implementation. You'll do some minor tweaking to include applying a force towards the mouse pointer.
> 13 votes

---
Tags: 2d, physics, unity
---


# Question
Title: Using timer to reverse enemy movement in Flash game made with Flixel
I am creating a 2d flash game using Flixel 2.5 in Flash Builder. I am trying to reverse enemy movement on an interval so that they will move back and forth over a set space. I felt that a timer would be best for this situation. The enemy class extends FlxSprite. I have three class level variables to help with managing the sprite's direction:

```
private var _movementTimer:Timer;
private var _movementTimerEvent:TimerEvent;
private var _forward:Boolean;
public var _directionSet:int = 0;

```

In the constructor, I instantiate the timer like this:

```
//create timer for movement
_movementTimer = new Timer(3000);
//set listener for movement
_movementTimer.addEventListener(TimerEvent.TIMER,SetDirection);
//start timer
_movementTimer.start();
//set initial direction
_forward = true;

```

The function called on the timer interval is as follows:

```
/*Reverse direction of this sprite*/
        public function SetDirection():void
        {
            _directionSet++; //increment direction set for debug purposes
            FlxG.log("direction set");
            FlxG.log(_directionSet);

            if(this._forward)
            {
                this._forward = false;
                //set the direction the sprite is facing
                this._facing = RIGHT;
            }
            else
            {
                this._forward = true;
                //set the direction the sprite is facing
                this._facing = LEFT;
            }

        }

```

Then, the update function evaluates the `_forward` flag to determine direction of movement:

```
/*Update this sprite*/
        override public function update():void
        {
            super.update();

            if(this._forward)
            {
                this.acceleration.x = this.maxVelocity.x * .5;
            }
            else
            {
                this.acceleration.x = -this.maxVelocity.x * .5;
            }
        }

```

However, my sprite is not reversing direction, it just continues forward. What am I missing?

EDIT:

I added additional variables and calls to FlxG.log for debugging purposes, and it seems that `SetDirection` is never called, but I am not sure why.

# Answer
> 1 votes
Your signature for `SetDirection()` is incorrect. It should be `SetDirection(e:TimerEvent)`. Flash can be forgiving about this sort of thing resulting in some infuriatingly subtle errors.

# Answer
> 3 votes
Using Flash's built in`Timer` isn't a great idea in Flixel. You should really use the `Update` function in conjunction with `FlxG.elapsed`, as this will respect pausing and resuming the game using Flixel.

Here's an overview of how to use Flixel's timing:

http://flashgamedojo.com/wiki/index.php?title=Timer\_(Flixel)

---
Tags: flash, actionscript-3, movement, timer, flixel
---