# Question
Title: Is my idea of how to use matrices to layer 2D on top of 3D correct?
I'm new to using matrices, so I'd like some input on whether I've understood the use of them in the context described in the title.

Right now I have a small Direct3D 11-based game engine which renders a stack of scenes, or screens if you will, from bottom to top. I have a static 2D orthographic view-projection matrix that simply maps to screen coordinates from ( 0, 0 ) to ( screen width, screen height ). The position and resulting world matrix of the different entities are set with coordinates relative to this.

However, I'd like to expand on this by enabling different scenes to use different perspectives, so that I would be able to render a 3D scene with perspective, and then a flat 2D GUI on top of it. But since I'm very new to using matrices, I'd like confirmation on whether I have the correct idea of what will happen before I change things, because it takes a fair amount of work to refactor the engine with the way it is set up now.

Let's say I have `Scene A` as the 3D scene, and `Scene B` as my 2D overlay.

When entities in `Scene A` is rendered, the following matrices are passed to the shader:

* `View` = camera position/orientation in the 3D world
* `Projection` = perspective matrix with FoV, aspect ratio and near/far depth
* `World` = the individual entity's position in the 3D world

Then, when I want to render `Scene B`, I pass these matrices instead:

* `View` = identity matrix since the view is static
* `Projection` = orthographic matrix with screen coordinates
* `World` = the individual entity's position in the screen coordinate system

In both cases the vertex shader multiplies the matrices like so: `world * view * projection`

Is this correct? Will this draw my 3D scene as expected first, and then correctly draw the 2D elements relative to the screen coordinate system instead? Or have I misunderstood how the matrices work?

EDIT: scratch the question below; I found the answer under related questions...: Should the modelview and projection matrices be calculated in the shader or on the CPU?

Original question: And one more thing, would it be more efficient to compute the View-Projection-World matrix on the CPU end before passing it to the shader's constant buffer, or is the GPU better suited at receiving the three matrices and multiplying them on the shader side? I've seen both approaches used, but I haven't found any conclusions on which way is more practical/efficient. I have two constant buffers by the way, one with the View and Projection matrices which is updated once per scene, and one with the World matrix updated for each individual entity, so the memory bandwidth savings would be insignificant if I moved the multiplications to the CPU instead. But would that be faster in theory, and are there any eventual drawbacks to this?

# Answer
The matrix calculations, as long as they are constant for a frame being rendered, should be calculated by the CPU and sent to GPU. Multiplying matrices is not an expensive operation for the CPU as you might think. But if you pass it to the vertex shader, the same matrix result gets calculated n times, where n is the total number of 3D vertices being rendered for that frame, which is totally inefficient no matter how fast that might be. That is unless you have a method of calculating the matrix in vertex shader just once. If you do, then its great. Otherwise just 'keep it simple'. Calculate them in CPU and set them as constants to the shader.
> 0 votes

---
Tags: matrix, directx11
---


# Question
Title: Extract derived 3D scaling from a 3D Sprite to set to a 2D billboard
I am trying to get the ***derived* position** and **scaling** of a 3D Sprite and set them to a 2D Sprite.

I have managed to do the first part like this:

```
        var p:Point = sprite3d.local3DToGlobal(new Vector3D(0,0,0));
        billboard.x = p.x;
        billboard.y = p.y;

```

*But I can't get the scaling part correctly.* I am trying this:

```
        var mat:Matrix3D = sprite3d.transform.getRelativeMatrix3D(stage); // get derived matrix(?)
        var scaleV:Vector3D = mat.decompose()[2]; // get scaling vector from derived matrix
        var scale:Number = scaleV.length;
        billboard.scaleX = scale;
        billboard.scaleY = scale;

```

...but the result is apparently wrong.

PS. One might ask what I am trying to achieve. I am trying to create "billboard" 3D sprites, i.e. sprites which are affected by all 3D transformations except rotations, thus they always face the "camera".

# Answer
You could project each vertex of your 3d sprite to screenspace and then calculate the distance between these points to get the size of the sprite on screen.

To do billboarding, I always find a helper LookAt function is useful. It will orientate your game entity towards a point in space. To billboard you just make it LookAt the camera position. (The alternative is getting the inverse of your view matrix and using that to apply the appropriate rotation).

Here's a link to at LookAt implementation: http://msdn.microsoft.com/en-us/library/windows/desktop/bb281710%28v=vs.85%29.aspx
> 1 votes

---
Tags: flash, actionscript-3, matrix, transformation
---


title: Swaying Camera when Walking

text:
# Question
Title: Swaying Camera when Walking
You can see the effect in many games. The camera sways or wiggles a bit while walking to make the movement feel more realistic.

