title: Separate draw and physics loops

text:
# Question
Title: Separate draw and physics loops
I there a point in updating the physics at a different rate than drawing / taking input? Is it just to exploit parallelism?

I've heard that many engines update the physics at 15FPS but render at 60FPS. What's the point in rendering the same image four times until it changes if it doesn't add fluidity?

# Answer
Physics literally *can't* be updated at the same time as drawing in many games, even if the programmer wanted to. Physics in most games is significantly more complicated than just applying velocity and acceleration. You can't simply move an object and then draw the object, since the actual final position of that object is going to require multiple passes over all nearby objects, constraints, etc.

The only way to get meaningful transform data out of physics is to let it step the entire physical simulation.
> 1 votes

# Answer
Usually you want physics to be deterministic, in that if you run your game multiple times the exact same simulation will occur each time. One key factor in implementing determinism is to have a timestep that never changes. The amount of time passed to physics shouldn't be a variable, but a constant.

However, when graphics is being run and things rendered to the screen it may be favorable to run at maximum FPS, or at 60 FPS, or 30 fps, or whatever you like. It's easiest if you let rendering occur at a variable interval, and only update the physics when discrete chunks of time has passed.

This idea doesn't have anything to do with parallelism.

Also, you don't render the same thing 4 times. Usually you interpolate between the lower resolution discrete jumps in physics. Say an object moves from point A to point B over the course of 4 render frames. Each render frame would interpolate from A to B to create a very smooth transition. In this way usually the screen renders about an entire frame behind whatever the actual physics is doing.
> 1 votes

# Answer
you don't render the same game state 4 times but interpolate the state between 2 physics frames

also 15 (visual) FPS just feels laggy you need at least 25ish to feel smooth
> 0 votes

---
Tags: game-loop
---


# Question
Title: Point in Polygon, Ray Method: ending infinite line
Having a bit of trouble with point in polygon collision detection using the ray method
i.e. http://en.wikipedia.org/wiki/Point\_in\_polygon
My problem is I need to give an end to the infinite line created.
As with this infinite line I always get an even number of intersections and hence an invalid result.
i.e. ignore or intersection to the right of the point being checked
what I have
what I want

My current code based of Mecki awesome response

```
for (int side = 0; side < vertices.Length; side++)
        {
            // Test if current side intersects with ray.

            // create infinite line
            // See: http://en.wikipedia.org/wiki/Linear_equation
            a = end_point.Y - start_point.Y;
            b = start_point.X - end_point.X;
            c = end_point.X * start_point.Y - start_point.X * end_point.Y;

        //insert points of vector
            d2 = a * vertices[side].Position.X + b * vertices[side].Position.Y + c;
            if (side - 1 < 0)
                d1 = a * vertices[vertices.Length - 1].Position.X + b * vertices[vertices.Length - 1].Position.Y + c;
            else
                 d1 = a * vertices[side-1].Position.X + b * vertices[side-1].Position.Y + c;

            // If points have opposite sides, intersections++;
            if (d1 > 0 && d2 < 0 )
                intersections++;
            if (d1 < 0 && d2 > 0 )
                intersections++;

        }
//if intersections odd inside = true
    if ((intersections % 2) == 1)
        inside = true;
    else
        inside = false;

```

# Answer
> 1 votes
You should be thinking about the problem from the point of view of casting a ray from a point to infinity. In your drawings you're casting a ray from infinity to a point.

This is a math problem, so if you're having trouble writing the code I'd be keen to recommend you try to solve the problem on paper first and then transcribe your math into code. This is always the best approach for geometry problems like this.

The idea is to compute the intersection point of both lines, then use barycentric coordinates to see if your intersection point lays within the line segment of your polygon. This last part seems to be what your `d1` and `d2` variables are doing.

---
Tags: xna, collision-detection, geometry
---


# Question
Title: What do I need to Mod a Unreal Engine 3 game?
what I am looking for is some advise making a mod for a certain game and how I would go about making it. The game I am talking about is Blacklight: Retribution and what I wan't to know is; Is it possible? And if so, what programs will I need? It is an online only game so I was unsure how plausible a mod would be for it. Plus I have never made a video game before, but I do like the game and I wanted to do some things with it. Additionally, this will be my first time making anything video game related so I would appreciate any advise.

To expand a bit, I plan to add something simple at first. A mod that would let you spectate another player in the first person. Then I plan do something a bit more complex where I want to make so the game optionally always records you playing (in short intervals most likely or you would run quickly out of memory). After all that is done I would add items, armor, weapons, and maybe make a map or not I am not sure but this in a shell what I hope to do. I don't know much about these things but I am reading anything I can get my hands on. So if this is overly ambitious or just plain out not a possibility any advise on what I should look to instead will be welcomed warmly. Thank you.

# Answer
> 0 votes
I hate to be the one to say it, but modding for that game is not possible. BUT NEVER FEAR! There are tons of games out there to start getting your hands dirty. Seeing as your beginner and never worked with programming I would not recommend something as complicated as recording thing you just described. Surprisingly, the things you mentioned later are actually easier stuff to do. But still complicated for a beginner.

Here are some awesome websites I've found to be very handy over the years. http://www.pixelprospector.com/

http://unity3d.com/ (A very great engine for the beginner)

---
Tags: modding, unreal
---


title: Rotation matrix for a 3D vector

text:
# Question
Title: Rotation matrix for a 3D vector
I have a direction vector on which I have to apply some rotation to align it to positive z-axis. To use `Matrix.CreateRotationX(angle)` of `XNA`, I need the `angle` for which I'd have to compute cos or tan inverse.

I think this is a complex task to do. Also, eventually those are also converted to `sin(angle)` and `cos(angle)` in the matrix.

**Is there any *inbuilt* way to create rotation matrix from a 3D vector?**

However, I can write the function but still asking if there is one already there.

# Answer
You are **very much correct** in your thinking that you shouldn't be using trigonometric functions where you don't absolutely need them. Particularly in cases where your calculation is using both a trigonometric method *and* its inverse (noting, as you do, that `Matrix.CreateRotation*` uses `sin` and `cos` internally).

---

***However***, you need more than a single vector to accomplish what you are trying to do!

What Outlaw Lemur and Tiago Costa were pointing out in comments is that you don't get a rotation just by specifying a single vector. You need to specify that vector *relative* to another vector. Traditionally people just choose a fixed vector representing "up" - in XNA: `Vector3.Up`.

So if you passed `Vector3.Up` to your rotation method, you would expect to get no rotation at all.

***But***, even then, this is not enough to *fully* specify a rotation. If you picture the above system in your head, imagine you have an "up" axis that you are rotating into a new position. But you're still free to rotate *around* that new "up" axis. You need *another* vector to select a specific rotation around that axis.

For this, people typically choose "forward" or "right" or "left" (and `Vector3` has these static properties as well, for XNA's right-handed coordinate system).

**So with an "up" and a "forward" vector, you have fully defined the rotation of an object.**

---

Now, the original question was: does XNA have a built-in method for creating such a rotation matrix? **Yes it does**. It also lets you simultaneously specify a translation. It's:

```
Matrix.CreateWorld(Vector3 position,
                   Vector3 forward,
                   Vector3 up);

```

(MSDN)

(And there's also `CreateLookAt`, which does a similar thing for cameras.)
> 2 votes

# Answer
The following code conveys the intent of RandyGaul's answer translated into Xna(ease).

```
Matrix RotationNeededToAlignArbitraryVectorWithZAxis(Vector3 arbitraryVector)
{
    arbitraryVector.Normalize();
    Vector3 axis = Vector3.Cross(arbitraryVector, Vector3.UnitZ);
    float partialAngle = (float)Math.Asin(axis.Length());
    float finalAngle = arbitraryVector.Z < 0f ? MathHelper.PiOver2 - partialAngle + MathHelper.PiOver2 : partialAngle;
    axis.Normalize();

    return Matrix.CreateFromAxisAngle(axis, finalAngle);
}

```

It so happens that when you need to cross a couple normalized vectors (usually to find the axis), the magnitude of the result is the arcSin of the angle that separates the 2 vectors just as the dot product is the arccosine of the angle that separates them. So since a cross is necessary in this case, I used the cross result to derive the angular value instead of calculating the dot product.

The order of the arguments in the cross is important, don't swap them.
> 3 votes

# Answer
You can probably use the axis angle representation to build a rotation matrix, with whatever math library you have available.

If you dot your vector (normalized) with the z axis vector (normalized) and take the inverse cosine of this result, you have the angle you need to rotate by. To get the vector to apply this rotation along you can cross your vector with the Z axis to get an appropriate perpendicular.

From here it's just a matter of using the axis angle representation of a rotation matrix.

```
Vector v;
float theta = acos( dot( v, zAxis ) );
Matrix3 m = AxisAngle( theta, normalize( cross( v, zAxis ) );

```

Please note that this code will give poor results when your vector is nearly parallel with the z axis. To avoid this problem it would be sufficient to make sure the length of the cross product result is clearly not near zero before executing the rest of the code.

As Steve pointed out in the comments this isn't quite enough as you'll need to know which direction to rotate about your vector, either theta or -theta. I haven't worked out these details, so I'd recommend taking a look at his comment.
> 1 votes

---
Tags: c#, 3d, xna-4.0, rotation, graphics-programming
---


title: GLSL Normals not transforming propertly

text:
# Question
Title: GLSL Normals not transforming propertly
I've been stuck on this problem for two days. I've read many articles about transforming normals, but I'm just totaly stuck. I understand choping off W component for "turning off" translation, and doing inverse/traspose transformation for non-uniform scaling problem, but my bug seems to be from a different source.

So, I've imported a simple ball into OpenGL. Only transformation that I'm applying is rotation over time. But when my ball rotates, the illuminated part of the ball moves around just as it would if direction light direction was changing.

I just can't figure out what is the problem. Can anyone help me with this?

Here's the GLSL code:

Vertex Shader:

```
#version 440 core

uniform mat4 World, View, Projection;

layout(location = 0) in vec3 VertexPosition;

layout(location = 1) in vec3 VertexColor;

layout(location = 2) in vec3 VertexNormal;

out vec4 Color;
out vec3 Normal;

void main()
{
    Color = vec4(VertexColor, 1.0);

    vec4 n = World * vec4(VertexNormal, 0.0f);
    Normal = n.xyz;

    gl_Position = Projection * View * World * vec4(VertexPosition, 1.0);
}

```

Fragment Shader:

```
#version 440 core

uniform vec3 LightDirection = vec3(0.0, 0.0, -1.0);
uniform vec3 LightColor = vec3(1f);

in vec4 Color;
in vec3 Normal;

out vec4 FragColor;

void main()
{
    diffuse = max(0.0, dot(normalize(-LightDirection), normalize(Normal)));
    vec4 scatteredLight = vec4(LightColor * diffuse, 1.0f);

    FragColor = min(Color * scatteredLight, vec4(1.0));

}

```

And here is demonstration of the problem:

# Answer
Andon is making the correct assumption I believe. Specifically, the `n` vector in the vertex shader should be assigned as `View * World * vec4(VertexNormal, 0.0f);` so that view space normals are used in both the position and the vertex normal computations.

One additional suggestion: the `Normalize(Normal)` execution may be more efficient if it is applied to each vertex normal before the results are used in the fragment shader. Try assigning `Normal = Normalize(n.xyz)` in the vertex shader right after the view space normal assignment...then take it out of the diffuse shading line in the frag.

Basically, my thought is vertex normalization can be parallelized in the vertex shader context, and it may not happen parallelized during the fragment shader.

Either case, the above solutions should make the sphere shading invariant to rotation which was your problem in the first place.
> 2 votes

# Answer
Found where was the problem. I just didn't fetch normals properly while parsing fbx. Now everything works fine.
> 1 votes

---
Tags: opengl, glsl, transformation, normals
---


# Question
Title: How do I save my game with highscores and player positioning in LibGDX?
So I have a game that needs to save high scores for the number of waves, what guns the player has, positioning of the player and the zombies, and so on. I saw something about SharedPreferences but have no clue how to use them. Can someone point me to the right direction or willing to tell me how to use them correctly?

# Answer
> 1 votes
Here how to save your datas with SharedPreferences :

**Store data**

```
SharedPreferences sp = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor spe = settings.edit();
spe.putInt("someKey", someIntegerValue);
spe.putFloat("anotherKey", someFloatValue);
spe.commit();

```

**Retrieve data**

```
SharedPreferences sp = getSharedPreferences(PREFS_NAME, 0);
float floatValue = sp.getFloat("anotherKey", defaultFloatValue);
int intValue = sp.getInt("someKey", defaultIntValue);

```

Where PREFS\_NAME is a string containing the name you want for your preference file.

However, SharedPreference is not the only solution, you also can use Internal Storage and SQlite DBs.

---
Tags: libgdx, savegame
---


title: Unity - Invert Movement Direction

text:
# Question
Title: Unity - Invert Movement Direction
I am currently developing a 2,5D Sidescroller in Unity (just starting to get to know it).

Right now I added a turn-script to have my character face the appropriate direction of movement, though something with the movement itself is behaving oddly now.

When I press the right arrow key, the character moves and faces towards the right. If I press the left arrow key, the character faces towards the left, but "moon-walks" to the right.

I allready had enough trouble getting the turning to work, so what I am trying is to find a simple solution, if possible without too much reworking of the rest of my project. I was thinking of just inverting the movement direction for a specific input-key/facing-direction.

So if anyone knows how to do something like that, I'd be thankful for the help.

If it helps, the following is the current part of my "AnimationChooser" script to handle the turning:

```
    Quaternion targetf = Quaternion.Euler(0, 270, 0); // Vector3 Direction when facing frontway
    Quaternion targetb = Quaternion.Euler(0, 90, 0); // Vector3 Direction when facing opposite way

    if (Input.GetAxisRaw ("Vertical") < 0.0f) // if input is lower than 0 turn to targetf
    {
        transform.rotation = Quaternion.Lerp(transform.rotation, targetf, Time.deltaTime * smooth);
    }
    if (Input.GetAxisRaw ("Vertical") > 0.0f) // if input is higher than 0 turn to targetb
    {
        transform.rotation = Quaternion.Lerp(transform.rotation, targetb, Time.deltaTime * smooth);
    }

```

The Values (270 and 90) and Axis are because I had to turn my model itself in the very first place to face towards any of the movement directions.

# Answer
Well, I solved it myself now. After a lot more searching I found just the spot to reverse the movement.

I went to the pre-made FPSInputController to the line where it says:

```
directionVector = directionVector * directionLength;

```

And instead changed it to this:

```
        if (Input.GetKey("d") || Input.GetKey("right"))
    {
        directionVector = directionVector * directionLength;
    }
    if (Input.GetKey("a") || Input.GetKey("left"))
    {
        directionVector = -directionVector * directionLength;
    }
    else
    {
        directionVector = directionVector * directionLength;
    }

```

And now the character moves as he is supposed to.
> 0 votes

---
Tags: unity, movement, unityscript, direction
---


# Question
Title: Linking one uniform variable to many shaders
Let's say, that I have 3 programs, and in each of those programs there is a view matrix uniform, which should be the same in all those programs.

Right now, when my camera moves, I need to re-upload the modified matrix to every program separately. Is it possible to create some kind of global uniforms which are constant for all programs linked to it, so I could just upload the matrix once?

I tried creating a globalUniforms object which looked kinda like this:

```
var globalUniforms = {
    program: {},
    // (...)
    vMatrixUniform: null,
    // (...)
    initialize: function() {
        vMatrixUniform = gl.getUniformLocation(this.program, 'uVMatrix');
    }
};

```

So I could just link it to proper programs like this: `program.vMatrixUniform = globalUniforms.vMatrixUniform;`, and then pass the matrix like this:

```
if (camera.isDirty.viewMatrix !== false) { camera.isDirty.viewMatrix = false;
    gl.uniformMatrix4fv(globalUniforms.vMatrixUniform, false, camera.viewMatrix.element);
}

```

but unfortunately it throws an error:

> Uncaught exception: gl.INVALID\_VALUE was caused by call to: getUniformLocation called from line 272, column 2 in () in mysite/js/mesh.js: vMatrixUniform = gl.getUniformLocation(this.program, 'uVMatrix');

Summing up: is there a more efficient way of managing shaders which follows my logic?

# Answer
> 2 votes
You can make an analogy of a GL shader program to a program running on a desktop PC. It is natural to expect that it should have its own private "memory space" for variables. This is necessary for several reasons, such as avoiding name collisions and accidental/erroneous memory reads/writes. So you will not be able to share uniform variables between programs.

You can, of course, keep a single CPU-side copy of your `uVMatrix`, but each program will have to declare a `uVMatrix` uniform and you will have to update all of then when the CPU-side variable changes.

One exception to this would be, like Andon M. Coleman commented, to use a Uniform Buffer Object (UBO). UBOs provide a very nice way of sharing memory between shader programs. They use the same framework of Vertex Buffers and the like, but unfortunately they are not available for WebGL yet. So we are stuck with the duplicate uniform variables until further updates of WebGL start to provide support for UBOs.

# Answer
> 1 votes
You can hack around this by abusing vertex attributes.

Say you have a matrix declared as follows (I'm not using JS here but you should be able to follow):

```
float myMatrix[4][4];

```

Instead of sending it as a uniform to each program object, you send it as vertex attributes like so:

```
glVertexAttrib4fv (13, myMatrix[0]);
glVertexAttrib4fv (14, myMatrix[1]);
glVertexAttrib4fv (15, myMatrix[2]);
glVertexAttrib4fv (16, myMatrix[3]);

```

(Per https://www.khronos.org/registry/webgl/specs/1.0/ this usage is supported in WebGL).

Then you define these input attributes in your GLSL, and rebuild the matrix from them. Now you can change program as often as you wish and - so long as you're consistent in that you use the same attribute slot numbers (via glBindAttribLocation) in each program - the matrix will be available to all of them.

A downside of this approach is that it uses up attribute slots, of which there are a limited number (typically 16), so you most definitely *should not* use it as a general-case workaround. But where you absolutely must share uniforms, this is one way of working around this limitation.

---
Tags: shaders, javascript, webgl
---


title: How are game characters animated?

text:
# Question
Title: How are game characters animated?
I will be working with my friends on our final year project. Our game will be FPS and I have to draw some animations for FPS view and other enemy character that can be programmed easily to make a good game.

I would like to know how game characters are made that are movable? What kind of software and engines are used for these characters?

# Answer
> 18 votes
Game characters are usually animated using a technique called **skeletal animation**: (Image source: Valve Software)

Each 3d model has an invisible bone structure (the red and teal lines in the image above). Each polygon of the model is connected to a bone. When you define a motion sequence, you define it as a sequence of rotations of the bones around their connections to other bones. When a bone moves, the polygons connected to it move with it. This allows to define motion sequences without having to change the position of every single polygon. When multiple characters share the same bone structure, they can also share the same animations, so you don't have to recreate each animation for each character (although you might want to make some animations different for characters of different genders, personality types and levels of physical fitness).

Most 3d modeling software supports skeletal animation and have export-formats which are readable by widely used 3d engines. Please do not ask for product recommendations here, because they are off-topic.

However, letting an artist create animations from scratch doesn't always lead to the best results. It's hard to recreate all the subtle nuances of human body-language from memory, so the results often look robotic and unnatural. That's why larger game studios which have the resources for it use a process called **Motion Capturing**.

Human actors are hired to enact the actions of the game characters. The actors wear special suits during the performance which have highly visible marks attached to them. When they are recorded by a video camera during the enactment, the movement of these marks can be mapped to the bones of the character 3d models. That way the movements of the actors can then be applied to any 3d model which uses the same bone structure. This method usually leads to much more naturally-looking results and when there is a large number of animations to create, it can also be a huge time-saver. (Image source: Toptear Games)

However, the cost for the equipment needed for motion capturing will likely far exceed your budget, so you will have to resort to defining skeletal animations manually in a 3d modeling program.

# Answer
> 3 votes
Actually, the answer by Philipp is quite good, but misses an important point.

Some games (Quake/Q2 being the most notable examples) didn't use any skeletal animation at all - they instead resorted to vertex animation (ie. animating the position of vertices in the mesh). It's actually a lot simpler to support in code, although for big projects this usually don't hold true (but still, many games *were* made that way\*.

For specifics, see e.g.

https://en.wikipedia.org/wiki/MD2\_(file\_format)

Also, this was the default way of defining animations in Flash, 3D Studio and 3DSmax in the days of old (although it stopped being that way after the implementation of skeletal animations for them). I think that for simple games, frame-based interpolation of vertices is still the easiest (in terms of both code *and* modelling effort) way to get started.

# Answer
> 1 votes
Philipp's answer is correct, but it's worth adding that there are (relatively) low cost markerless motion capturing solutions that utilize sensors commonly found at home, such as an array of webcams, Microsoft Kinect sensors or Sony PS Eyes. They usually don't output production-quality animations (you can expect mediocre precision and jitter in most cases), but you'll have the timing right and if you're willing to do some cleanup and some fine-tuning, it'll save you a lot of time compared to manually animating the skeleton (or the mesh directly).

Additionally, there's Mixamo, a service that sells ready-made animations for common skeletal meshes. If I recall correctly, they give an amount of animations for free, for evaluation purposes.

---
Tags: animation, movement, models, character
---


title: How do I temporarily pause an XNA game?

text:
# Question
Title: How do I temporarily pause an XNA game?
Collision with an enemy should pause the game for 1.5 seconds.

My failed attempt:

```
bool tPause;
float timer;

public ovveride Update(GameTime gameTime) {
    if(!tPause) {
        // ...
        if(enemy.rectangle.Intersects(player.rectangle)) {
            timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
            tPause = true;
            if(timer > 1500) {
                tPause=false;
                timer=0;
            }
        }
        // ...
    }
}

```

What am I missing? How can I do this?

# Answer
Once there is a collision, the *timer* variable will not get updated anymore, because the code segment of your if statement will not be executed.

Instead, you can use an *else* statement, where you exectue the code, to update your *timer* variable.

```
bool tPause;
float timer;

public ovveride Update(GameTime gameTime)
{
    if(!tPause)
    {
        if(enemy.rectangle.Intersects(player.rectangle))
        {
            tPause = true;
            timer = 0;
        }
    }
    else // if you are in the paused state
    {
        // update the timer variable and check, if 1.5 seconds passed
        timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
        if (timer > 1500)
        {
            // set the paused state back to false
            tPause = false;
        }
    }
}

```
> 2 votes

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


# Question
Title: LWJGL/Java - Implementing a writeable text box?
I would like to create a writeable text box where a user can input text into it. A nice "send" button that the person could click to send the text to the server would also be nice.

I currently haven no idea how to do this and I do not see any tutorials on how to do this.

I am using LWJGL and Java, and also I am using the Slick2D library.

Thanks!

# Answer
LWJGL is just a binding of OpenGL, a way to buffer data to your graphics hardware. Slick2D is a depreciated game library for rendering images, and telling LWJGL what to do.

Although, Slick2D does have a way to render True-Type font files as quadrilateral images. The TrueTypeFont class has more information on it.

Here's really good tutorial on NinjaCave: http://ninjacave.com/slickutil3

As for buttons, Slick2D does not natively support GUI. But there are really good libraries for GUI handling (With text integrated) The most popular and configuable is nifty-ui: http://nifty-gui.lessvoid.com/
> 2 votes

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


title: Key Handling mechanics

text:
# Question
Title: Key Handling mechanics
I am new to game development and am working on my first game using OpenGL and C++. I have a game class which handles everything necessary in an update() function. Now i want to handle keyboard inputs. I use GLFW which supports key callbacks. However i wonder how to deal with inputs. Should i record the keys pressed and poll on it the next time my game updates or should the callback immediately perform the necessary actions? And why?

Thanks :)

# Answer
> 2 votes
It's far easier to control how your game controller acts if you take any asynchronous key inputs and store them away until the update loop can get to them.

First reason is that the update function may change conditions before the key is handled. For example: I press fire. If handled immediately you would create a fire action, but in update handling it could be that you're declared dead and unable to fire.

Second reason is that let's say you quickly press two keys, go left and go right. If handled immediately that could fire off all sorts of secondary actions like animation changes, but if handled at update you can parse all the inputs and intelligently decide what the final outcome is and avoid lots of extra work.

Corollary to second reason is that combination keys are now easily handled, say Left + Up which would normally be handled by two separate callbacks for left and then up are now parsed by update as an entire action that means go diagonal.

# Answer
> 0 votes
**As pointed out in the comments, I have discovered that this version only works if using LWJGL, the java port of OpenGL.**

Use OpenGL's Keyboard class.

Please note that I use LWJGL so the syntax may be different from yours.

```
while (Keyboard.next()){
            if (Keyboard.isKeyDown(Keyboard.getEventKey())){
            String app = Keyboard.getKeyName(Keyboard.getEventKey());
            if (!Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)){
                app = app.toLowerCase();
            }
            if (app.length() != 1){

            }else{
            //if (app != null && app != "" && app != " "){
                TextDemo.user.append(app);
                System.out.println(app);
            }
            }
            //}
        }

```

Keyboard.next() checks if a key has been pressed down or released. I check if the event key is down. The event key is the key that is involved in the press or release, and I want to see that it has been pressed, not released. The output is capitals, so if shift is down I keep it capitals, if it is not then I make it lowercase. I have yet to implement caps lock.

And the rest of the code is checking that it is not something like the spacebar or shift (More than 1 character), and if it is not, then append it to a string which I draw onto the screen in another piece of code that I have not shown above.

You can also use Keyboard.getEventCharacter(), however in my experience this returns a weird box character which can be annoying. Experiment with it :).

Hope this helped!

Edit: The above was mainly for typing strings. You can use the following code as well:

```
if (Keyboard.isKeyDown(Keyboard.KEY_YOURKEYHERE));
if (Keyboard.isKeyDown(Keyboard.KEY_SPACE));

```

# Answer
> 0 votes
It depends. Personally I would look at key presses in a constant part of the loop instead of performing the action as soon as the key is pressed. But it may be beneficial to you to perform the actions as soon as the key press comes in. Is there anything that need immediate processing in your application?

---
Tags: input, keyboard
---


# Question
Title: Can various browsers be assumed to maintain predictible state accurately in multiplayer online gaming?
With many games it is said that **server will assume that clients keep track of the world accurately**. Assuming this is true, for a browser based multiplier space invaders game you would only tell the client when new bullets or the players ship moves and everything that behaves in a predetermined manner in the js client.

It would be expected that positions would be the same in the browsers. Do you think you could trust browsers to do this? I feel that timings could differ between rendering loops and cause positions to get out of sync and might just get the server to maintain all the positions to make sure.

# Answer
The server should maintain all the positions to "make sure" anyway -- this is how you prevent trivial cheating.

Most browsers have a "debug mode" they can be put into. It's trivial for me to hit F12 on my copy of IE, for example, and have access to a JS debugger I can use to halt execution, inspect variables, and change them. So you should be aware that a client could potentially do that.

Even without that sort of effort on the end-user's part, you shouldn't rely on your simulation being in *exactly the same state* at *exactly the same time* on all machines; that level of synchronization is basically improbable to achieve for real-time games, since you are dealing with the internet and all the latency involved, floating point inaccuracies, clock drifts, et cetera.

Most of the time things will be "good enough" that you can do what you are asking and send only the updates to the client, allow the clients to simulate locally (this is good, in fact, because it allows you to hide some of the latency and make your game feel better) but you should still simulate everything on the server and periodically ensure the client and server are in sync.

You should not trust client state, ever (not just for browser-based games either).
> 8 votes

# Answer
Yes, it's fully possible to trust client state, and to mutate that state across all clients using only commands. (Whether or not that's a good idea with respect to security and cheat protection is another matter.)

Mark Terrano and Paul Bettner describe one such model in this article about Age of Empires multiplayer synchronization. Think of a game as a sequence of game states (or, better yet, a *trajectory* through the space of all possible game states) and imagine what's necessary to keep the trajectory of each client the same.

Again, this answer is not about trusting the browser or any other client environment from a security or cheating perspective. It's only about distributed state synchronization. From that perspective, **you, the developer, can use a browser to design trustworthy client-side game state and iteration logic.** Verifying that your client has not been tampered with is a different problem, but it is possible to synchronize state with the model you mention.

You have to write your game to execute with the following properties:

* Each client must start with exactly the same initial condition, like a common *seed state*.
* Each command (like `new bullet` or `ship move left by 3`) must change the game state in exactly the same way on each client. (This is called **determinism** and it's the essential part of "trusting" your code to behave identically on all clients.)
* On each client, before applying a command, all previous commands from each client must already be received and applied in the same order on each client.

### Things to be careful of, because they degrade determinism:

* The same code can do strangely different things on different machines, whether it's JavaScript in Firefox vs. Chrome, or C++ in OS X vs. Windows. Same code + different behavior == nondeterministic program!
* Floating point (decimal/fractional) numbers are dangerous, because they are more difficult to mutate deterministically.
* Commands that use a random number generator should be seeded by the same number on each client, that way each client gets the same random number each time one is generated. In other words, random number generation needs to behave (you guessed it...) deterministically!

# TLDR

1. Make a deterministic system composed of game state and game commands.
2. Make sure each client starts with the same state.
3. Make sure each client applies the same commands in the same order as close to the same time as possible.
> -1 votes

---
Tags: multiplayer, browser-based-games, node.js, game-state
---


# Question
Title: In 3D camera math, calculate what Z depth is pixel unity for a given FOV
I am working in iOS and OpenGL ES 2.0. Through trial and error I've figured out a frustum to where at a specific z depth pixels drawn are 1 to 1 with my source textures. So 1 pixel in my texture is 1 pixel on the screen. For 2d games this is good. Of course it means that I also factor in things like the size of the quad and the size of the texture.

For example if my sprite is a quad 32x32 pixels. The quad size is 3.2 units wide and tall. And the texcoords are 32 / the size of the texture wide and tall.

Then the frustum is:

```
    matrixFrustum(-(float)backingWidth/frustumScale,(float)backingWidth/frustumScale,
                   -(float)backingHeight/frustumScale, (float)backingHeight/frustumScale, 40, 1000, mProjection);

```

Where frustumScale is 800 for a retina screen. Then at a distance of 800 from camera the sprite is pixel for pixel the same as photoshop.

For 3d games sometimes I still want to be able to do this. But depending on the scene I sometimes need the FOV to be different things.

I'm looking for a way to figure out what Z depth will achieve this same pixel unity for a given FOV.

For this my mProjection is set using:

```
    matrixPerspective(cameraFOV, near, far,  (float)backingWidth / (float)backingHeight, mProjection);

```

With testing I found that at an FOV of 45.0 a Z of 38.5 is very close to pixel unity. And at an FOV of 30.0 a Z of 59.5 is about right. But how can I calculate a value that is spot on?

Here's my matrixPerspecitve code:

```
void matrixPerspective(float angle, float near, float far, float aspect, mat4 m)
{
    //float size = near * tanf(angle / 360.0 * M_PI);
    float size = near * tanf(degreesToRadians(angle) / 2.0);
    float left = -size, right = size, bottom = -size / aspect, top = size / aspect;

    // Unused values in perspective formula.
    m[1] = m[2] = m[3] = m[4] = 0;
    m[6] = m[7] = m[12] = m[13] = m[15] = 0;

    // Perspective formula.
    m[0] = 2 * near / (right - left);
    m[5] = 2 * near / (top - bottom);
    m[8] = (right + left) / (right - left);
    m[9] = (top + bottom) / (top - bottom);
    m[10] = -(far + near) / (far - near);
    m[11] = -1;
    m[14] = -(2 * far * near) / (far - near);
}

```

And my mView is set using:

```
lookAtMatrix(cameraPos, camLookAt, camUpVector, mView);

```

*** UPDATE ***

I'm going to leave this here in case anyone has a different solution, can explain how they do it, or why this works.

This is what I figured out. In my system I use a 10th scale unit to pixels on non-retina displays and a 20th scale on retina displays. The iPhone is 640 pixels wide on retina and 320 pixels wide on non-retina (obsolete). So if I want something to be the full screen width I divide by 20 to get the OpenGL unit width. Then divide that by 2 to get the left and right unit position. Something 32 units wide centered on the screen goes from -16 to +16. Believe it or not I have an excel spreadsheet do all this math for me and output all the vertex data for my sprite sheet.

It's an arbitrary thing I made up to do .1 units = 1 non-retina pixel or 2 retina pixels. I could have made it .01 units = 2 pixels and someday I might switch to that. But for now it's the other. So the width of the screen in units is 32.0, and that means the left most pixel is at -16.0 and the right most is at 16.0.

After messing a bit I figured out that if I take the \[0\] value of an identity modelViewProjection matrix and multiply it by 16 I get the depth required to get 1:1 pixels. I don't know why. I don't know if the 16 is related to the screen size or just a lucky guess. But I did a test where I placed a sprite at that calculated depth and varied the FOV through all the valid values and the object stays steady on screen with 1:1 pixels. So now I'm just calculating the unityDepth that way.

If someone gives me a better answer I'll checkmark it.

# Answer
I'm answering this myself since no one else has touched it in a month.

I'm not sure why it works. If I ever get a chance to go through all the math to figure it out. But this is the code that I worked out, and it works across all FOV's. I tested it by sliding through all FOV's and placing my sprite at unityDepth, which changes for each FOV. The sprite stays at pixel for pixel the whole time with no jello or distortion.

The way I do it in this app is 'centerField' is a zDepth of what I'm focusing on. Then instead of having a huge frustum that goes from .01 to whatever, I only go a range around that. The reason for that is to add resolution steps to my depth buffer. But that's a different discussion. You could replace the near and far (`centerField+350`) with whatever values you normal use. It doesn't effect this z depth unity issue.

```
GLfloat centerField = cameraPos.z - camLookAt.z;
GLfloat near = centerField-150;

if (near<1.0) {
    near=1.0;
}

matrixPerspective(cameraFOV, near, centerField+350,  (float)backingWidth / (float)backingHeight, mProjection);
matrixCopy(mProjection, pProjection);

matrixMultiply(mProjection, mView, mViewProjection);

unityDepth = mViewProjection[0]*16;
focusZ = -unityDepth;

```
> 1 votes

---
Tags: 3d, ios, opengl-es2
---


title: Tessellation vs Geometry Shader

text:
# Question
Title: Tessellation vs Geometry Shader
Correct me if I'm wrong, but both the Geometry Shader and the Tessellation Shader jobs are to generate vertices in the Graphic Pipeline. What I would like to know is how they are different and when should I use one over the other?

# Answer
> 15 votes
Actually no, the 'job' of the geometry shader (GS) is primative evaluation.

Geometry shaders can tesselate, but they are limited by a) an in-process upper bounds on the number of output elements, and b) execution within a single shader...of course shader instancing aleviates the 2nd issue, but overall geometry shaders are more effective at primative evaluation and/or value interpolation than they are at tessellation.