I have implemented a camera in my game. (Who'd have thunk it?) So is there a common approach to build this swaying effect in?

# Answer
> 8 votes
Applying a transformation to the world from the point of view of the camera is the most straight forward way.

When the character advances the camera can be modeled as a cartwheel without the wooden circle, keeping just the wooden sticks. This curve is called cycloid.

Also with each foot step the camera needs to move slightly to one side or the other as if the wooden sticks where separated by the horizontal distance between the two legs, balancing the center of mass to keep it vertically aligned with the foot touching the ground.

The two movement seen from the point of view of the camera would look like half a circle (or an ellipse).

Approximating the cycloid to a sinusoidal, the translation would be given by:

```
translation( A * cos(d + pi/2), B * sin(pi/2 - 2*d), 0 )

```

Where *d* is the distance since the character started to move. The movement speed can be modified by multiplying d by a factor, or the values of *X* or *Y* by an arbitrary amplitude.

---
Tags: camera, movement, effects
---


title: Using circles to create a sphere

text:
# Question
Title: Using circles to create a sphere
I've been working on creating spheres in a 3D space recently, and have successfully created cylinders. I've just run into a little problem. For some reason, my "Spheres" end up looking like very thick star shapes. I can't seem to figure out what's wrong, and I could not really find any algorithms to reference off of. My code:

```
public static void createCircle(int xoff, int yoff, int zoff, int FOV, ArrayList<Point3D> Points, int radius) {
    for(int j=0;j<Math.PI*2;j++) {
        int x = (int) (radius * Math.cos(j));
        int y = (int) (radius * Math.sin(j));
        Points.add(new Point3D(x+xoff, y+yoff, zoff, FOV, 900, 600));
    }
}
public static void createSphere(int radius, int height, int FOV, ArrayList<Point3D> Points, int posx, int posy, int posz) {
    for(int z=0;z<height;z++) {
        createCircle(posx, posy, posz+z, FOV, Points, (int) (radius*(Math.sin(z)*2)));
    }
}

```

Here's what it ends up looking like:

# Answer
> 3 votes
You are using integers for all your numbers, unless you have a very specific purpose and know what you are doing, stick to floats for geometry.

Your radius calculation is completely wrong, in `createSphere` you should do something like:

```
for(float angle=0;angle<Math.PI;angle+=0.1){
    createCircle(posx, posy, posz + Math.cos(angle)*height/2, FOV, Points,
        Math.sin(angle)*radius);
}

```

---
Tags: 3d, algorithm, trigonometry
---


# Question
Title: How can I make a falling down effect in 2D - Birds Eye View
Currently whilst making my game, I'm not sure how I am going to implement the actual gameplay/environment of it. At first I thought to do a side-on plat-former, where my character falls down the screen, from the side on. However, I think it would be much better gameplay (better gameplay mainly for mobile) to do this falling down in a birds eye view perspective.

What I want is my character to start at some arbitrary point in the world (say the sky) and fall down infinitely. Obviously, I don't actually have to make the character fall down, but I have to make it so that it looks like it is. Now I'm no artist, but how would an artist make art for the scrolling down background? Would he/she have to create sprites for the objects in the environment (i.e. clouds)?

Reference Image (sorry for the quality, and don't judge my lack of art skills):

Now as you can see, my character (the turtle) is in the sky. I eventually want it to go past the clouds and look like it is going closer the ground. Now that I think about it, would it be better for this type of game to not actually transition the setting (i.e. keep one type of setting per game). What I mean is should I just keep the sky so the character never reaches the "bottom".

# Answer
Implement some perspective in your game. Orient your fall direction to be at the center of the screen. Objects that are in the fall path and far away will be near the center of the screen and small. As they get closer, they grow in size and move outwards.

Note how the straight street appears to get smaller. Since the direction of the perspective is at the center of the screen, all the horizontal lines point towards the center of the perspective. The lines in this perspective will be the same as the travel paths for your objects as the player gets closer to them. Also note that the object displayed is as large as it's going to get, right before moving off screen and not being visible anymore.

See this question (and my answer) about simulating the movement of 2D objects toward the screen. Basically it's a scale operation in place of moving the object along the z axis.

The artistic style is up to you. You can have a far away ground that never gets closer or just have blue sky. That bit is just art related, it's not important to the implementation.

"Moving" the objects past the player is just an issue of scaling all the objects more and more the longer they're on screen. They should then pass outside of view along the edge of the screen once they've gotten to their full size. All of your objects will have some on screen path that matches the above image. Moving from somewhere near the center to which ever portion of the edge is closest to them. The scale will change from smallest when near the center to as large as the object is once it's almost done with it's path. See my other answer for details on how you might calculate the scale for an object depending on how long it'll be on screen.
> 3 votes

# Answer
If you would like to have almost 3D models in your game then you have to make it as a 2,5D. So you have to draw your spirtes as if you were looking at them from an angle (birdeye angle, like 45 degrees) then that is called isometric view. For the falling effect, you only have to move the offset of your spirtes by the height of the falling turtle.

Like you have a cloud at x:100 and y:200 and the turtle is at x:100 y:300 you have to say height-otherobjecty (300-200). Also you have to set the distance from the camera (z).

And you can make the clouds at runtime dinamically or make the as sprites and load them.
> 1 votes

# Answer
For the absolute background, don't put anything, keep the eternal blue sky and just fill the scene with many white clouds, so it looks like these don't let you see the ground. This way, you can fall and fall without worrying if the ground is getting closer.

As for the sprites, just zoom them and move them to the outer spaces of the viewpoint so they look like they are coming closer. The problem with this kind of games, is that it is hard to know for the player when an object is close enough to hurt him; has happened to me many times with games alike.
> 1 votes

# Answer
If it is a scoring game, you better have to set an image for the ground and never change it. So that players can play undefinaly.

The falling effect would already be nice just with the clouds and the other objects zooming.

If you want them to have a time limit to finish the level, you better have to set an image and makeit scale/zoom while the timer is running.
> 0 votes

# Answer
You could just spawn the cloud sprites in random location, but really small and just make them bigger over time. Thereby giving the effect that the character is falling downwards (To put it another way, falling under the phone).

Regarding changing the background (ie. The ground). Don't modify it, although if it looks a little flat, I suppose you could shift the ground ever so slightly (just a little in a random direction). Just so that the ground moves as well. Just a thought.
> 0 votes

---
Tags: game-design, graphics, art, graphic-effects
---


title: Walk to nearest attackable range node

text:
# Question
Title: Walk to nearest attackable range node
My game has 3D environment which is partitioned in 2d cells(nodes). I have implemented A\* for path finding.

Now I am just breaking my head to how to implement the algorithm to move the hero to the nearest attackable range node/point when the enemy is out of attack able range.

Which means, it should satisfy two conditions

1. Target whithin attackable range
2. No obstacles in between the target and attacker

See below picture (pardon for my bad drawings)

* Brown boxes are obstacles
* Attacker/hero is in the cell highlighted with Turquoise color dot, the circle is the radius/size of the model.
* Target is the red dotted color cell, surrounded with red color circle to indicate the size of the model
* Green circle is the radius where hero has to move to some where inside that location to attack (its the radius of hero's attack range)
* Blue dots are the A\* path to reach from hero position to target position

When the player issues attack command, hero should move to the nearest attack able node and start attacking.

Finally I thought of below algorithm

1. Calculate radius to scan - This is the sum of attacker radius + attacker weapon radius + target radius
2. Get nodes fall within the radius (from step 1) from targets position
3. Find path from attacker to target using A\*
4. Keep walking in the path (from step 3)
5. check if current node is in the scanned nodes (from step 1)
6. If true,
7. Check that no obstacle are in between
8. If true, attack, if false keep walking (repeat step 4)

If we put together the algorithm and the figure1

The A\* gets the path of 9 node to reach the target After moving 5 steps, it enters the attackable range, since there is obstacle between the target, it take two more steps where it finds no obstacles and stats attacking.

I am not sure if this is the optimized method to achieve this but I am not getting alternative solution.

Very particular to the steps 2-5 which looks little weird and process intensive to me.

I am using actionscript 3 and Flare3D (Stage3D API)

# Answer
Your algorithm looks fine, I'd do it like that myself.

The only thing I'd change is points 2 and 5 - you don't need to build a collection of valid nodes and check if current position is in the collection. You're only interested in being close enough to the target. I'd drop point 2 and replace point 5 with "check if current node is within the radius". It's a simple distance check, should be much cheaper than filling a datastructure and searching within it.
> 1 votes

# Answer
There is one other option you might want to consider, which might result in better playing experience.

after step 2, where you create a list of all possible you can find a path starting from yourself to the nearest point. The basic concept is just like A\* with a single difference in heuristic function. In a normal A\* you have a single target and you have a way to predict how many more steps you have to take to reach it. with multiple target you should predict the number of steps remaining for each of target nodes, and return minimum.
> 0 votes

---
Tags: actionscript-3, path-finding, stage3d
---


title: Changing Yaw, Pitch And Roll OpenGL

text:
# Question
Title: Changing Yaw, Pitch And Roll OpenGL
I'm using LWJGL and OpenGL 1.1 at this time and I was wondering what command is used to change the yaw, pitch and roll?

# Answer
glRotatef

```
glRotatef(Angle.X, 1.0f, 0.0f, 0.0f) ;
glRotatef(Angle.Y, 0.0f, 1.0f, 0.0f) ;
glRotatef(Angle.Z, 0.0f, 0.0f, 1.0f) ;

```

(which of those angles are 'yaw', 'pitch', and 'roll', and the order in which you apply them, will depend on which axis you're considering to be 'up')
> 2 votes

---
Tags: opengl, java, 3d, lwjgl
---


# Question
Title: Make a 2D character stop moving and going back when encounter an obstacle
I am using a 2d character who is sliding infinite ( huge incrementation of the X or Y value ) when moving. He can only move up, down, left, right inside a virtual grid, made of multiple squares.

Now I want to add obstacle to stop his sliding and make him go back to the center of the previous square

The obstacles can be of different size and are located in the center of a square, so the collision occurs with the obstacle and NOT when the character enter the square containing this object !

How can I manage to stop the incrementation of X or Y when colliding ? And get the previous value of X or Y for which the character was on the center of the square just before the one containing the obstacle.

Thank you everybody !

---

I am not certain to have the good reasoning. Actually I was thinking about something like that :

Lets say each square is 5 * 5 and each square center is at X + 5 from the previous square center and X - 5 from the next. I was thinking about a loop which is moving the character from + 5 on the X axis and checking if there is a collision. If yes, the character goes back to the previous square center, if not, the loop keep going.

So assuming that my character is in ( 0 ; 0 ) coordinates and the obstacle is in ( 20 ; 0 ) coordinates ( but not filling the square ), my character will be in ( 5 ; 0), then ( 10 ; 0 ), then ( 15 ; 0 ), then it will collide with the object in ( 18 ; 0 ) ( because the object dont match exactly with the square size, considering the fact that on object can be 3\*3 and just drop on a 5\*5 square ), and the character will go back to ( 15 ; 0 ).

With this reasoning :

* is the movement of my character going to be smooth ( like a slide ) or is it going to be square by square ?
* if checking the collision BEFORE moving, is my character going to move from ( 15 ; 0 ) to ( 18 ; 0 ) and bounce back to ( 15 ; 0 ) or is it just going to stay in ( 15 ; 0 ) ?

because I would like to have my character to move smoothly AND bouncing back when colliding !

Thank you

# Answer
You'll stop the incrementing of X or Y when a collision is detected. That'll depend on where you're looking for collisions. I assume it would be before you move your character to its new position.

Getting the center of the previous square isn't too hard either. Since your squares are equal sized, it's easy to round to the nearest center position in the opposite direction of travel. For example, if the direction of travel is in the X positive direction and the X position is at `43.3` when you collide. You know that there's a center square at `n.5` along the X axis. Since you were going in the X positive direction, you want to find the nearest center in the X negative direction. So round the X position down to the nearest integer and subtract `.5`.
> 3 votes

# Answer
You generally want to have the player's X and Y coordinates and the player's X and Y velocity...You determine the velocity then add the velocity to the x coordinate to move, then you subtract the velocity from the x coordinate to stop.

```
if (right)     player.xVel+=player.movementSpeed;
else if (left) player.xVel-=player.movementSpeed;

player.x+=player.xVel;
if (collides)  player.x-=player.xVel;

```

You could probably do the following, but I've always moved the player before checking collisions to simplify my code, so I don't know how well this method would work...

```
if (!collides) player.x+=player.xVel;

```
> 0 votes

---
Tags: android, animation, movement, character
---


# Question
Title: How do I gain access to objects in order to change their properties in Unity?
I have created a GUI text object named "GUIText" in the Unity editor, and I want to change what the text says via code (I'm using C#). How do I access GUIText1 to change its string properties?

I want to be able to write code like this:

```
GUIText1.Text = "";

```

In general, I'm not sure how to get access to any sort of object created in the editor (a mesh or a light for example). How do you access them in code?

I already know how to write the scripts and trigger them.

# Answer
Considering GUI Text is a component of a gameobject in your scene, you can do this:

In the script where you want to make the change, you add a public field of type GameObject, like so:

```
public GameObject someObject;

```

Make sure the script inherits from MonoBehavior; you have to add the script as a component to some game object of your choosing. For example, create an empty gameobject somewhere, and add the script to it. If you've done everything correctly, you should be able to set the reference to the gameobject that contains the GUI Text component via the visual editor (just click on the gameobject that contains the script with the public GameObject field).

Next, in the Start() method of the script you write:

```
GUIText guitext1 = someObject.GetComponent<GUIText>();
//Do something with guitext11 e.g. guitext1.Text = "";

```

Alternatively, you could use a GUIText reference instead of a GameObject one; referencing it via the editor should work the same, though by doing it the way I wrote above you also get to know how to manually access a particular component of a GameObject.

In case you get stuck:

```
class MyScript : MonoBehavior
{
   public GameObject someObject; //You set this with the editor.

   private void Start()
   {
       GUIText txt = someObject.GetComponent<GUIText>();
       txt.Text = "";
   }
}

```
> 1 votes

---
Tags: unity, objects
---


# Question
Title: Find the footprint of an isometric entity
I'm working on making a 2D isometric engine in Java. I'm getting into collision detection and I've hit a bit of a problem.

Characters in-game are not restricted to movement from tile to tile - they move freely. My problem is that I'm not sure how to stop a player from colliding with, say, a crate, without denying them access to the tile.

For instance, say the crate was on .5 of a tile, and then the rest of the crate was off the tile, I'd like the player to be able to move on to the free .5 of the tile instead of the entire tile becoming blocked.

The problem I've hit is that I'm not sure how to approximate the size of the footprint of the object. Using the image's dimensions don't work very well, since the object's "height" in gamespace translates to additional floorspace being taken up by the image.

How should I estimate an object's size? Mind, I don't need pixel-perfect detection. A rhombus would work fine.

I'm happy to provide any code you might need, but this seems like a math issue.

# Answer
> 2 votes
You'll need to provide data (or explicit code) specifying the object's floor size. There's really no way for code to automatically figure out, for an isometric image, what portion of the image is flat on the ground, and what portion is vertical -- you'll need to specify that information yourself.

On the other hand, it's a fairly common thing to just treat the whole area encompassed by an object as unwalkable. If you allow the player to walk behind a large crate (for example), it's easy for him to go out of view, and no longer to know what's going on. So you might be able to just get away without doing anything special, if you're happy to do that.

---
Tags: 2d, java, collision-detection, mathematics, isometric
---


title: Multiple pipelined game loops

text:
# Question
Title: Multiple pipelined game loops
I am considering using the following game engine design pattern, but I am unsure if it's a good idea or not:

* Each major task (drawing, physics, logic, networking, disk I/O) will have its own isolated thread or subprocess
* Each of these threads can be put to sleep if it is running too quickly, so as to not consume an excess of CPU resources
* Threads can only talk to each other through some well-defined interface to avoid messy, buggy, thread-unsafe conditions from occurring
* This approach enables parallelism and scalability, but causes a thread safety problem: what if one thread is accessing data that another thread is currently processing?
* We could introduce fine-grained locking, but it still can't be guaranteed that the collective states of all of a thread's data objects are coherent.
* To solve this, collections of objects are maintained inside state objects, and state objects are double-buffered. The intent of this is to ensure that other threads only see a valid, coherent set of data. If one thread happens to be processing data that another thread wants to read, then the other thread reads from a buffered state, which is guaranteed not to be written to.
* However, buffering these states introduces a delay where one thread sees old data from the last cycle of the other thread.
* Another problem might occur when a reading thread has a slower "tick rate" than a writing thread: the writing thread may have flipped the state buffer multiple times, while the reading thread is still processing one "tick" using the same state. However this can be solved using OO references.
* Pipelining should be achievable using this approach, because the draw thread could be drawing information that entered the pipeline 30 milliseconds ago, while more information is being processed
* Ultimately, what I'd like to see is completely decoupled processing for all of the tasks in a game, implemented in a way that helps leverage multi-core environments, and maybe leaves some future expansion room for scaling the server side of things amongst multiple machines. I am aware that this is probably overkill for most purposes :-)

What are the criticisms or pitfalls of this approach? Is this the "right" way to do things? Am I thinking about this backwards?

# Answer
The benefit to pushing your *rendering* to its own thread separate from the game logic is to give the player the illusion that they are getting higher FPS but reality is that in most cases, you're really just drawing the same state over and over more often by doing so since you should be batching rendering commands to the rendering thread through a set interval of your logic thread's fixed time-step.

For File IO and even Network IO, I would consider using asynchronous IO. Whether you opt to use a library for this or not, there is serious advantages to using Asyncronous IO. I wouldn't offload this to another thread however, I'd make use of OS-centric constructs to perform non-blocking IO. This provides you the means to swap between blocking & non-blocking where appropriate for IO without having to concern oneself with threading.

For game logic, I use the notion where I update logical systems in sequential/serial order but the update loop itself operates in a batched parallel\_for() manor where I operate on small buckets of components for a given operation across multiple threads.

```
Thread 1 - Components 1 through 50
Thread 2 - Components 51 through 100
Thread 3 - Components 101 through 150
Thread 4 - Components 151 through 200

```

What I prefer about all these approaches is that if you simply double buffer the command queue between the render thread and the logic thread, you can render as fast as possible, you can update on a set interval and you can manage all the above multi-threading goodness with nearly little to no need for locks, making the execution speed as robust as possible.
> 5 votes

# Answer
I don't prefer multiple threads for each process. I use one thread for logic and rendering and a thread for each sound (say asynchronously) so that the sound system doesn't prevent logic and rendering thread. Though I use the same thread for logic and rendering, I separate them so that the game renders only after the logic has completed. Here's my game loop.

```
private void gameLoop(){
    long now;
    long gameTime;
    long ups = 33;
    long frameTime = 1000/ups; // 30ms for each frame
    while (running){
        now = getCurrentTime();
        while (now > gameTime){
            updateFrame(frameTime);
            gameTime += frameTime;
        }
        renderGame();
    }
}

```

This implementation is getting me 90-100 fps on my 2.6 GHz duel core machine with 1 GB RAM. If you are using java, please see my game engine `here`
> 2 votes

---
Tags: game-loop, multithreading, pipeline
---


# Question
Title: Handling movement using an Entity Component-based System Architecture
I have seen various descriptions of how to handle movement in a component-based entity framework. The most common I've stumbled across is the idea of using components called *Controller*, *Physics*, *Transform*, *Velocity*, and *Collider*.

The idea here is that the *Controller* influences the *Velocity* component when movement keystrokes are detected. The *Velocity* component in turn influences *Physics*. Once the simulation has been stepped, the *Collider* is either affected if a collision occured or is not if no collision happened. In the end, the *Transform* is updated with the new position from the physics simulation step and thusly the *Renderable* needs to be adjusted so it is drawn in the proper location.

I have often read that one needs to consider both physics-driven and non-physics-driven entities. As outlined in the above paragraph, manipulating physics-driven entities seems like a piece of cake. The difference with non-physics-driven entities is that the *Velocity* component values need to simply be applied to the the *Transform* based on delta-time. This would allow moving the entity without being concerned with physics nor collision detection.

For physics-driven entities, one simply iterates entities with both *Velocity* and *Physics* components. But for non-physics-driven entities, simply iterating over entities with a *Velocity* component isn't sufficient as it would include the above subset as well.

So there must be some factor that clearly separates these two cases. So with these two cases in mind, how would movement actions that influence the values of *Velocity* be carried out in such a system to manipulate both types of entities whether physics plays a roll in their movement or not??

And lastly, considering that there may be times where the transform for an entity needs to be manipulated directly, such as player clicking on a portal to be teleported to another x/y/z position, how would one properly propagate this change to adjust both the physics step simultation and the renderable's draw location?

EDIT: @bobenko Your explanations provide insight to the most common case where objects are simulated via physics but I'm somewhat lost on the Kinematic aspect regarding updating an entities position via a velocity value? Are you simply implying that some code of my own will apply movement to the entity via velocity, thus being Kinematic? I still am interested in your explanation on how to avoid cyclic notifications effectively when aspects of these components involved change.

For all who answered, I'm still not clear how would you handle teleporting an entity from one position to another? Would this involve turning *off* physics, teleporting the player, then turning physics *on* after teleport finished? Turning physics on/off can be as simply as setting the entity as Kinematic YES/NO, right?

# Answer
> 4 votes
With your **Physics** you subscribe to changes of your **Transform** component. So when transform position changed directly you Physical part also moves. And after physics simulation you can directly change Transform-\>position from **Physics**, because entities which have Physics will always have Transform.

What about direct moving of objects without physical simulation, you can use *Kinematic* bodies most of engines provides their support. Or you can directly write your *position+=velocity* in any your script. Or create some *BasicPhysics* component and then just adjust properties.

# Answer
> 1 votes
The basic setup for interaction with physical simulation has already been covered by user bobenko. I've implemented it more or less like this myself and it works fine.

However, a problem that occurs when multiple Components each add their own movement to the same object during the frame is that velocity is no longer a value you can simply store somewhere and set from the outside, as suggested by your Velocity Component. My solution was, in short:

* The Transform Component stores a velocity value, but doesn't apply it. This is just a "for your information" stat.
* If some Component wants to move the object (not teleport it), it wouldn't just set the position (obj.Pos += vel) but call one of several specific Move methods exposed by Transform. They remember the applied velocity in a local variable and accumulate it throughout the frame.
* Actually, the Transform Component stores two velocity values: One that is accumulated and one that is exposed for read access - the actual velocity value that has been determined last frame. When the Transform Component updates, the accumulator is written to the readout value and then set to zero.

That way, Transform isn't only a central place to store the current position and rotation values, but also a place where all the modifications done to them in one frame are gathered for public usage. I read those values out for velocity-specific effects such as the doppler effect for the sound system.

---
Tags: entity-system, component-based, entity-component
---


# Question
Title: How do I find realistic 3D paths for stable and unstable flying rockets?
I am building a 3D application that simulates launching small rockets. I want to draw their trajectories.

I know that rockets have a degree of stability. I want to include this in the simulation, but I don't know what the physics would look like.

How do I go about calculating a rocket's trajectory?

# Answer
I would take a physics engine, model rocket, add force to jet and just save state in a list of time points. Its no need to be in runtime, you can change parameters from code.
> 2 votes

# Answer
I can think of three interesting paths to plot:

1. the *projected* path of the rocket at launch,
2. the *projected* path of the rocket from the current point in time,
3. and the path traveled by the rocket so far.

From any point in time, you can project where the rocket will land by stepping forward and assuming constant flying conditions.

But as the rocket actually moves, you'll likely want to add in slight random fluctuations in things like wind strength and direction, and perhaps imperfect burn from the rocket itself, and this introduces error between the projected path and the actual path.
> 0 votes

---
Tags: 3d, physics, trajectory
---


# Question
Title: When and where should I calculate collision response with multiplayer physics?
I've troubles wrapping my head around multiplayer physics and collisions on the client side, so far I interpolate the state of my network entities ( position and velocity ) of the other clients based on the snapshot data I receive, but how should I handle collisions on the client side?

If I bump into another player, should I calculate the new position of the other player immediately after I interpolated the state or should I just predict the collision response of my local player and don't set a new position / velocity of the network entity on my client?

# Answer
> 3 votes
In general, the server should be the sole authority for calculating object positions and movement vectors. The clients should only send their *intention* to move to a certain destination or into a certain direction, and the server should respond with a new movement vector, when it decides to allow the client to do so.

The server should also be allowed to send movement vectors which are not a response to a client, or even directly contradict what the client is saying, like when the movement destination of the client is blocked by another object.

A client *can* assume that the server will allow them to perform a move and already show the player character moving even though the server didn't sent a new movement vector. This makes the network latency less apparent to the user and thus offers a more fluent game experience. But the client should be prepared to correct the position of the player character when the server decides to deny or interrupt the movement, for example because there is a collision with another object.

Example:

1. User issues a move command
2. Client checks if the move may be performed according to its current view of the game state, and decides that it's possible
3. Client sends the move command to the server, and already starts to move the player character, because it assumes that the server will allow it.
4. Server receives the move command, and decides to deny it because there is something in the way the client wasn't aware of or didn't consider to be in the way due to timing differences
5. Server sends a rejection message to the client
6. Client stops moving the player character and moves it back to the original position

---
Tags: collision-detection, physics, multiplayer, mmo
---


# Question
Title: Simulating "line of sight" with obstacles on 2d grid?
Ran into an interesting problem. I need to figure out how to simulate line of sight - simple enough, just on a 2d grid with obstacles. Either a grid cell is visible, or it's not.

I can get something really rudimentary going - like spreading n spaces from player, or blocking horizontal propagation when an adjacent obstacle is detected, but I can't let myself live with it. Plenty of other apps are using more sophisticated methods that slope the line of sight around corners etc, and I want to be up to par.

So far DCSS has been my source of inspiration when I'm stumped, I'm hoping to get something close to what they have: http://crawl.s-z.org/.

Any insight would be appreciated - thanks for the help!

(Forgive if this is embarassingly noobish - only started game dev a few weeks ago, trying hard to catch up.)

# Answer
> 7 votes
Ray casting is a very fast and efficient way to determine line-of-sight. It basically involves sending a ray (think of it like an infinite laser that can't be redirected) from a certain position in a certain direction. Using this ray, you can determine things like which point(s) it intersects and how far away from the origin it was when it crossed a certain point.

So for example, in a player/enemy scenario, the ray could originate from the enemy with the direction being the location of the player. If the ray collides with a solid tile, the enemy can't see the player. If it doesn't, the enemy can see the player.

Here is an excellent tutorial that will should help.

You can also consider Bresenham's line algorithm (summed up, it creates lines) for something that might be more easily scaled to tiles.

# Answer
> 3 votes
I have blogged code to compute line of sight from a height-map. A simple flat map with obstacles is just a very flat height-map, and this implementation is still completely applicable.

Here it is in C++ and its `O(n)`; if you know the maximum height in the map, you can track a scanline that has no rays remaining under that height, and early-out:

```
typedef std::vector<float> visbuf_t;

inline void map::_visibility_scan(const visbuf_t& in,visbuf_t& out,const vec_t& eye,int start_x,int stop_x,int y,int prev_y) {
    const int xdir = (start_x < stop_x)? 1: -1;
    for(int x=start_x; x!=stop_x; x+=xdir) {
        const int x_diff = abs(eye.x-x), y_diff = abs(eye.z-y);
        const bool horiz = (x_diff >= y_diff);
        const int x_step = horiz? 1: x_diff/y_diff;
        const int in_x = x-x_step*xdir; // where in the in buffer would we get the inner value?
        const float outer_d = vec2_t(x,y).distance(vec2_t(eye.x,eye.z));
        const float inner_d = vec2_t(in_x,horiz? y: prev_y).distance(vec2_t(eye.x,eye.z));
        const float inner = (horiz? out: in).at(in_x)*(outer_d/inner_d); // get the inner value, scaling by distance
        const float outer = height_at(x,y)-eye.y; // height we are at right now in the map, eye-relative
        if(inner <= outer) {
            out.at(x) = outer;
            vis.at(y*width+x) = VISIBLE;
        } else {
            out.at(x) = inner;
            vis.at(y*width+x) = NOT_VISIBLE;
        }
    }
}

void map::visibility_add(const vec_t& eye) {
    const float BASE = -10000; // represents a downward vector that would always be visible
    visbuf_t scan_0, scan_out, scan_in;
    scan_0.resize(width);
    vis[eye.z*width+eye.x-1] = vis[eye.z*width+eye.x] = vis[eye.z*width+eye.x+1] = VISIBLE;
    scan_0.at(eye.x) = BASE;
    scan_0.at(eye.x-1) = BASE;
    scan_0.at(eye.x+1) = BASE;
    _visibility_scan(scan_0,scan_0,eye,eye.x+2,width,eye.z,eye.z);
    _visibility_scan(scan_0,scan_0,eye,eye.x-2,-1,eye.z,eye.z);
    scan_out = scan_0;
    for(int y=eye.z+1; y<height; y++) {
        scan_in = scan_out;
        _visibility_scan(scan_in,scan_out,eye,eye.x,-1,y,y-1);
        _visibility_scan(scan_in,scan_out,eye,eye.x,width,y,y-1);
    }
    scan_out = scan_0;
    for(int y=eye.z-1; y>=0; y--) {
        scan_in = scan_out;
        _visibility_scan(scan_in,scan_out,eye,eye.x,-1,y,y+1);
        _visibility_scan(scan_in,scan_out,eye,eye.x,width,y,y+1);
    }
}

```

---
Tags: 2d, grid, line-of-sight
---


title: Remove HUD from Child Scene

text:
# Question
Title: Remove HUD from Child Scene
For my game, I create game scene for which I set HUD to it.

First my game scene use BoundCamera, so I use hud to set score text, dollar text and setting button. Now on game scene when I touch on setting button, the child scene (setting scene) come up because I attached it to game scene.

I use child scene because of pause/resume functionality added to the setting scene.

When child scene display on the screen at the same time hud content also displayed on the sceeen. But I don't want that hud content of my child scene (setting scene).

From other post of this forum I found that made hud.setVisible(false).

But this solution does not work for me because the touch area of hud's children remain active even though it were not displayed on the screen. So when player touch on these areas the effect of touch become available even if the hud is not displayed on the screen.

Also I like to mention that my development platform is AndEngine. I hope someone give me best guidance on this.

# Answer
I don't know why this question was tagged with **cocos2d-iphone**, but here it is the answer for cocos2d-iphone:

In cocos2d you solve this problem by using the Z index ordering. Layers with lower Z index get rendered first.

Check the Cocos2D 2.0 Docs.

```
//kGameLayer
[self addChild:[GameLayer node] z:0 tag:KGameLayer];

//kHudLayer
[self addChild:[HudLayer node] z:1 tag:KHudLayer];

//kTopLayer
[self addChild:[TopLayer node] z:2 tag:KTopLayer];

```

Now in order to show/hide a layer you can use the visible property of a node, check the documentation.

```
@implementation HudLayer

-(void) showLayer: (BOOL) shouldShow
{
  self.visible = shouldShow;
  self.isTouchEnabled = shouldShow;
  menu.isTouchEnabled = shouldShow;
}
@end

```

Now when you display the menu and want to hide the HudLayer, you only have to get the HudLayer by tag, and call shwoLayer with **NO**.

**AndEngine**

In AndEngine you should be able to set the isVisible property of the HudLayer to false, check the source code of BaseEntity

```
public boolean isVisible() {
  return this.mVisible;
}

public void setVisible(final boolean pVisible) {
  this.mVisible = pVisible;
}

```

I assume that the HudLayer in AndEngine is a Layer object, and as I checked the Layer object is a subclass of BaseEntity, hence you should be able to call setVisible on the HudLayer.
> 2 votes

---
Tags: cocos2d-iphone, cocos2d, andengine
---


title: Protecting XNA Assets

text:
# Question
Title: Protecting XNA Assets
With so many XNA asset viewers out there, how do I distribute my XNA game for PC without having my assets open for persons to steal or manipulate? I know i can create custom asset importer/processor, but that's too time consuming right now. So, are there any alternatives to securing my assets?

model viewers:

http://modelviewer.codeplex.com/

http://xnamodelviewer.codeplex.com/

https://github.com/devpro/Xna-Model-Viewer

Edit: found a solution: http://www.xnawiki.com/index.php/Compressed/Encrypted\_Content\_Archive I was looking for something like this all along, but there is still the problem of 3d ripper dx. I guess i'll have to rely on copyright as my protection

# Answer
There is no way to securely protect your assets. You can make it more difficult to get them, but you can't prevent it.

The reason is that in order to use your assets, your game program must be able to read them. And when the game program can read them, any other program can do the same.

You could encrypt your resource files somehow. Even a very weak encryption, like XOR-ing all files with your lucky number, would break any off-the-shelf resource viewer. But in order to read them, your game must include the encryption algorithm and the encryption key. A determined hacker will be able to extract these through reverse engineering and then extract your resources or even release a customized resource viewer for your game, when there is a demand for that. Obfuscation of your code can make this harder, but it can't make it impossible. Any code which is readable for the machine is also readable for a dedicated human.

The best way to prevent others from using your assets is by exercising your rights according to international copyright law.
> 5 votes

# Answer
There is this thing called copyright. It gives you all the protection you need.

If someone wants to steal your assets, they're going to do so whether you waste your time on obfuscating your data or not. If it isn't an XNA asset viewer, it'll be 3d Ripper DX or something like it.

Now, a more interesting question is to ask why you think someone is going to steal your assets, and if they do, how is it going to hurt you?
> 2 votes

---
Tags: xna, xna-4.0, xna-content-pipeline
---


# Question
Title: SimpleOpenNI: Check if user hand is in specific area on image
Concerning our Microsoft Kinect project, we need some help.

We control a robot with our movements tracked by the Kinect sensor. We display the depth image of the Kinect sensor on our screen, so we see what the sensor is acutally tracking.

Now we want to implement a feature that a user can turn the robot on and off by moving the hand on a specific area drawed on this depth image. You can see this in the image below. The problem now is, that the coordinates of this "on-drawed" ellipse obviously are relative in the 3d-space. I know that there must be any possibility to translate the X-, Y- and Z-coordinates of the hand in the 2d-space, but honestly, I have no idea how to do this. I imagine a kind of "tunnel" from the point of view of the sensor, like in the picture below, which the user must hit.

I hope that somebody can help us here.

# Answer
We found a solution by using the DiABlu NXTComm's function

```
convertRealWorldToProjective(PVector world, PVector proj);

```

whichs converts the coordinates like desired. However, even if our problem now is solved, I still wonder how this convertion works in a mathematical way.
> 1 votes

---
Tags: 2d, 3d, coordinates, transformation
---


# Question
Title: why is it faster to draw lots of small arrays than one big array?
This application on-line here has interesting performance characteristics:

Sorting the rectangles to be drawn so it keeps having to change colour is *faster* than sorting the rectangles by their colour and drawing all of each colour at once...

(Timings are printed to Javascript console. Javascript profiling and understanding what is happening between the emitting of draw ops and the actual rendering of frames is, well, guesswork and disappointment. But the result is still surprising (to me).)

***I'm very interested in the fps logged to the javascript console when run in your browser, and how it differs when sorted by colour vs sorted by z***

Now naturally I assume GPU batches are expensive and in my normal apps I get that *impression*, but I cannot distill a simple test case to show this; quite the opposite, in fact!

Deep in my code, it places all the vertex data interleaved into a single big VBO array. It then calls `glDrawArrays` as often as needed. So drawing a rectangle (6 vertices, each 4 floats) in three colours can be:

* Red\*1,Blue\*1,Red\*1 = 3 `glDrawArrays` calls
* Red\*2,Blue\*1 = 2 `glDrawArrays` calls, *but is slower*

I am not sorting, creating, uploading the vertices each frame. I compute the buffers to draw once. Each frame, I simply call `glDrawArrays` as often as needed.

Because I've built this vertex attribute VBO once, and keep reusing it, I have a tight little draw-loop for rendering each frame. So the Javascript code is doing more work when I have lots of little calls, and less work when I'm emitting concatenated rectangles.

So why is it faster to call `glDrawArrays` multiple times with small sub-sequences of the array, instead of calling it only a few times and telling it draw long sequences from the array?

*Related:* there's ***+500 pts*** up for grabs over on StackOverflow for the best general discussion about optimising the drawing of a 2D scene.

# Answer
> 8 votes
As far as I can tell from my working knowledge of OpenGL, the act of sorting all of your rectangles into one big draw call means the CPU is wasting the first half of each update loop carefully and neatly organizing everything while the GPU twiddles its thumbs waiting for the draw call to come in.

Conversely, when when you tell each object to draw individually one after another, the GPU doesn't have to wait around, it's always working at the same time. This way you draw in less than half the time, firstly because the CPU doesn't have to waste time organizing everything into one big draw call every frame, and secondly because the GPU doesn't have to wait for the CPU to completely finish before it can start rendering.

Now this may be a little different in web applications, but most drawing processes generally work the same.

# Answer
> 5 votes
What you describe is not sprite batching. Sprite batching is sorting so that the GPU doesn't have to change **textures** too often (expensive because textures have to be loaded from GPU memory).

Colour data is usually stored in the vertex attributes. If two objects have different colours this doesn't matter, since we always have to read the colour data and 'changing colours' does not trigger loading of any resources.

To give a simpler comparison. If you have to add up five numbers to each other, it won't help first sorting the numbers before you sum them up. The number of instructions stays the same and sorting adds overhead.

# Answer
> 2 votes
Just to elaborate on Stomy's answer - I'd hesitate before describing time spent sorting as "waste"; if the performance gain from being able to batch outweighs the performance loss from sorting, then it's perfectly valid and a reasonable use of CPU time.

There's also a misunderstanding in Stomy's answer whereby the CPU and GPU actually don't operate in a synchronous order as he describes; instead the CPU will submit commands to a driver-managed command buffer and return immediately, which the GPU will then come along and pickup some time later, so they're quite asynchronous.

The trick is to be able to balance your workload between CPU and GPU so that neither ever gets to a situation where it needs to wait on the other before it can continue.

That hints at what's going on here - you seem to be spending a lot of CPU time on sorting and you're not gaining the desired performance from it. I don't know what you're using for your sorting, but one would expect that with JavaScript being a generally slower language, it may not be the most optimal for any kind of more CPU-intensive work such as this; your sort algorithm may also need looking at (e.g. you may be using bubble sort).

---
Tags: optimization, webgl
---


title: Dynamic Sprite Scaling in SDL?

text:
# Question
Title: Dynamic Sprite Scaling in SDL?
I was wondering if I could get a player sprite effect similar to the one in this video using SDL (without openGL). If not, does anyone know how I might achieve that effect using SDL/OpenGL?

# Answer
Without OpenGL, you have to do scaling/rotation/etc yourself. Here is one person's implementation: http://www.ferzkopp.net/joomla/content/view/19/14/ . You could however also manually animate it like that
> 1 votes

# Answer
SDL\_gfx is a library which can do the SDL surface scaling and rotation for you. Its documentation is in the section marked "Rotozoomer".
> 1 votes

# Answer
From what I could see from the video, there are several "effects" in play:

* scaling (by distance)
* bouncing (possibly with nonuniform scale) animated procedurally
* white flashes (on hit)

There's nothing that stops you from doing any of the above in SDL. While SDL has some functions for blitting scaled versions, it's probably better to roll your own for your specific needs. This is relatively easy to do.

As for the white flashes, I'd just keep a second copy of the textures that are white.
> 0 votes

---
Tags: opengl, sprites, sdl
---


title: Large FPS vs consistent FPS

text:
# Question
Title: Large FPS vs consistent FPS
When optimizing the frame rate of a game, when should I focus on a large FPS and when should I focus on a consistent frame rate.

This is often a hotly contested issue, so please note I'm **not** asking which is better.

What are the pros and cons of each?
In which situations is one preferred over the other?

Also note: my input polling/processing, physics, and game update rates are independent of my frame rate. The only thing the FPS affects is how often a screen is rendered.

# Answer
> 10 votes
This is subjective, of course, but I think that consistency is much more important to game play than speed.

Basically, players will put up with a slower frame-rate if the game is consistent, fun to play and not jarring. However, even if the game totally rocks, if it gives people headaches to look at because it bursts, and/or they can't control things, they will become annoyed & stop playing.

So...

Focus on consistent FPS throughout design & development.

Focus on faster (but still consistent) FPS when the game is nearly done, and you have time to improve performance without worrying about bug fixes, etc.

One way to get better performance is to use callbacks/delegates/interrupts (depending on your language/platform) rather than polling.

# Answer
> 13 votes
What you should do:

* Lock game *logic* to a fixed framerate
* Render graphics as fast as possible

That way, if the framerate drops you don't get input lag (I'm looking at you, Just Cause 2), and if the framerate becomes too high (think games from the 90's) the game doesn't become unplayable.

Here's how I do it:

```
s_PhysicsCurrent = GetTickCount();
float delta = (float)(s_PhysicsCurrent - s_PhysicsStart);
s_PhysicsStart = s_PhysicsCurrent;

s_PhysicsTime += delta;

while (s_PhysicsTime > ONEFRAME)
{
    // Update
    Game::Tick(ONEFRAME);

    // Clear input
    Keyboard::Clear();
    Mouse::Clear();

    s_PhysicsTime -= ONEFRAME;
}

s_Window->Clear();

Game::Render();

s_Window->Swap();

```

You basically collect a "stack" of frames to do logic for and you can interpolate between them perfectly.

# Answer
> 2 votes
It sounds like you've got at least two threads of execution, with your rendering on its own thread. If that's the case, then you actually have two frame rates to worry about. You'll want both to be as fast as possible. However, it also depends on the kind of game you're building.

Are you building a first-person shooter, where small drops in frame rate could give an opponent an advantage? If so, then you'll want to make sure your average fps is high enough, but also worry about your worst-case frame times. Are you building a board game? If so, the occasional frame time spike isn't going to kill the user experience.

In my own games, my process is usually something like this:

* Run a profiler on the code
* Look at the average frame rate. If it's too low on average, bring the averate fps up by optimizing the slow stuff.
* Once average fps is high enough, look for worst-case frame times (frames where you see big spikes in computational or rendering time). Try to optimize those worst-case scenarios to improve worst-case frame time.

If you're at 30 fps most of the time, but you spike to 200ms every 10 seconds, that's going to cause problems. But if you're averaging 15 fps, bring your average fps up first.

So, the short answer would probably be: optimize whatever makes the biggest improvement to the user experience first.

# Answer
> 2 votes
Locking your FPS to a consistent number allows you to:

* Maintain a smooth visual appearance
* Keep animations running in linear time, physics objects falling at a consistent rate between frames, etc.
* However, the most useful part of locking your FPS is that on frames where you have some down time you can do other work--collect garbage, work on streaming in the next area of the map, etc and you will have some headroom when rendering something big and shiny or when knocking down a pile of boxes.

# Answer
> 1 votes
Both. I'd say ideally, consistently over 60 frames per second. Realistically, consistently over 30 frames per second. Under 30 frames per second and it starts affecting how well the player can perform (I'm thinking of FPS/twitch-based games by the way, strategy games can probably get by on lower).

If you really had to say one or the other, I'd go with consistency. If you can guarantee a frame rate, then you can focus on moving that guaranteed framerate higher.

# Answer
> 1 votes
Larger is always better, but:

Inconsistent framerate can lead to motion sickness.

(We had an internal tester throw up when his framerate jumped between 20 and 60 for 10 seconds.)

# Answer
> 0 votes
I would think you would want both a consistent and larger FPS. The smoother the graphics (due to refresh rate), the better. If it starts dropping below 30FPS your users are going to start to notice the jitteriness and will become frustrated with lack of response time to actions.

# Answer
> 0 votes
If you want to prevent tearing, you should use V-sync which will lock the FPS to the refresh rate of the monitor, or lower (if you go higher it won't be visible, so it'd be a waste).

# Answer
> -4 votes
There's only one answer, and that is.. always go for high during development and when your down bring it down to the lowest spike, this will bring the game into a sick steady flow. I'm sitting on the code, and it will stay there because it's my secret way of the coding dragon. /Eyhe

---
Tags: optimization, frame-rate
---


# Question
Title: Sync clocks on a real time multiplayer game - Is this ok?
I'm developing a multiplayer game through Gamecenter in unity with prime31 plugin. This is how I sync the clocks of the two players (right now there will only be 2 player in one match), and I wanted to now if it's ok:

This is done one time at the start of the match.

* I have device A and device B.
* Device A resets it's game clock to 0.0f.
* A sends a reliable message to B saying that A has reset it's game clock.
* B recieves the message and resets his game clock as well and sends a message to A saying he has also reseted the clock.
* A recieves the message and does the following.

> ```
> float delayAtoB = getCurrentTime() / 2;
> setGameClock(delayAtoB);
>
> ```

delayAtoB is actually this the time it took to get to B, so right now the two devices have the same clock. It works ok, but I wanted some opinions because I'm not sure if it's the best way and some exceptions might ocur..

# Answer
> 4 votes
What you've described is correct and commonplace. Ping times can vary widely though, so to get a more accurate result you can repeat the process a few times and take the average ping time as described on wikipedia.

# Answer
> 1 votes
You actually want unreliable messages not reliable ones. The reason is that if a retransmission occurs then your timings can be significantly out. Just repeat the unreliable process until it works.

There's a standard protocol for doing this called NTP which may be of some interest, although it may be overkill for a game.

---
Tags: ios, multiplayer, synchronization, game-center
---


# Question
Title: How slow is generating a new Vertex Buffer?
I am currently working on a project that does 2D sprite-like graphics on Windows 8 (Metro-style app). For that purpose I am using Direct3D with quads to act as sprites.

My problem is that it get's very slow (30fps at 100 sprites) and profiling led me to believe that the bottleneck is withing the CreateBuffer call. How can I solve that problem in an elegant way? Wouldn't gathering copying vertex data from all elements that share the same texture in a single, bigger, buffer be more cost-prohibitive, as it is all done on the CPU?

# Answer
You shouldn't be creating a new buffer each frame. Memory allocation/deallocation operations are often quite slow, especially when it involves video memory as a CPU/GPU sync point may be introduced.

A better way to work with vertex buffers is to reuse a single vertex buffer, mapping it with the DISCARD and NOOVERWITE flags, as appropriate, to let the driver know what you're doing. This is a topic big enough for an article in itself, but this MSDN page has the basics. If you search for "dynamic vertex buffer" on the web you'll find more articles about this. BTW, this works essentially the same way in all versions of Direct3D, though the API calls and flags are a little different in D3D10-11 vs D3D9.

And, just to be clear, you should definitely group together all the sprites that have the same texture and draw them at once. Texture/shader changes have a nontrivial performance cost, so it's best to minimize the number of such changes.
> 3 votes

---
Tags: directx, windows-8
---


# Question
Title: As an indie game dev, what processes are the best for soliciting feedback on my design/spec/idea?
**Background**

I have worked in a professional environment where the process usually goes like the following:

1. Brain storm idea
2. Solidify the game mechanics / design
3. **Iterate on design/idea to create a more solid experience**
4. Spec out the details of the design/idea
5. Build it

Step `3.` is generally done with the stakeholders of the game (developers, designers, investors, publishers, etc) to reach an 'agreement' which meets the goals of all involved. Due to this process involving a series of often opposing and unique view points, creative solutions can surface through discussion / iteration. **This is backed up by a process for collating the changes / new ideas, as well as structured time for discussion.**

As a (now) indie developer, I have to play the role of all the stakeholders (developers, designers, investors, publishers, etc), and often find myself too close to the idea / design to do more than minor changes, which I feel to be local maxima when it comes to the best result (I'm looking for the global maxima, of course).

I have read that ideas / game designs / unique mechanics are merely multipliers of execution, and that keeping them secret is just silly. In sharing the idea with others outside the realm of my own thinking, I hope to replicate the influence other stakeholders have.

I am struggling with the collation of changes / new ideas, and any kind of structured method of receiving feedback.

**My question**: As an indie game developer, how and where can I share my ideas/designs to receive meaningful / constructive feedback? How can I successfully collate the feedback into a new iteration of the design? Are there any specialized websites, etc?

# Answer
There is a very well-established feedback loop on the TIGSource Forums, particularly in their Creative-\>Feedback sections. You can also document and display works in progress, update their completion status, and isolate individual components of your game for specialized feedback (Art, Music, Animation, Models, Code, etc).

Reddit Gamedev is another great resource for honest feedback. The community is large and diverse, so you can expect to get a number of alternative and possibly unexpected insights into how well your game is being received.

The forums over at IndieDB are another great place to communicate progress, chat with other developers of all levels of expertise and garner feedback.
> 5 votes

# Answer
I always like /r/gamedev over at reddit - If you go over there, you'll find plenty of people posting new ideas /designs for feedback, progress on their current projects, and weekly 'Screenshot Saturday' posts to show off your games (as well as get new ideas yourself!)
> 4 votes

# Answer
It's java-related but there is a section named "Game Play & Game Design", i think this is what you are looking for: JavaGaming.
> 0 votes

---
Tags: game-design, game-mechanics
---


# Question
Title: How to draw a smooth circle in Android using OpenGL?
I am learning about OpenGL API on Android. I just drew a circle. Below is the code I used.

```
public class MyGLBall {

private int points=360;
private float vertices[]={0.0f,0.0f,0.0f};
private FloatBuffer vertBuff;

//centre of circle

public MyGLBall(){

    vertices=new float[(points+1)*3];
    for(int i=3;i<(points+1)*3;i+=3){
      double rad=(i*360/points*3)*(3.14/180);
      vertices[i]=(float)Math.cos(rad);
      vertices[i+1]=(float) Math.sin(rad);
      vertices[i+2]=0;
    }
      ByteBuffer bBuff=ByteBuffer.allocateDirect(vertices.length*4);
      bBuff.order(ByteOrder.nativeOrder());
      vertBuff=bBuff.asFloatBuffer();
      vertBuff.put(vertices);
      vertBuff.position(0);

}

public void draw(GL10 gl){
    gl.glPushMatrix();
    gl.glTranslatef(0, 0, 0);
//  gl.glScalef(size, size, 1.0f);
    gl.glColor4f(1.0f,1.0f,1.0f, 1.0f);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertBuff);
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glPopMatrix();
 }

 }

```

It is actually taken directly from here The circle looks pretty good. But now I want to make the boundary of the circle smooth. What changes do I need to make to the code? Or do I need to use some other technique for drawing the circle?

Thanks.

# Answer
> 8 votes
With polygon-based graphics, the only option you have to better approximate a circle is to subdivide further. 720 triangles will result in a smoother circle, but 1440 will give you an even smoother circle, but 2880...

A perfect circle, created using polygons, would require an infinite amount of infinitesimally small polygon sections (in other words, it just isn't possible, in theory). Practically, however, if you subdivide enough times, you may reach a point where the length of the polygon section is equal to or smaller in size than a pixel, meaning that, for purposes of your framebuffer, you have achieved a "perfect" circle.

The other option, of course, is to cheat: render a flat quadrilateral oriented perpendicular to the camera, and texture it with an image of a sphere. 2 triangles, 1 texture of sufficient resolution: smooth circle, and a hell of a lot less vertices for your GPU to worry about.

# Answer
> 5 votes
If you want to do vector graphics with OpenGL, you should do taht in shaders. E.g.

```
gl_FragColor = ( length(gl_FragCoord.xy) < 0.5 ) ? vec4(1,1,1,1) : vec4(0,0,0,1);

```

You can do some "supersampling" to make it smooth, or analytically compute the area of pixel, which is overlapped by circle.

BTW. there is also OpenVG API out there.

---
Tags: opengl, android, antialiasing
---


title: Stopping on a slope in Box2d

text:
# Question
Title: Stopping on a slope in Box2d
I am creating a simple platformer using Box2d. I've implemented a variant of the technique described here.

To make the player character move more 'platformer-like' I want him to stop on (shallow) slopes.

However, the engine I am using does not support angle-joints, so I have trouble restricting the movement of the wheel. I've tried some different alternatives that not worked: Setting the horizontal velocity to 0 every game loop doesn't seem to work, because between calls the wheel catches up speed once again.

Is there another way to fix this?

# Answer
> 7 votes
One possible solution is as follow:

* **Fix the rotation angle for the box**

Box2D doesn't have angle joints, but setting the body definition with the property `fixedRotation = true` allows it to maintain a constant angle of rotation like the angle joint.
* **High maximum torque for the motor's joint**

The maximum torque for the motor in the revolute joint needs to be relatively high, so that the joint can accelerate or be able to stand the two bodies on the slope. To stop on the slope set the motor speed to zero.
* **High friction coefficient for the circle**

Also a high friction coefficient for the circle allows it to maintain a good grip on the ground, so that it can start to move without drifting.

To test the suggested technique create a new project, then choose the **iOS \> cocos2d \> cocos2d\_box2d** template.

After creating the project go to **HelloWorldLayer.mm** and change the `init` method like this

```
-(id) init
{
    //...

    // bottom
    groundBox.SetAsEdge(b2Vec2(0,0), b2Vec2(screenSize.width/PTM_RATIO,0));
    groundBody->CreateFixture(&groundBox,0);

    //...
}

```

changes to

```
-(id) init
{
    //...

    // bottom
    groundBox.SetAsEdge(b2Vec2(0,0), b2Vec2(.5f*screenSize.width/PTM_RATIO,.25f*screenSize.height/PTM_RATIO));
    groundBody->CreateFixture(&groundBox,0); groundBox.SetAsEdge(b2Vec2(.5f*screenSize.width/PTM_RATIO,.25f*screenSize.height/PTM_RATIO), b2Vec2(screenSize.width/PTM_RATIO,0));
    groundBody->CreateFixture(&groundBox,0);

    //...
}

```

look for `addNewSpriteWithCoords` method and replace all its content

```
-(void) addNewSpriteWithCoords:(CGPoint)p
{
    //...
}

```

changes to

```
-(void) addNewSpriteWithCoords:(CGPoint)p
{
    CCSpriteBatchNode *batch = (CCSpriteBatchNode*) [self getChildByTag:kTagBatchNode];

    //We have a 64x64 sprite sheet with 4 different 32x32 images.  The following code is
    //just randomly picking one of the images
    CCSprite *circleSprite = [CCSprite spriteWithBatchNode:batch rect:CGRectMake((rand()%4)*32,32,32,32)];
    [batch addChild:circleSprite];

    circleSprite.position = ccp( p.x, p.y);

    // Define the dynamic body.
    //Set up a 1m squared box in the physics world
    b2BodyDef circleBodyDef;
    circleBodyDef.type = b2_dynamicBody;
    //bodyDef.fixedRotation = true;

    circleBodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
    circleBodyDef.userData = circleSprite;
    b2Body *circleBody = world->CreateBody(&circleBodyDef);

    // Define another box shape for our dynamic body.
    b2CircleShape dynamicCircle ;
    dynamicCircle.m_radius = .5f;//These are mid points for our 1m box

    // Define the dynamic body fixture.
    b2FixtureDef circleFixtureDef;
    circleFixtureDef.shape = &dynamicCircle;
    circleFixtureDef.density = 1.0f;
    circleFixtureDef.friction = 4.0f;
    circleBody->CreateFixture(&circleFixtureDef);

    //We have a 64x64 sprite sheet with 4 different 32x32 images.  The following code is
    //just randomly picking one of the images
    CCSprite *boxSprite = [CCSprite spriteWithBatchNode:batch rect:CGRectMake((rand()%4)*32,0,32,32)];
    [batch addChild:boxSprite];

    boxSprite.position = ccp( p.x, p.y);

    // Define the dynamic body.
    //Set up a 1m squared box in the physics world
    b2BodyDef boxBodyDef;
    boxBodyDef.type = b2_dynamicBody;
    boxBodyDef.fixedRotation = true;

    boxBodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
    boxBodyDef.userData = boxSprite;
    b2Body *boxBody = world->CreateBody(&boxBodyDef);

    // Define another box shape for our dynamic body.
    b2PolygonShape dynamicBox;
    dynamicBox.SetAsBox(.5f, .5f);//These are mid points for our 1m box

    // Define the dynamic body fixture.
    b2FixtureDef boxFixtureDef;
    boxFixtureDef.shape = &dynamicBox;
    boxFixtureDef.density = 1.0f;
    boxFixtureDef.friction = 0.3f;
    boxBody->CreateFixture(&boxFixtureDef);

    b2RevoluteJointDef revoluteJointDef;
    revoluteJointDef.bodyA = boxBody;
    revoluteJointDef.localAnchorA = b2Vec2(0, -.5);
    revoluteJointDef.bodyB = circleBody;
    revoluteJointDef.collideConnected = false;
    revoluteJointDef.enableMotor = true;
    revoluteJointDef.maxMotorTorque = 200;
    revoluteJointDef.motorSpeed = CC_DEGREES_TO_RADIANS(0);

    world->CreateJoint(&revoluteJointDef);
}

```

in the tick method add this code just after `world->step(…)`

```
-(void) tick: (ccTime) dt
{
    //...

    world->Step(dt, velocityIterations, positionIterations);

    for (b2Joint* j = world->GetJointList(); j; j = j->GetNext())
    {
        int randomNumber = rand()%40; // choose a random number, ranged between 0 and 39
        bool changeMovement = randomNumber == 0;  // change movement only when random number is 0, it could be any other arbitrary number

        if (changeMovement)
        {
            b2RevoluteJoint* rj = (b2RevoluteJoint*) j;

            rj->GetBodyB()->SetLinearVelocity(b2Vec2(0,0));

            int randomNumber = rand()%3; // take the number 0, 1, or 2 at random

            randomNumber = randomNumber-1; // convert the random number to either -1, 0 or +1

            float angularSpeedInDegrees = randomNumber*2.f*360.f // multiply the random number by a given angular speed, in this case two revolutions per second

            rj->SetMotorSpeed(CC_DEGREES_TO_RADIANS(angularSpeed));
        }
    }

    //...
}

```

replace the file **blocks.png** for this file

this is the screen capture

http://youtu.be/10WO9tp5p0M

---
Tags: box2d, movement, platformer
---


# Question
Title: How to get the height at a position in a triangle
I have a heightmap, and I store the heights in a giant array. However, when I move, it's quite choppy on the Y-axis, so I need a way to get the height at a certain point in a triangle.

I currently am picking a triangle based on the player's position, but I'm stuck on finding the intermediate height at the point. At the moment, I'm using similar triangles on each axis to calculate the height, but this method seems slow, and someone mentioned using a weighted average to find the height, which would probably be faster.

I know that DirectX has a "D3DXIntersectTri" function, but I couldn't find one in XNA.

Basically, I just want to know how the height is interpolated with a weighted average.\

Thanks!

# Answer
> 2 votes
I believe you can use bilinear interpolation on the heightmap data. (I suppose, you have your heightmap as 2D raster of heights)

1. Get floating point position fX, fY in your height map. This is something like:

> ```
> float fX, fY;
> float fHeightMapWorldSizeX, fHeightMapWorldSizeY;
> float fHeightMapWorldOffsetX, fHeightMapWorldOffsetY;
> int   iDimHeightMapX, iDimHeightMapY;
> float fPlayerX, fPlayerY;
>
> fX = (fPlayerX + fHeightMapWorldOffsetX) / fHeightMapWorldSizeX * iDimHeightMapX;
> fY = (fPlayerY + fHeightMapWorldOffsetY) / fHeightMapWorldSizeY * iDimHeightMapY;
>
> ```
2. Bilinear interpolation

> ```
> float fTX, fTY;
> float fSampleH1, fSampleH2, fSampleH3, fSampleH4;
> int x,y;
> float fFinalHeight;
> x = floor(fX);
> y = floor(fY);
> fTX = fX - x;
> fTY = fY - y;
> fSampleH1 = arrHeightMap2D[x][y];
> fSampleH2 = arrHeightMap2D[x+1][y];
> fSampleH3 = arrHeightMap2D[x][y+1];
> fSampleH4 = arrHeightMap2D[x+1][y+1];
> fFinalHeight = (fSampleH1 * (1.0-fTX) + fSampleH2 * fTX)*(1.0-fTY) + (fSampleH3 * (1.0-fTX) + fSampleH4 * fTX)*(fTY);
>
> ```

Easy, isn't it ?

# Answer
> 1 votes
One approach is to use a generic ray-triangle intersection algorithm.

If you have a ray from `[player.x,MAX_Y,player.z]` straight down (direction `[0,MAX_Y-MIN_Y,0]`) and fire this at both triangles that form the grid-square, you'll find the y at the player's position.

---
Tags: xna, collision-detection, movement, heightmap
---


# Question
Title: What is an elegant way to localize level data?
I'm writing a simple android game. I planned to store all levels in xml files that contain info about level, including a `level_name` field. The `Level` class would load an appropriate level by parsing the corresponding XML file and reading data into the Level's fields) when user selects it.

Everything seems fine, until I want the game to support multiple languages. With UI it is clear how to solve this problem since we have `strings.xml` file. But what about localizing level data stored in `XML` files?

I considered having multiple fields for a given piece of data in a `level.xml` file, with each containing a different translation. Another thought was storing only the ID of level and get related level name from strings.xml file.

However, neither of these seem very elegant. Is there a more better way of doing this?

# Answer
> 9 votes
When you put all languages in one file, no two translators can work with the same map at the same time, because there will be edit conflicts. You also have to train your translators how to edit your level files. XML might seem intuitive to a programmer, but to a non-technical person it isn't.

But when you use a string file for each language, all translators can work independent from each other. It will also be easier for you to check the completeness of each translation, because you only have to look into one file.

# Answer
> 6 votes
My preferred elegant solution is this:

The English text in any file (or whatever your base language might be) must be passed through a translation function before display.

The gist is that your string table(s) consist of the English version of the string followed by the localised version(s) of the string, and your translation function takes the english version of the string as a parameter, and returns the localised string to be drawn to the screen.

* If the translation function finds a translated version of the requested string, it returns the translated version, and everything works normally.
* If the translation function **doesn't** find a translated version of the requested string (and this is the elegant part of this system), it returns `$$string$$`. That is, it returns the requested string, surrounded by `$$` on each side.

Calling the function might look something like this:

```
string translatedString = XLAT( rawString );

```

Ideally, I advise putting this code into your string drawing code, immediately before rendering, so that you can be certain that every string which makes it to the screen has been through the translation function exactly once.

Here are the benefits of this system:

1. Your English-language developers can still easily read and use the non-translated strings during development, by simply ignoring the `$$` characters. **Additionally, all your level files do not require any special localisation: any strings placed in them which wind up being rendered to screen will automatically be translated through this system.**
2. Any non-translated strings are very obvious, due to the `$$` characters surrounding them. It's easy to not notice untranslated strings if you don't do something like this.
3. If a string is changed at all in your code or data, it *automatically* becomes an untranslated string again, even if it had already been translated. This means that it starts showing up as untranslated again when you run your program, and you don't wind up with old, no-longer-accurate translations peppering your game the way that you can in integer-keyed string tables where none of your programmers or testers actually speak the translated language.

Downside of this system:

* By keying translated strings by the non-translated string, you can sometimes wind up with English strings that appear in more than one context, but need different translations in those different contexts ("OK" is a frequent culprit for this). In these cases, you wind up having to instead use unique "English" strings for the different situations, and translate that into proper English in the English translations.

(unrelated side note: A frequent novice mistake in localisation is to treat US English and UK English as the same language. Don't do that!)

---
Tags: android, xml, localization
---


# Question
Title: FPS games: don't they have unrealistic one-eyed view? What are the causes?
I have played many fps games, and noticed that the camera perspective is similar to the 'one eyed view' of the surroundings. It does not feel like bilinear. :/

Is it because of the single flat view of the screen? Or is it the problem that can be fixed by some research?

PS: If you want, try to roam around with only one eye open.

# Answer
I'll state the obvious - FPS games are doing the best they can within the limitations of a single 2D display device.

The interesting part - this might change soon thanks to the Oculus Rift project \- a VR headset for games. I've seen info that DOOM 3 is fully supported (due to Carmack's involvement) and that Hawken has promised support. There is also work on external engine integration (Unity and Unreal were mentioned here).

Note the games on Oculus must support full stereoscopic 3D, since the headset has a separate display for each eye.
> 7 votes

# Answer
It's hard to tell exactly what's being asked here but I'll try to give the best answer I can. There are a few misconceptions going around in comments and answers so I'll try to clarify all this, to the best of my knowledge.

> \[I\] noticed that the camera perspective is similar to the 'one eyed view' of the surroundings.

Indeed, the default (horizontal) field of view of first-person shooters (e.g. 75° in HL2) is notably smaller than the 'natural' FOV (around 95°). It might be close to a single eye FOV, but to me this is more or less a coincidence.

> Is it because of the single flat view of the screen?

**Not really**.

This is simply a side effect of the display size. The FOV is reduced to *compensate* the fact that a regular screen doesn't cover your entire vision (you can see your environment around the screen, unless you stick your nose on the flat panel). Note than some gamers like to change this default FOV to something bigger for a better view of their virtual surroundings. So there is no single magic value used in FPS games: this is a matter of preferences and habits.

Stereoscopic 3D displays are quite common nowadays, and plenty of games support them, thus offering a proper 'two eyed view'. The default FOV is *not* changed in those cases: the fact that both of your eyes receive a different image doesn't change the relative size of the display compared to your vision.

> Or is it the problem that can be fixed by some research?

**I wouldn't call this a *problem***.

The 'fix' already exists, lots of game allow you to change the FOV on-the-fly, for instance try typing this in HL2's console:

```
sv_cheats 1;fov 95

```

This will seem to distort the perspective on a regular screen. To keep a natural-looking perspective with a high FOV, you simply have to use a display that covers your entire vision (stereoscopic or not). There are plenty of solutions:

* Add more screens, for instance through AMD EyeFinity. Games supporting this technology will enlarge the FOV to fit the new display size.
* Use a VR headset (expensive), or wait for the the much hyped Occulus Rift (or even customize an old Virtual Boy if you want to go retro).
* Another fancy upcoming technology that could benefit from larger FOVs is Microsoft's IllumiRoom \- or, why not, a plain old overhead projector.
* Heck, if you've got plenty of money or a VR research department in your neighborhood, you could even go for a full-fledged CAVE.
> 5 votes

# Answer
IMO the main reason for the usually limited field of view is preventing things like motion sickness and keeping aspect ratios sane (i.e. not looking awkward).

Most players will most likely sit around 30-50 cm in front of their screen, probably a bit more for console games. If you consider the screen to be a "window" you're looking through and its size, you'd be able to have a field of view of around 60-90 °, which is the usual setting used in these games as well.

Due to this you get a "realistic" view even while moving. If this doesn't really fit, the player might encounter things like motion sickness, or he'd just see the scene as through a fisheye (which usually isn't desired either).
> 1 votes

# Answer
Most games allow you to adjust the field of view to your liking within reason, and many seems to set it rather narrow as default - likely because it will perform better and I'd guess cause less issues with nausea that way?

It's not like you can actually recreate the feeling of roaming around with two eyes on a flat display without additional tools like shutter glasses and wider, closer placed displays or HMDs.
> 0 votes

# Answer
As Liosan said, only in the future we will change that (Oculus Rift is also coming to the steam box). But i think is a even more distant future. Oculos Rift just puts your head as the control of the camera (i think), so it will still be a flat image.
> -1 votes

---
Tags: camera, first-person-shooter
---


# Question
Title: Entity Component System: Retrieving components quickly
> **Possible Duplicate:**
> Retrieving components from game objects (entities)

I'm working on an entity-component-system game at the moment. I've looked in particular at the Artemis framework and a c# port of it but I am writing my own implementation of the pattern.
http://gamadu.com/artemis/manual.html

I'm puzzled as to how components are retrieved from the EntityManager. As far as I can tell I have two options:

* Assign each type of component a static ID, that is used as the index of the component (my entities are held as EntityComponent\[entityID\]\[componentIndex\]) but I'm concerned that in a situation where an entity has a component of ID 9, that I will then have size the array to 10 and have 9 empty elements preceding the sole component, consuming memory unnecessarily.
* Alternatively I could write a generic method e.g EntityManager.GetComponent(int entityID) but this would require a look up or OfType\<\> call against the entities components.

Surely there is a more efficient way. What am I missing? Artemis includes a ComponentMapper class but I struggle to understand what it does. I want to ensure the basics of the system work as efficiently as possible. Many thanks in advance for any feedback.

# Answer
> 1 votes
> Assign each type of component a static ID, that is used as the index of the component (my entities are held as EntityComponent\[entityID\]\[componentIndex\]) but I'm concerned that in a situation where an entity has a component of ID 9, that I will then have size the array to 10 and have 9 empty elements preceding the sole component, consuming memory unnecessarily.

As long you are reusing your Entities and their static ID (something Artemis does). I don't see the problem with this. Chances are you are going to fill in the spots anyway, with the entities that are in an object-pool or something similar. And in the case where you reuse your Entity the memory is already allocated for you. From Artemis point of view Components are very small objects( they can be big, but I doubt that will happen ). I Really don't think you're loosing too much memory.

# Answer
> 3 votes
In a very reduced implementation example, this is what I do in my GameObject / Entity class:

```
private Dictionary<Type,Component> compMap;

public T GetComponent<T>() where T : Component
{
    Component result;
    this.compMap.TryGetValue(typeof(T), out result);
    return result as T;
}

```

Basically the lookup you try to avoid - but as far as my experience goes, this has always been "fast enough". I have a specific optimization for Transform Components, though, because they're accessed very often. I hold a special private field for them and allow access via predefined property.

```
private Transform transform;

public Transform Transform { get { return this.transform; } }

```

When adding or removing Components, I check if its the Transform Component and update the internal field. It's kind of a hack, but since almost every GameObject / Entity has a Transform Component, it speeds up things a bit.

I'm not sure whether we're using the same Component System approach, but a lookup actually isn't *that* bad - you just have to use them wisely. A Component that needs a reference to another one might look it up once and store the reference until its disposed or no longer attached to the GameObject / Entity. Even if you do a once-per-frame lookup for a lot of Components, other things are more likely to affect your performance: Rendering, streaming audio, complex AI, etc. usually consume more CPU power.

---
Tags: xna, c#, component-based, entity-system
---


# Question
Title: Slick2D Isometric TiledMap Rendering Problem
I created a Tiled Map using the Tiled Map Editor. In the Editor it looks like this:

Desired State

In my java program it looks like this:

Actual State

My java code is:

```
public class Game extends BasicGame {

    private TiledMap map;

    public static void main(String[] args) throws SlickException {
        AppGameContainer app = new AppGameContainer(new Game());

        app.setDisplayMode(800, 600, false);
        app.setShowFPS(true);
        app.start();
    }

    public Game() {
        super("Test");
    }

    @Override
    public void render(GameContainer arg0, Graphics arg1) throws SlickException {
        map.render(300, 200);
    }

    @Override
    public void init(GameContainer arg0) throws SlickException {
        map = new TiledMap("res/unbenannt.tmx"); //path is valid!
    }

    @Override
    public void update(GameContainer gc, int arg1) throws SlickException {

    }
}

```

The orientation of the map is isometric. I'm working under Linux Mint, Java 6, eclipse with the latest Slick2D and LWJGL Library.

Did I forget anything? Why am I getting such a weird looking map rendering?

# Answer
It seems the current Slick2D release (2.8.5 on 18th of January 2013) doesn't render isometric maps correctly. In previous versions of Slick an Exception was thrown:

> Only orthogonal maps supported, found: isometric

In the current version there is no such Exception. So I compiled the current development version here (change from `default` to `development` first) and now it works as desired.

## How did I compile it?

I installed `Mercurial` and got the development version by executing `hg clone https://bitbucket.org/kevglass/slick`. In the `Slick` folder there is a `build.xml` file for `ant`. I executed `ant build-slick` to build the project. The resulting jar files are located in the `lib` folder. You will have to replace your old Slick files with these. Also you will have to replace the old natives with the new ones.

Linux Hint: I also had to unpack the `natives-linux.jar` manually and replace the old files (\*.so) with the unpacked ones.

To save your time I will provide a whole development-build here.
> 3 votes

# Answer
I've never worked with Slick2D and LWJGL, but here's a wild guess just from the looks of the image: Each tile seems to be drawn with some kind of "Solid" or no Blending at all. That is, each tile, which is drawn as a rectangular area, overwrites all the pixels behind it with "black", which might be the tile textures "background color" becoming visible due to a rendering state that ignores their alpha values.

* Did you happen to manually set OpenGL blend states or similar and forgot to set them back? Something along the lines of glBlendFunc maybe?
* Is there anything else you could have done to screw up some internal rendering state?
* Does a .tmx file contain a reference to the Tileset Image that is used and is there any kind of configuration you might want to check?
* Does the Tileset Image require to be in a specific format in order to be interpreted correctly regarding each tile rectangles alpha values?
* Is there some kind of "transparency color key" you need to set that will mark a specific color (such as "black") as transparent?
> 0 votes

---
Tags: java, tiles, lwjgl, slick
---


# Question
Title: How to stack units in a tile based game?
I'm trying to make it so that no more than 5 units can be stacked on a tile. I have a Tile class that creates each tile's preferences. Should I store the units in an array or arraylist in this class?

# Answer
Choosing a data structure will depend on what other features you want to support. In this case, you may as well use the ArrayList since it's easier to work with and more flexible.

It would be best to just store a reference to the unit in the tile, and have the unit objects stored elsewhere.
> 6 votes

# Answer
Based on the nature of your question a Stack http://docs.oracle.com/javase/6/docs/api/java/util/Stack.html be optimal, however it is last in first out so I don't know if that would fit your requirements, otherwise you could also use a queue. If order doesn't matter to you then use ArrayList, it is generally the most efficient (good comparison to linkedlist here http://www.java-gaming.org/topics/arraylist-vs-linkedlist/27017/view.html)
> 0 votes

---
Tags: java, tiles
---


title: UDK Fixed AIController / Pawn Height

text:
# Question
Title: UDK Fixed AIController / Pawn Height
*\[I already asked this question on the UDK forums, without much success though.\]*

I'm using a class derived from `AIController` to control my pawn in RTS-style. My problem is that the pawn does not have a fixed `Location.Z` so if his `Velocity` in X and Y direction changes the `Velocity.Z` also changes (for whatever reason). I have tried nulling the `Velocity.Z` in the tick method, using `Move` to move the character back to a constant height and some other things of which nothing had worked. How can I solve this?

# Answer
> 1 votes
The problem seemed to be that I was using the a Terrain as ground even though it was flat and the height was not modified. I'm using a blocking volume now and it works just fine.

---
Tags: software-engineering, udk, rts, unreal
---


# Question
Title: Approaches for storing grid-like information
I am drawing this simple grid on my NodeJS server:

```
var grid = [];

for(var x = 0; x < 20; x++){
    grid[x] = [];
    for(var y = 0; y < 20; y++){
    grid[x][y] = 0;

    }
}

console.log(grid);

```

The outcome looks like this:

I know, pretty right?!

0 is supposed to indicate FREE, thus if a player requests to move to a field with 0, he will!

The problems come when I want to add more then just Free/Occupied, for instance I would like to give each Array Element an ID number for the Client Updates, or certain features on the field to be stored.

I tried to assign `{ something: N, something2: N}`

But thought it looked rather performance expensive in the long run. (On a big Grid)

*I read about using a single Object for several elements, but I cannot find this any more..*

Should I perhaps use an Array of Objects, or an Additional Array inside each X,Y element?

Any performance / convenience / anything goes tips are welcome :D

**Edit: Thank you for the ideas so far, I was now thinking to perhaps using Strings. Storing Variable\_A + "," + Variable\_B and then later using the .split to use the information. Any thoughts on this?**

# Answer
> 3 votes
You seem to match this frequent use case :

* a big map with each cell having a few characteristics
* some objects being somewhere in the map

I suppose the map is big because you ask about performances. If the map is small, then both the question and my answer seem less relevant.

I usually use

* a grid containing an int for each cell, this int being able to carry up to 32 flags (using bitwise operation)
* a list of objects (may be an array or database records), each one having an x and an y

Not referencing the objects from the grid avoid coherency/race problems and is lighter.

A frequent practice is also to use a monodimensional array and to address the cells as `a[x+W*y];`. It makes many operation (like the cloning of the whole map or any range operation independent of the position) easier and faster. I'm not really familiar with node.js but I suppose the Buffer class should be used.

As I suppose you'll want to use a browser as final interface, here's a trick I use : I encode my maps as PNG, with each color of the palette simply being one of the possible flag combinations. This makes

* storage and transmission very efficient (PNG is compressed)
* map operations easy with image based operations
* fast rendering at low resolution easy in the browser using image rendering

# Answer
> 3 votes
You should absolutely use this approach:

```
{ something: N, something2: N}

```

Deciding to not use it, is a perfect example of *premature optimization*.

Just do the simplest thing that will work, and if it is slower or takes too much resources (this will more likely be the problem, not speed) you optimize from there.

People nowadays underestimate what a powerful beast they have in front of them. And I am not even talking about your dev PC, but of modern smartphones/tablets.

---
Tags: javascript, performance
---


# Question
Title: Is there an FBX file/model viewer for Mac OS X?
Is there a free tool I can use to view and inspect FBX assets? I've got a bunch of FBX files and I'd like to look at the mesh and textures and preview the animations.

# Answer
Found it! The FBX Converter can be downloaded from the FBX Plug-Ins, Converter, and QuickTime Viewer Downloads page. One opened there's an "Add FBX Viewer" button which can display FBX contents and animations.
> 4 votes

# Answer
Try this:

http://usa.autodesk.com/adsk/servlet/pc/item?id=10775855&siteID=123112

Down the page is a thing called

FBX 2013.3 Plug-in for QuickTime

I think this will allow you to open FBX files in Quicktime.
> 0 votes

---
Tags: macos, fbx
---