By comparison, tesselation shaders (TS) were introduced specifically to perform geometry densification so they perform well, are robust to an ever widening array of algorithms, (pun intended) and they are less limited by output bounded buffers.

Daniel Rákos has a good article on the GS/TS evolution: History of hardware tessellation

When to apply each is a case of 'use the right tool for the job' and here is how: Build a rough draft pipeline without a tesselator to get primitives evaluating correctly in the VS/GS/FS. Separately scope the view- or scene-based tessellation, then insert the TS ahead of the GS to densify primitives which are then passed to your already-designed GS. If you want to try a different TS then build an alternative up and swap it into the pipeline...you can even use an instanced GS to dynamically select the right TS based on a primitive's properties!

---
Tags: shaders, hlsl, geometry, tessellation
---


title: Problem with publishing an XNA game

text:
# Question
Title: Problem with publishing an XNA game
I can't publish a game in XNA, if I try there comes out 2 errors:

1)Could not find required file 'setup.bin' in'C:\Users\Trica\Desktop\example\example\ example\Engine'.

2)Cannot publish because a project failed to build.

What can I do?

# Answer
> 0 votes
I think this issue is probably related with bad paths and not with XNA itself. Take a look at this answer :

https://stackoverflow.com/questions/11139538/could-not-find-required-file-setup-bin

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


# Question
Title: Why was my Facebook game rejected with the note that "your app icon must not overlap with content in your cover image?"
My FB game just recently got rejected for two reasons. The first I fixed, but I just can't see to figure out what they mean by the second, and I was hoping someone else got the same issue and did know what they meant.

The remaining error is:

> **Cover Image**
>
> Your app icon must not overlap with content in your cover image. Click on 'Web Preview' in the 'App Details' section to check for overlap prior to submitting your app. See more here.

All I know is that the rejection has something to do with the cover image, not the icons or the screenshots.

The web preview of my game looks like this now:

Please let me know what to do to get approved.

# Answer
> 2 votes
> **Your app icon must not overlap with content in your cover image.**

---
Tags: facebook
---


# Question
Title: How to manipulate 2d image as different objects
Hello Im very new to this so I don't even know what this process is called exactly. Im posting image of flappy bird here in which it consist all the objects day, night, birds, font etc Here :

So how to use them in 2D game? this is just example i have used. How to manipulate different objects at different coordinates ? Thanks.

# Answer
"A texture atlas is a large image containing a collection, or "atlas", of sub-images" - So basicly since we have sub images we will need sub rectangles.

Depending on what you want to do, the engine you use you would use this in diferent sections.

For example, in my engine I do something like this

```
MyTexture.Draw(Position,SubRect,Texture ,(...));

```

SubRect is the section of the atlas I want , My Atlas is 100\*100 I want the the piece that stays at (50,50) and is 10 Width and 10 Height, So my sub rect is equal to (50,50,10,10). this says to my engine to "slice" that part and render it a Position coordinate.

From the look of your answers you need to learn a few things before. You lack knowledge on game design.

Either way, adressing your second question,

To manipulate each sprite as independent object, you would have a abstraction class called GameObject in my case, which has a Sprite associated.

So when I loop through my objects and draw them I actually Draw the Inner Sprite at the Object position, this way I can do what i want with my Objects and they will be aligned to their sprites.

Hope this helps!
> 1 votes

# Answer
That would be called a sprite sheet/texture atlas. Your game would have objects and might have textures that all reference the same image but specify different locations. So when you go to render them, you simply load the same image, while drawing a different portion of the image. This is done differently in different frameworks/engines/platforms/etc.
> 1 votes

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


# Question
Title: How can I simulate the sun's position for 3D lighting?
I'm using a directional light as a light source. It dosn't have a positon, only a direction, represented by a vec3.

I'm trying to figure out how to make the light direction to simulate sun movement and I'm clueless where to start. There's a related question here on gamedev but its 2d and only on suns position, which I am not interested in. Any suggestions on how to start?

# Answer
> 2 votes
You will need to explain a bit better, a vector can be described as a diference between 2 points A-B =\> C C will be your direction

So if you want to get the sun direction you need to assume that you SUN is at some position, lets call it

```
SunPos = Vector(0,0,0);

```

To get direction from the sun to whatever surface you are , just do

```
Direction = CurrentPoint - SunPosition

```

Unless I am not understanding what you are saying.

To simulate the Sun movement just make the Sun position Change based on Cos and Sin function, this will simulate the sun position across the earth and calculate the direction based on that position.

```
SunPos = Vector(Cos(time),Sin(Time);

```

This for 2D, if 3D you need to decide which axes is the sun moving, but the principle is the same.

Hope this helps.

# Answer
> 1 votes
Another definition of a vector is as a normal to a plane or primative face. The sun's rays can be simulated by the same sin/cos motion as described in Morphex' answer, but the sun's apparent motion can be applied as a scaled dot product with the normal to the ground plane. The scaling is a time-dependent matrix of cos and sin so that the direction vector is long (ie. the dot product to the ground normal is small) near sunrise and sunset and approaches unity (parallels the ground normal) at midday.

Of course this is a crude approximation, but can be improved by multiplying an azmuthal angle based on your scene's latitude. This helps simulate the roughly 18deg. off-axis tilt of the earth and adjusts the sun normal for the scene's distance from the equator. (The effect would be more in New York than in Mexico City, for example.) Yet another angle can be applied to account for season of the year at that latitude.

Google 'modeling apparent sun direction' for some more details.

Lastly, remember to reverse the sign of the vector you get from this process when you apply it as light because you first derive it as outward from the ground, but use it as an inbound light vector!

---
Tags: mathematics, algorithm
---


# Question
Title: Game testing on Android - emulator or real devices?
I am working at a localization agency and we have been approached by a client about testing their games on iOS as well as Android. Testing on iOS seems fairly easy as we can just buy a couple of devices and we should be covered. For Android it seems to be completely different. From what i found, the emulator can cover all API levels, screen sizes and such, but i hear it's buggy and nothing could replace testing on real devices. With the vast amount of Android devices out there and the rate at which new devices are released it seems impossible to keep up. How can i test games (localization and functional) on Android covering all compatible devices?

# Answer
> 5 votes
The only real thing that is different is the amount of devices, Apple just sell 1-2-3 new product each year, Android offers 1 new product every day/week.

The emulator it's not buggy, it's just not intended for profiling, if you want to profile an Android application you have to do the same thing that you have done for iOS: consider the lowest profile device that match your requirements and buying it.

You are supposed to have at least a basic know-how about the ARM architecture, otherwise you can make a difference between all the devices on the market, begin to outline the hardware features that are important for your application and buy that device for real testing.

# Answer
> 1 votes
In our company we prefer not to use emulators as they don't show real picture especially in terms of performance, instead we select several real devices to cover most popular screen size / gpu vendor / form factor combinations, more about how we select test devices on our blog http://developers.nravo.com/best-test-devices-for-game-development/

# Answer
> 0 votes
The Android emulator provided by the SDK has serious performance issues on all systems. Proper "functional" testing as you describe is probably completely invalid using emulators only. Also as far as I know, the emulator doesn't cover manufacturer-specific implementations of the Android OS. So even if you spoof, say, all the hardware of a Samsung Galaxy SII with the emulator, you may still get bugs specific to the Samsung implementation of Android. Lastly, you simply can't multi-touch with a mouse...

The only valid solution I can imagine is buying as wide a range of the most popular Android devices you can afford (in dollars) for your functional testing, and then use the emulator to test as many other specifications of phones as you can afford (in man hours). Fortunately the Android platform is robust enough this *usually* covers the majority of issues, but weird edge bugs still occur on some specific devices.

# Answer
> 0 votes
The solution to this might be test partitioning.

Consider partitioning into a low-end, medium/normal, and high-end device, for example. You can reasonably expect (in terms of performance) that if the performance is X on a certain low-end device, it will be reasonably similar on a similar low-end device.

With this in mind, you can judiciously choose devices that represent a "class" of devices and test of those.

And ultimately, as anyone who shipped an Android game will tell you, **every phone has its own unique quirks and bugs.** Make sure you use some sort of analytics tool (I used Flurry Analytics) that allows you to capture errors; you can eventually diagnose and fix a number of these, increasing the range of devices on which your game works on.

In my opinion, the emulator is only good for functional tests; it neither has decent performance, nor does it represent device-specific bugs. I would avoid it. If you want a decent alternative with decent performance, go with BlueStacks, which is an implementation of Android on Windows.

---
Tags: android, testing, playtesting, localization
---


# Question
Title: Is HTML5/WebGL performance unreliable on low-end Android tablets and phones?
I've developed a couple of WebGL games, and am trying them out on Android. I found that they run very slowly on my tablet, however. For example, a game with 10 sprites or so runs as 5fps. I tried Chrome and CocoonJS, but they are comparably slow. I also tried other games, and even games with only 5 or so moving sprites are this slow. This seems inconsistent with reports from others, such as this benchmark. Typically, when people talk about HTML5 game performance, they mention well-known and higher-end phones and tables. While my 7" tablet is cheap (I believe it's a relabeled Allwinner tablet, apparently with the Mali 400 GPU), I found it generally has a good gaming performance. All the games I tried run smoothly. I also developed an OpenGL ES 2 demo (in Java) with 200 shaded 3D objects, and it ran at 60fps.

My suspicion is that the WebGL engines have unacceptably limited support for many low-end and white-label devices (for example, relying on software fallback for no apparent reason), which means there may be a large section of gamers you will not reach when you choose this as your platform. I've heard rumors about inconsistent performance of HTML5 and WebGL on different devices, but no clear picture emerges.

I would like to hear if any of you have had similar experiences with HTML5 or WebGL, or whether I can find information about the percentage of devices I can expect to have decent performance.

**EDIT**: As a "thorough" way to prove my point, I've started on a WebGL implementation of my own, to see if I can do any better than CocoonJS. Results are promising so far. On said tablet I can draw like 10,000 sprites at 60fps, all updated and drawn in JS through a WebGL compatible API. Check out the APK here. So, I guess that proves that the existing WebGL implementations are really doing something wrong. I'm now in the process of making my games playable in my framework.

# Answer
> 1 votes
CocoonJS implements a direct conversion of WebGL calls to openGL. This allows us to run ludei webgl logo on a Nexus One running android 2.3.4 at 15 fps.

The problem is that mobile GPUs have certain limitation, such as the bandwith limit of GPUs, between others.

This stuff has been discussed here regarding mobile GPU limitations. On the other hand, cocoonJS has special (non-standard) javascript functions to deal with this stuff, such as image.dispose().

I know you're referring to 3D and webGL. WebGl engines has not been created thinking in mobile GPUs, so this theme is recurrent for people running 3rd party engines. The problem isn't webGL, but the way webGl engines are developed.

---
Tags: android, html5, webgl
---


# Question
Title: How can I transform a Point2f with a matrix on Android?
I'm developing for Android and I'm using the `android.renderscript.Matrix3f` class to do some calculations.

What I need to do now is to now is to do something like `mat.tranform(pointIn, pointOut);`

So I need to transform a matrix by a given `Point` class. In `awt` I would simply do this:

```
AffineTransform t = new AffineTransform();
Point2D.Float p = new Point2D.Float();
t.transform( p, p );

```

But in Android I now have this:

```
Matrix3f t = new Matrix3f();
PointF p = new PointF();
// Now I need to tranform it somehow..

```

But the `Matrix3f` class in Android doesn't have a `Matrix.transform(Point2D ptSrc, Point2D ptDst)` method.

So I guess I have to do the transformation manually. But I'm not really sure how that works. From what I've seen it's something like a `translate` and then a `rotate`?

Could anyone please tell me how to do this in code?

# Answer
> 1 votes
Matrix transform functions are just implementing matrix multiplication, which is pretty straightforward. For the simple (non-homogeneous) 2D case, you have a matrix of four values:

$$ \begin{bmatrix} a & b \\ c & d \end{bmatrix} $$

multiplied by a 2-vector (x, y).

I'm most used to the convention that vectors are columns, and so are multiplied on the right, like so: $$ \begin{bmatrix} a & b \\ c & d \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix} = \begin{bmatrix} ax + by \\ cx + dy \end{bmatrix} $$

Here, each entry of the result vector is the dot product of the input vector with the corresponding row of the matrix. (The opposite convention is also valid, where vectors are columns and are multiplied on the left - just know which one your libraries expect)

If you want homogeneous coordinates (necessary for translating with a matrix), then you're "really" working with a 3-vector, (x, y, 1), something like:

$$ \begin{bmatrix} a & b & h\\ c & d & v \end{bmatrix} \begin{bmatrix} x \\ y \\ 1 \end{bmatrix} = \begin{bmatrix} ax + by + h \\ cx + dy + v \end{bmatrix} $$

or equivalently: $$ \begin{bmatrix} a & b & h\\ c & d & v\\ 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} x \\ y \\ 1 \end{bmatrix} = \begin{bmatrix} ax + by + h \\ cx + dy + v\\ 1 \end{bmatrix} $$

So you might be able to use the 3-vector support that already exists in your library, or implement it yourself using the formula above.

---
Tags: android, matrix, transformation
---


# Question
Title: Are there any good html 5 mmo design tutorials?
Hey all. I got a rather inspired after playing gaia online's zOMG and wanted to revive an old project idea I've had laying around for a few years now.

I'm looking to work with html5 (ie canvas, svg based sprites, & WebGL) to build a graphical web based MUD/MMO. Obviously, this is a new take on an old idea and after searching google I haven't really turned up many good resources. But does anyone have any tutorials or other resources to point me in the right direction?

# Answer
> 3 votes
Dwight - dive in and start building. Start small, build your way up. I.e., get a nice little sprite based game working that's talking to a back-end server first, then worry about the whole WebGL thing later.

And ignore the HTML5 doubters. See links below for some nice HTML5 demos and info on what it can do. Also, go check out Google's App store. There are some pretty amazing web based apps people have built that should inspire you.

http://www.chromeexperiments.com \- A collection of impressive tech demos from Google. Requires Chrome, but as far as I know is written primarily to HTML5 standards. If other browsers support the standard, they will work too.

http://www.html5rocks.com/ \- More information on HTML5. Includes an interactive slideshow going over features of HTML5.

# Answer
> 10 votes
No. There are not good tutorials to make MMOs for the languages and environments that MMOs have actually been written in. There are certainly not tutorials for languages and environments that barely work as is.

# Answer
> 2 votes
This is quite similar to this question: Browser-based MMOs (WebGL, WebSocket) which had some helpful answers imho.

# Answer
> 2 votes
There is much room for exploration in this arena. If you're dead set on canvas+websockets, you should consider a non-RPG MMO, something like a massive puzzle game or a simple, iconographic, RTS.

Check out "comet" servers such as cometd, or something that you might build with mochiweb or nodejs. And for the client side you could look into limejs or the dojo.gfx utilities.

Thats as good a place as any to get started. The technology just isn't mature, much experimentation and waiting will be required before the browser is a good place for 'professional' games.

# Answer
> 1 votes
Ok, this is an old question, but it does need an updated answer.

This is 2014, most modern browsers are very reliable in terms of HTML5 features, and Chrome is the most used browser right now.

Probably you won't be able to create a full 3d mmorpg with canvas/WebGL, but you can still create an interesting 2d game with very good performance across most devices.

There are plenty of frameworks out there, and you can even used websockets to allow a fluid multiplayer experience.

With HTML5 you can develop apps much faster than using other 'native' languages, but you will have to drop support to older browsers like IE8 or lesser versions.

---
Tags: game-mechanics, html-canvas, mmo, webgl
---


# Question
Title: How can I compile a Direct3D 9 effect from a file?
I started working with shaders recently in DirectX9. I noticed that there is a `D3DXCompileShaderFromFile` function for `IDirect3DVertexShader9` and pixel shader. Which compiles the shader and gives you the compiled code so you can put that into a file and then read it.

But is there a way to do it with the ID3DXEffect or is `IDirect3DVertexShader9` the only way?

# Answer
Use the `D3DXCreateEffectFromFile` function.

The parameter list is a bit daunting, but most of the parameters are optional and can support null values. Do note, however, the comment for the `flags` parameter:

> If pSrcFile contains a text effect, flags can be a combination of D3DXSHADER Flags and D3DXFX flags; otherwise, pSrcFile contains a binary effect and the only flags honored are D3DXFX flags. The Direct3D 10 HLSL compiler is now the default. See Effect-Compiler Tool for details.

Typical usage would be:

```
LPD3DXEFFECT effect = nullptr;
LPD3DXBUFFER errors = nullptr;
HRESULT result = D3DXCreateEffectFromFile(
  direct3DDevice,
  "Path/To/Your/Effect.fx",
  nullptr,
  nullptr,
  0,
  nullptr,
  &effect,
  &errors
)

```

If the `HRESULT` isn't successful, compilation errors can be recovered from the `errors` buffer (it's just a string; you can case the `void *` returned from `GetBufferPointer`).
> 4 votes

---
Tags: c++, shaders, directx
---


# Question
Title: Unity3D - Android pause screen - double click issue
I made a pause script for the game im developing for android.

I added the script to the GUITexture I created and placed on the top right side of the screen.The issue stands at the part where if the player clicks the pause button then clicks resume then he wants to pause the game again.When he clicks pause the second time the buttons dont show up unless he clicks again.

This is the script :

```
#pragma strict

var paused = false;
var isButtonVisible : boolean = true;

function OnMouseDown(){
    this.paused = !this.paused;
    Time.timeScale = 0;
    isButtonVisible = true;
}

function OnGUI(){
    if ( isButtonVisible ) {
        if(this.paused){
            if (GUI.Button(Rect(Screen.width/2-100,Screen.height/2+3,200,50),"Restart")){
                Application.LoadLevel(Application.loadedLevel);
                Time.timeScale = 1;
                isButtonVisible = false;
            }

            if (GUI.Button(Rect(Screen.width/2-100,Screen.height/2-50,200,50),"Resume")){
                Time.timeScale = 1;
                isButtonVisible = false;
            }

            // Insert the rest of the pause menu logic
            if (GUI.Button(Rect(Screen.width/2-100,Screen.height/2+56,200,50),"Main Menu")){
                Application.LoadLevel ("MainMenu");
                isButtonVisible = false;
                Time.timeScale = 1;
            }
        }
    }
}

```

Thank you.

# Answer
> 0 votes
When any of the Restart, Resume, or Main Menu buttons are pressed you are not setting `this.paused` back to `false`. The menu appears the first time because `this.paused` begins as `false`. The second time the menu is opened, `this.paused` is already `true`, so it becomes `false` again at the statement:

```
this.paused = !this.paused;

```

Then your conditional `if (this.paused)` in `OnGUI` evaluates to `false` and your buttons are never drawn, until a second click when `this.paused` becomes `true` again.

In the future, you could debug problems like this by narrowing down what kind of conditions have to be satisfied to cause the problems you encounter. In this case, your buttons were not drawing, so it *must* be the case that either (or both) `isButtonVisible` or `this.paused` were `false` in `OnGUI`. Adding prints to inspect their values would have made it clear what was wrong.

---
Tags: android, unity, javascript
---


title: OpenGL - have object follow mouse

text:
# Question
Title: OpenGL - have object follow mouse
I want to have an object follow around my mouse on the screen in OpenGL. (I am also using GLEW, GLFW, and GLM). The best idea I've come up with is:

Get the coordinates within the window with glfwGetCursorPos.

The window was created with

```
window = glfwCreateWindow( 1024, 768, "Test", NULL, NULL);

```

and the code to get coordinates is

```
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);

```

Next, I use GLM unproject, to get the coordinates in "object space"

```
glm::vec4 viewport = glm::vec4(0.0f, 0.0f, 1024.0f, 768.0f);
glm::vec3 pos = glm::vec3(xpos, ypos, 0.0f);
glm::vec3 un = glm::unProject(pos, View*Model, Projection, viewport);

```

There are two potential problems I can already see. The viewport is fine, as the initial x,y, coordinates of the lower left are indeed 0,0, and it's indeed a 1024\*768 window. However, the position vector I create doesn't seem right. The Z coordinate should probably not be zero. However, glfwGetCursorPos returns 2D coordinates, and I don't know how to go from there to the 3D window coordinates, especially since I am not sure what the 3rd dimension of the window coordinates even means (since computer screens are 2D). Then, I am not sure if I am using unproject correctly. Assume the View, Model, Projection matrices are all OK. If I passed in the correct position vector in Window coordinates, does the unproject call give me the coordinates in Object coordinates? I think it does, but the documentation is not clear.

Finally, to each vertex of the object I want to follow the mouse around, I just increment the x coordinate by un\[0\], the y coordinate by -un\[1\], and the z coordinate by un\[2\]. However, since my position vector that is being unprojected is likely wrong, this is not giving good results; the object does move as my mouse moves, but it is offset quite a bit (i.e. moving the mouse a lot doesn't move the object that much, and the z coordinate is very large). I actually found that the z coordinate un\[2\] is always the same value no matter where my mouse is, probably because the position vector I pass into unproject always has a value of 0.0 for z.

Edit: The (incorrectly) unprojected x-values range from about -0.552 to 0.552, and the y-values from about -0.411 to 0.411.

# Answer
> 1 votes
**Disclaimer**: I generally don't work in 3D, so possible inaccuracies, vague details, and untested thoughts may follow.

When you say you want the object to "follow the mouse", what do you really mean? In another sense, you can interpret it like this: you want a certain point on the object to be "below" the mouse at all times. We'll call this point the "anchor point" of the object; moving the anchor point moves all the vertices of the object. How can we move this point in a way that it always lies under the mouse? To answer that, we need to take a look at the viewing frustum:

Some plane cutting the view frustum (out farther than the near view plane but closer than the far view plane) is what you'd normally think of as the screen - i.e. where the mouse would be. The exact place this plane is located is defined by your field of view. Objects are projected onto this plane and the plane is drawn onto the screen. That means, then, that the mouse lies on this plane in 3D space.

Consider this: If you were to draw a line from the camera's position to the mouse's position on the near plane, that line (extended infinitely) consists of all the points under the mouse. This implies, then, that for our anchor point to always be under the mouse, the line I just described must always intersect that point.

The problem is that the line has infinite points; where along that line should the anchor point be placed? The intuitive answer is that "the distance from the mouse to that point should always remain the same", but this is not correct; if that were true, the object would move along a sphere, and the viewing frustum is made of planes. Ah - therein lies our answer! We want the object to move along a plane, not along a circle.

So, then, we have two constraints:

1. **We want the anchor point to move along the plane which is parallel to the near/far planes and which contains the original anchor point.**
2. \**We want the anchor point to always lie on the line defined by the mouse's location in 3D space and the position of the camera. \**

And the intersection of a line and a plane is a point - the new position of the object's anchor point. Having now defined the problem more precisely, we can get a high-level algorithm:

1. Pick the anchor point `p_a` on the object.
2. On a mouse move from `p_1` to `p_2` (3D coords), do the following:
3. Get the plane `P` parallel to the near/far planes which contains `p_a`.
4. Intersect the line defined by the camera and `p1` with `P`. Call the intersection point `x_1`.
5. Intersect the line defined by the camera and `p2` with `P`. Call the intersection point `x_2`.
6. Move each vertex of the object by the vector `x_2 - x_1`.

Obviously, I've left out a whole lot of details out, such as how to get the mouse position in 3D coords (which, incidentally, is what I think `glm::unproject` is doing right now), but most of those are mathematical in nature. Hopefully this gives you enough details to go off of.

---

After sleeping and rereading the question, I see I have barely answered the original questions posed. Here is what `glm::project` does, largely paraphrased from this presentation and this question: **it takes a point on the screen and translates it into a point *on the line* underneath it**, not to where the screen would be. This is what the `Z` coordinate is passed in for; it is a real between 0.0 and 1.0 representing the plane between the near and far view planes on which the point you receive will lie. So, right now, you are obtaining the position of the mouse on the near clip plane, which is probably much closer to the camera than you would like.

In terms of my original answer, you should instead set this `Z` coordinate to wherever between the clip planes your original anchor point is. Then, the points you will receive are exactly the points you would get from manually doing steps (4) and (5).

The likely reason the `Z` coordinate is always the same is that you have your camera pointed along the Z axis (i.e. the view planes are perpendicular to that axis); then, any point a plane parallel to the near/far planes is going to have the same Z coordinate.

---
Tags: opengl, graphics, graphics-programming, glm, computational-geometry
---


# Question
Title: Is it a good plan to use 2D physics for a 3D racing game?
I am working on a 3D racing game using SDL and OpenGL. I thought it would be easier to use a 2D physics engine, since I really don't need the 3rd dimension. There will be no flying cars or jumps, they will just be stuck to the floor, so I would use 2D colliders and that things to simulate collisions in a plane but render the actual game from a 3D perspective. So the real question is: is it possible, is it a dumb idea, what else can I do?

# Answer
## Yes, it's possible.

No its not a dumb idea. In fact many of the older racing games did something similar. Super Mario Kart is one example. The rendering uses 2d sprites in 3d space instead of polygons, but the physics engine is all 2d.
> 9 votes

# Answer
It's not dumb, but realize that car/racing physics are *very* different from traditional game physics. You're not going to be able to just drop in Box2D.

Traction, handling, acceleration, braking, etc. are all going to need a good deal of special casing. It'll likely be a lot easier sticking to 2D collision handling, of course, but collision is hardly going to be the most complex thing you'll have to deal with.
> 7 votes

# Answer
It depends on what level of physics realism you are aiming for. If you're fine with a Mario-kart type of racing game, then you won't have much trouble with a 2D physics engine. But if you want a top-heavy vehicle to roll over when it goes around a sharp turn at high speed, then you will need 3D physics.
> 6 votes

---
Tags: physics, sdl, c
---


# Question
Title: Tips on how to notify a user of new features in your game
I have noticed a problem when releasing new features for a game that I wrote for Android and published on Google Play Store. Because my game is "stage-based" - and not a game like Hay Day, for example, where users will just go into the game every day since it can't really be finished - my users are not aware of new features that I release for the game.

For example, if I publish a new version of my game and it contains a couple new stages, most of their devices will just auto-update the game and they don't even notice this and think to check out what's new. So this is why an approach like popping open a dialog that showcases the new feature(s) when they open the game for the first time after the update was done is not really sufficient.

I am looking for some tips on an approach that will draw my users back into the game and then they could read more detail about new features on such a dialog. I was thinking of something like a notification that tells them to check out the new features after an update is done but I am not sure if this is a good idea. Any suggestions to help me solve this problem would be awesome.

# Answer
> 1 votes
I'm not an Android developer, but I guess you could do two things:

**Actively bring the user to your application, then inform them of the new features when they open the app.**

1. You could do this with push notifications
2. or you could also try to catch their eye by changing the app's icon (maybe adding a "new levels!" banner on it, or shorten it to "new!".

When inside the app, **keep the user motivated to play until they reach the new content**.

1. Does your game have a feature where the player has a limited number of hints? Try giving them a few "hint points" every day the open the game, scaling them the longer they chain this together. Don't break the chain completely if they don't log in though, maybe revert to the previous' day scaling (so if the fourth day they had 4xhint points, and they skip a day, turn them back to 3x, or if they skip two to 2x, and so on).
2. Is your game based on sets of levels, like Cut the Rope? You could design a set that is only unlocked if the player gets a 10x bonus (rules of the previous point apply) and plays at least one or two rounds each day.
3. Simply make the content immediately accessible, as long as it does not rely on knowledge acquired on other parts of the game not immediately available to the player (as you run the risk of them not knowing what something does simply because they were not taught). If such elements are present, you could include a simple tutorial.

Hope this helps :)

---
Tags: android, google-play
---


# Question
Title: Do I need to store a generic rotation point/radius for rotating around a point other than the origin for object transforms?
I'm having trouble implementing a non-origin point rotation. I have a class `Transform` that stores each component separately in three 3D vectors for `position`, `scale`, and `rotation`. This is fine for local rotations based on the center of the object.

The issue is how do I determine/concatenate non-origin rotations *in addition to* origin rotations. Normally this would be achieved as a Transform-Rotate-Transform for the center rotation followed by a Transform-Rotate-Transform for the non-origin point.

The problem is because I am storing the individual components, the final Transform matrix is not calculated until needed by using the individual components to fill an appropriate Matrix. (See `GetLocalTransform()`)

Do I need to store an additional rotation (and radius) for world rotations as well or is there a method of implementation that works while only using the single rotation value?

**Transform.h**

```
#ifndef A2DE_CTRANSFORM_H
#define A2DE_CTRANSFORM_H

#include "../a2de_vals.h"
#include "CMatrix4x4.h"
#include "CVector3D.h"

#include <vector>

A2DE_BEGIN

class Transform {
public:

    Transform();
    Transform(Transform* parent);
    Transform(const Transform& other);
    Transform& operator=(const Transform& rhs);
    virtual ~Transform();

    void SetParent(Transform* parent);
    void AddChild(Transform* child);
    void RemoveChild(Transform* child);

    Transform* FirstChild();
    Transform* LastChild();
    Transform* NextChild();
    Transform* PreviousChild();
    Transform* GetChild(std::size_t index);

    std::size_t GetChildCount() const;
    std::size_t GetChildCount();

    void SetPosition(const a2de::Vector3D& position);
    const a2de::Vector3D& GetPosition() const;
    a2de::Vector3D& GetPosition();

    void SetRotation(const a2de::Vector3D& rotation);
    const a2de::Vector3D& GetRotation() const;
    a2de::Vector3D& GetRotation();

    void SetScale(const a2de::Vector3D& scale);
    const a2de::Vector3D& GetScale() const;
    a2de::Vector3D& GetScale();

    a2de::Matrix4x4 GetLocalTransform() const;
    a2de::Matrix4x4 GetLocalTransform();

protected:

private:
    a2de::Vector3D _position;
    a2de::Vector3D _scale;
    a2de::Vector3D _rotation;
    std::size_t _curChildIndex;
    Transform* _parent;
    std::vector<Transform*> _children;
};

A2DE_END

#endif

```

**Transform.cpp**

```
#include "CTransform.h"

#include "CVector2D.h"
#include "CVector4D.h"

A2DE_BEGIN

Transform::Transform() :
_position(),
_scale(1.0, 1.0),
_rotation(),
_curChildIndex(0),
_parent(nullptr),
_children()
{
    /* DO NOTHING */
}

Transform::Transform(Transform* parent) :
_position(),
_scale(1.0, 1.0),
_rotation(),
_curChildIndex(0),
_parent(parent),
_children()
{
    /* DO NOTHING */
}

Transform::Transform(const Transform& other) :
_position(other._position),
_scale(other._scale),
_rotation(other._rotation),
_curChildIndex(0),
_parent(other._parent),
_children(other._children)
{
    /* DO NOTHING */
}

Transform& Transform::operator=(const Transform& rhs) {
    if(this == &rhs) return *this;

    this->_position = rhs._position;
    this->_scale = rhs._scale;
    this->_rotation = rhs._rotation;
    this->_curChildIndex = 0;
    this->_parent = rhs._parent;
    this->_children = rhs._children;

    return *this;
}

Transform::~Transform() {
    _children.clear();
    _parent = nullptr;
}

void Transform::SetParent(Transform* parent) {
    _parent = parent;
}

void Transform::AddChild(Transform* child) {
    if(child == nullptr) return;
    _children.push_back(child);
}

void Transform::RemoveChild(Transform* child) {
    if(_children.empty()) return;
    _children.erase(std::remove(_children.begin(), _children.end(), child), _children.end());
}

Transform* Transform::FirstChild() {
    if(_children.empty()) return nullptr;
    return *(_children.begin());
}

Transform* Transform::LastChild() {
    if(_children.empty()) return nullptr;
    return *(_children.end());
}

Transform* Transform::NextChild() {
    if(_children.empty()) return nullptr;
    std::size_t s(_children.size());
    if(_curChildIndex >= s) {
        _curChildIndex = s;
        return nullptr;
    }
    return _children[_curChildIndex++];
}

Transform* Transform::PreviousChild() {
    if(_children.empty()) return nullptr;
    if(_curChildIndex == 0) {
        return nullptr;
    }
    return _children[_curChildIndex--];
}

Transform* Transform::GetChild(std::size_t index) {
    if(_children.empty()) return nullptr;
    if(index > _children.size()) return nullptr;
    return _children[index];
}

std::size_t Transform::GetChildCount() const {
    if(_children.empty()) return 0;
    return _children.size();
}

std::size_t Transform::GetChildCount() {
    return static_cast<const Transform&>(*this).GetChildCount();
}

void Transform::SetPosition(const a2de::Vector3D& position) {
    _position = position;
}

const a2de::Vector3D& Transform::GetPosition() const {
    return _position;
}

a2de::Vector3D& Transform::GetPosition() {
    return const_cast<a2de::Vector3D&>(static_cast<const Transform&>(*this).GetPosition());
}

void Transform::SetRotation(const a2de::Vector3D& rotation) {
    _rotation = rotation;
}

const a2de::Vector3D& Transform::GetRotation() const {
    return _rotation;
}

a2de::Vector3D& Transform::GetRotation() {
    return const_cast<a2de::Vector3D&>(static_cast<const Transform&>(*this).GetRotation());
}

void Transform::SetScale(const a2de::Vector3D& scale) {
    _scale = scale;
}

const a2de::Vector3D& Transform::GetScale() const {
    return _scale;
}

a2de::Vector3D& Transform::GetScale() {
    return const_cast<a2de::Vector3D&>(static_cast<const Transform&>(*this).GetScale());
}

a2de::Matrix4x4 Transform::GetLocalTransform() const {
    Matrix4x4 p((_parent ? _parent->GetLocalTransform() : a2de::Matrix4x4::GetIdentity()));
    Matrix4x4 t(a2de::Matrix4x4::GetTranslationMatrix(_position));
    Matrix4x4 r(a2de::Matrix4x4::GetRotationMatrix(_rotation));
    Matrix4x4 s(a2de::Matrix4x4::GetScaleMatrix(_scale));

    return (p * t * r * s);
}

a2de::Matrix4x4 Transform::GetLocalTransform() {
    return static_cast<const Transform&>(*this).GetLocalTransform();
}

A2DE_END

```

# Answer
I would avoid using a 3D vector to represent the transform's orientation. The problem with this is that you loose a dimension of rotation and thus cannot represent all possible orientations with such a vector.

Suppose the reference vector from which rotations are measured is the forward vector (0, 0, 1). Now suppose you want to rotate the transform by an angle of θ radians about the positive z-axis. The resulting orientation vector will be the same forward vector (0, 0, 1) regardless of the value of θ. We need an extra dimension to fully express a rotation in 3D space.

In summary, you should probably store your transform's rotation as either a Quaternion or 4x4 matrix. Suppose the transform has a unit quaternion, `transform.rotation`, representing the rotation of the transform from the reference forward vector.

Rotating the transform by a unit quaternion `q` is as simple as (where the symbol `*` is the Hamilton product):

```
transform.rotation = q * transform.rotation

```

Now on your specific question...

*I should warn that mixing origin and non-origin rotations will complicate your transform class. Using only local origin rotations allows your transformation matrix to be calculated directly from the transform's individual properties (position, rotation and scale). However, if you use non-origin rotations (or both), you will need to decompose the position, rotation and scale properties from the transformation matrix.*

You will notice that I did not specify about which point the above operation rotates the transform. This is because that is yet to be determined. It is in fact determined when you multiply together translation, rotation and scaling matrices. Note that you will need to convert the quaternion to a 4x4 matrix before you do this if you are using quaternions.

The order of multiplication to rotate about the transform's local origin is `rotation * translation` for column-major matrices. You first rotate the transform at the world origin and then translate out to its world position. This results in spinning.

The order of multiplication to rotate about the world origin is `translation * rotation` for column-major matrices. You first translate the transform out to its position and then rotate it about the world origin. This results in orbiting.

To rotate about a point `p` first construct the translation matrix `T1` that translates from the world origin to the point `p`. Now construct the rotation matrix, `R`. Finally construct the translation matrix `T2` that translates from the point `p` to the transform's position. The order in which you multiply these matrices depends on whether your matrix is row-major or column-major. For column-major order, it is `T1 * R * T2`. Reverse the order of multiplication if you are using row-major matrices.

To concatenate non-origin rotations with origin rotations you simply multiply the two resulting transformation matrices together. Again, the order depends on whether you are using column-major or row-major matrices.
> 2 votes

# Answer
The rotation works like this:

First do Local Transforms.

Then if you want to rotate in a arbitary point, just figure out the distance from:

WorldObject to RotationPoint,

Then translate the Object by that distance and perform a rotation this will rotate it By the Origin (0,0,0) since we are translated we will rotate in a Circle.

After that Transform by the world Coordinates and you will have your object this will have your objects Rotated across that point.
> 0 votes

---
Tags: c++, rotation, transformation
---


# Question
Title: Extrapolation breaks collision detection
Before applying extrapolation to my sprite's movement, my collision worked perfectly. However, after applying extrapolation to my sprite's movement (to smooth things out), the collision no longer works.

**This is how things worked before extrapolation:**

However, after I implement my extrapolation, the collision routine breaks. I am assuming this is because it is acting upon the new coordinate that has been produced by the extrapolation routine (which is situated in my render call ).

**After I apply my extrapolation**

**How to correct this behaviour?**

I've tried puting an extra collision check just after extrapolation - this does seem to clear up a lot of the problems but I've ruled this out because putting logic into my rendering is out of the question.

I've also tried making a copy of the spritesX position, extrapolating that and drawing using that rather than the original, thus leaving the original intact for the logic to pick up on - this seems a better option, but it still produces some weird effects when colliding with walls. I'm pretty sure this also isn't the correct way to deal with this.

I've found a couple of similar questions on here but the answers haven't helped me.

**This is my extrapolation code:**

```
public void onDrawFrame(GL10 gl) {

        //Set/Re-set loop back to 0 to start counting again
        loops=0;

        while(System.currentTimeMillis() > nextGameTick && loops < maxFrameskip){

        SceneManager.getInstance().getCurrentScene().updateLogic();
        nextGameTick+=skipTicks;
        timeCorrection += (1000d/ticksPerSecond) % 1;
        nextGameTick+=timeCorrection;
        timeCorrection %=1;
        loops++;
        tics++;

     }

        extrapolation = (float)(System.currentTimeMillis() + skipTicks - nextGameTick) / (float)skipTicks;

        render(extrapolation);
}

```

**Applying extrapolation**

```
            render(float extrapolation){

            //This example shows extrapolation for X axis only.  Y position (spriteScreenY is assumed to be valid)
            extrapolatedPosX = spriteGridX+(SpriteXVelocity*dt)*extrapolation;
            spriteScreenPosX = extrapolationPosX * screenWidth;

            drawSprite(spriteScreenX, spriteScreenY);

        }

```

**Edit**

As I mentioned above, I have tried making a copy of the sprite's coordinates specifically to draw with.... this has it's own problems.

Firstly, regardless of the copying, when the sprite is moving, it's super-smooth, when it stops, it's wobbling slightly left/right - as it's still extrapolating it's position based on the time. Is this normal behavior and can we 'turn it off' when the sprite stops?

I've tried having flags for left / right and only extrapolating if either of these is enabled. I've also tried copying the last and current positions to see if there is any difference. However, as far as collision goes, these don't help.

If the user is pressing say, the right button and the sprite is moving right, when it hits a wall, if the user continues to hold the right button down, the sprite will keep animating to the right, while being stopped by the wall (therefore not actually moving), however because the right flag is still set and also because the collision routine is constantly moving the sprite out of the wall, it still appear to the code (not the player) that the sprite is still moving, and therefore extrapolation continues. So what the player would see, is the sprite 'static' (yes, it's animating, but it's not actually moving across the screen), and every now and then it shakes violently as the extrapolation attempts to do it's thing....... Hope this help

# Answer
> 1 votes
I can't post a comment yet, so I will post this as an answer.

If I understand the problem correctly, it goes something like this:

1. first you have a collision
2. then the object's position is corrected (presumably by the collision detection routine)
3. the object's updated position is sent to the render function
4. the render function then updates the object's location using extrapolation
5. the position of the extrapolated object now breaks the collision detection routine

I can think of 3 possible solutions. I will list them in the order that is most desirable to least IMHO.

1. Move the extrapolation out of the render function. Extrapolate the object's position and then test for a collision.
2. or if you want keep the extrapolation in the render function, set a flag to denote a collision had happened. Have the collision detection correct the object's position as you already do, but before you calculate the extrapolation value check the collision flag first. Since the object is already where it needs to be, there is no need to move it.
3. The last possibility, which to me is more of a work-around than a fix would be to overcompensate with the collision detection. After a collision, move the object away from the wall, so that after extrapolation the object is back at the wall.

Example code for #2.

```
if (collisionHasOccured)
    extrpolation = 0.0f;
else
    extrapolation = (float)(System.currentTimeMillis() + skipTicks - nextGameTick) / (float)skipTicks;

```

I think #2 would probably be the quickest and easiest to get up an running, although #1 seems to be a more logically accurate solution. Depending on how you handle your delta time solution #1 could be broken in much the same way by a large delta, in which case you might have to use both #1 and #2 together.

EDIT: I misunderstood your code earlier. The loops is meant to render as fast as possible and update at a set interval. This is why you would be interpolating the sprite position, to handle the case where you are drawing more than updating. However, if the loop falls behind, then you poll on updating until you are caught up or you skipped the max number of frame draws.

That being said, the only problem is that the object is moving after a collision. If there is a collision the object should stop moving in that direction. So, if there is a collision, then set it's speed to 0. This should stop the render function from moving the object any further.

# Answer
> 0 votes
It looks like you need to separate rendering and updating of physics entirely. Usually the underlying simulation will run at discrete time-steps, and the frequency will never change. For example, you could simulate the movement of your ball every 1/60th of a second, and that's it.

In order to allow for a variable framerate the rendering code should operate on a variable frequency, but any simulation should still be at a fixed time-step. This lets the graphics read memory from the simulation as read-only, and lets you set up interpolation instead of extrapolation.

Since extrapolation is trying to predict where future values are going to be, sudden changes in movement can give you huge extrapolation errors. It is better to instead render your scene about a frame behind simulation and interpolate between discrete known positions.

If you want to see some details of implementation I've already written a short section about this topic in an article here. Please see the section called "Timestepping".

Here's the important psuedo code from the article:

```
const float fps = 100
const float dt = 1 / fps
float accumulator = 0

// In units seconds
float frameStart = GetCurrentTime( )

// main loop
while(true)
  const float currentTime = GetCurrentTime( )

  // Store the time elapsed since the last frame began
  accumulator += currentTime - frameStart( )

  // Record the starting of this frame
  frameStart = currentTime

  // Avoid spiral of death and clamp dt, thus clamping
  // how many times the UpdatePhysics can be called in
  // a single game loop.
  if(accumulator > 0.2f)
    accumulator = 0.2f

  while(accumulator > dt)
    UpdatePhysics( dt )
    accumulator -= dt

  const float alpha = accumulator / dt;

  RenderGame( alpha )

void RenderGame( float alpha )
  for shape in game do
    // calculate an interpolated transform for rendering
    Transform i = shape.previous * alpha + shape.current * (1.0f - alpha)
    shape.previous = shape.current
    shape.Render( i )

```

The `RenderGame` function is of most interest. The idea is to use interpolation between discrete simulation positions. The rendering code can make it's own copies of the simulation read-only data, and use a temporary interpolated value to render. This will give you very smooth movement without any silly issues like what you seem to be having!

---
Tags: android, collision-detection, interpolation, movement-prediction, extrapolation
---


title: 2D Boxes/Vertices merging

text:
# Question
Title: 2D Boxes/Vertices merging
I want to optimize my colliders geometry, at the moment is composed by boxes (it's a tile based game) of the same dimensions, i want to remove the inner vertices to have, at the end, only the shell. Does anyone knows or can point me out to the right direction/algorithm? The only way I can think about it's some kind of region growing with coordinates updating in a recursive way.

# Answer
> 1 votes
Since you're using a tile based game this may not be necessary at all. In general a tile is just an array of values. Each value can represent a different type of geometry to collide with, and in your case it looks like (judging by the picture) you only have AABBs of uniform size. If this is the case then you shouldn't have any floating point vertices at all! Collision with the grid involves truncating a floating point coordinate to see which grid cell it lays within.

---

This section only applies if you actually create individual AABBs from your tiles.

Since you're using a grid like this you can definitely create an algorithm to join multiple cells into a single AABB. The idea would be to, as a pre-processing step, use a simple algorithm in the likes of flood filling to find the biggest AABB you can that groups a lot of tiles together. Since this would be a pre-processing step and does not actually run in your release code, it can be a pretty naive algorithm and you move on to develop other interesting features of your game:

```
store a zero volume AABB called max

for each cell
  create AABB around cell
  visit all neighbors on the top of the AABB and expand if possible
  repeat last line for the right, left and bottom of the AABB
  if this AABB is greater than max, max = this AABB

```

If you're familiar with with the idea of a searching a graph with a depth first search (DFS), the idea could be to search all possible expansions for each grid cell and choose the one that eats up the most volume at any given step.

What you'd be implementing here is a type of *approximate convex decomposition*, and this topic can get very involved. Since you're only dealing with AABBs you can make very simple algorithms that get the job done, but if you want to you can do something more complicated... But I don't recommend this.

---
Tags: 2d, tiles, optimization, vertex
---