# Question
Title: EXTREMELY Confused Over "Constant Game Speed Maximum FPS" Game Loop
I recently read this article on Game Loops: http://www.koonsolo.com/news/dewitters-gameloop/

And the recommended last implementation is confusing me deeply. I don't understand how it works, and it looks like a complete mess.

I understand the principle: Update the game at a constant speed, with whatever is left render the game as many times as possible.

I take it you cannot use a:

* Get input for 25 ticks
* Render game for 975 ticks

Approach since you would be getting input for the first portion of the second and this would feel weird? Or is that what is going on in the article?

---

**Essentially:**

```
while( GetTickCount() > next_game_tick && loops < MAX_FRAMESKIP)

```

How is that even valid?

Let's assume his values.

```
MAX_FRAMESKIP = 5

```

Let's assume next\_game\_tick, which was assigned moments after initialization, before the main game loop is say... 500.

Finally, as I am using SDL and OpenGL for my game, with OpenGL being used for rendering only, let's assume that `GetTickCount()` returns the time since SDL\_Init was called, which it does.

```
SDL_GetTicks -- Get the number of milliseconds since the SDL library initialization.

```

*Source: http://www.libsdl.org/docs/html/sdlgetticks.html*

The author also assumes this:

```
DWORD next_game_tick = GetTickCount();
// GetTickCount() returns the current number of milliseconds
// that have elapsed since the system was started

```

**If we expand the `while` statement we get:**

```
while( ( 750 > 500 ) && ( 0 < 5 ) )

```

750 because time has passed since `next_game_tick` was assigned. `loops` is zero as you can see in the article.

So we have entered the while loop, let's do some logic and accept some input.

Yadayadayada.

**At the end of the while loop, which I remind you is inside our main game loop is:**

```
next_game_tick += SKIP_TICKS;
loops++;

```

Let's update what the next iteration of the while code looks like

```
while( ( 1000 > 540 ) && ( 1 < 5 ) )

```

**1000** because time has elapsed getting input and doing stuff before we reached the next ineteration of the loop, where GetTickCount() is recalled.

**540** because, in the code 1000 / 25 = 40, therefore, 500 + 40 = 540

**1** because our loop has iterated once

**5**, you know why.

---

So, since this While loop is CLEARLY depedent on `MAX_FRAMESKIP` and not the intended `TICKS_PER_SECOND = 25;` how is the game supposed to even run correctly?

It was no surprise to me that when I implemented this into my code, correctly I might add as I simply renamed my functions to handle user input and draw the game to what the author of the article has in his example code, the game did nothing.

I placed an `fprintf( stderr, "Test\n" );` inside the while loop which doesn't get printed until the game ends.

**How is this game loop running 25 times a second, guaranteed, while rendering as fast as it can?**

To me, unless I am missing something HUGE, it looks like... nothing.

And isn't this structure, of this while loop, supposedly running 25 times a second and then updating the game exactly what I mentioned beforehand at the start of the article?

If that is the case why couldn't we do something simple like:

```
while( loops < 25 )
{
    getInput();
    performLogic();

    loops++;
}

drawGame();

```

And count for interpolation some other way.

Forgive my extremely long question, but this article has done more harm than good to me. I am severely confused now - and have no idea how to implement a proper game loop because of all these arisen questions.

# Answer
> 9 votes
I think the author made a tiny error:

`while( GetTickCount() > next_game_tick && loops < MAX_FRAMESKIP)`

should be

`while( GetTickCount() < next_game_tick && loops < MAX_FRAMESKIP)`

That is: as long as it is not yet time to draw our next frame and while we have not skipped as much frames as MAX\_FRAMESKIP we should wait.

I also don't understand why he updates `next_game_tick` in the loop and I assume it is another error. Since at the start of a frame you can determine when the next frame should be (when using a fixed frame rate). The `next game tick` does not depend on how much time we have left over after updating and rendering.

The author also makes another common error

> with whatever is left render the game as many times as possible.

This means rendering the same frame multiple times. The author is even aware of that:

> The game will be updated at a steady 50 times per second, and rendering is done as fast as possible. Remark that when rendering is done more than 50 times per second, some subsequent frames will be the same, so actual visual frames will be displayed at a maximum of 50 frames per second.

This only causes the GPU to do unnecessary work and if rendering takes longer than expected it could cause you to start working on your next frame later than intended so it is better to yield to the OS and wait.

# Answer
> 4 votes
Maybe best if I simplify it a bit:

```
while( game_is_running ) {

    current = GetTickCount();
    while(current > next_game_tick) {
        update_game();

        next_game_tick += SKIP_TICKS;
    }
    display_game();
}

```

`while` loop inside mainloop is used to run simulation steps from where ever it was, to where it should be now. `update_game()` function should always assume that only `SKIP_TICKS` amount of time has passed since last call. This will keep game physics running at constant speed on slow and fast hardware.

Incrementing `next_game_tick` by amount of `SKIP_TICKS` moves it closer to current time. When this gets bigger than current time is, it breaks (`current > next_game_tick`) and mainloop continues to render current frame.

After rendering, next call to `GetTickCount()` would return new current time. If this time is higher than `next_game_tick` it means that we are already behind 1-N steps in simulation and we should catch up, running every step in simulation at same constant speed. In this case if it is lower, it would just render same frame again (unless there is interpolation).

Original code had limited the number of loops if we are left too far away (`MAX_FRAMESKIP`). This only makes it actually show something and not looking like being locked up if for example resuming from suspend or game being paused in debugger for long time (assuming `GetTickCount()` does not stop during that time) until it has catched up with time.

To get rid of useless same frame rendering if you are not using interpolation inside `display_game()`, you could wrap it inside if statement like:

```
while (game_is_running) {
    current = GetTickCount();
    if (current > next_game_tick) {
        while(current > next_game_tick) {
            update_game();

            next_game_tick += SKIP_TICKS;
        }
    display_game();
    }
    else {
    // could even sleep here
    }
}

```

This is also a good article about this: http://gafferongames.com/game-physics/fix-your-timestep/

Also, maybe reason why your `fprintf` outputs when your game ends might just be that it did not get flushed.

Sorry about my english.

# Answer
> 4 votes
His code looks entirely valid.

Consider the `while` loop of the last set:

```
// JS / pseudocode
var current_time = function () { return Date.now(); }, // in ms
    framerate = 1000/30, // 30fps
    next_frame = current_time(),

    max_updates_per_draw = 5,

    iterations;

while (game_running) {

    iterations = 0;

    while (current_time() > next_frame && iterations < max_updates_per_draw) {
        update_game(); // input, physics, audio, etc

        next_frame += framerate;
        iterations += 1;
    }

    draw();
}

```

I've got a system in place which says "while the game is running, check the current time - if it's greater than our running framerate tally, and we've skipped drawing fewer than 5 frames, then skip drawing and just update input and physics: else draw the scene and start the next update iteration"

When each update happens, you increment the "next\_frame" time by your ideal framerate. Then you check your time again. If your current time is now less than when the next\_frame should be updated, then you skip over the update and draw what you've got.

If your current\_time is greater (imagine that the last draw process took a really long time, because there was some hiccup somewhere, or a bunch of garbage-collection in a managed language, or a managed-memory implementation in C++ or whatever), then draw gets skipped and the `next_frame` gets updated with *another* extra frame worth of time, until either the updates catch up to where we should be on the clock, or we've skipped drawing enough frames that we absolutely MUST draw one, so the player can see what they're doing.

If your machine is super-fast or your game is super-simple, then `current_time` might be less than `next_frame` frequently, which means that you are not updating during those points.

That's where the interpolation comes in. Likewise, you could have a separate bool, declared outside of the loops, to declare "dirty" space.

Inside of the update loop, you'd set `dirty = true`, signifying that you've actually performed an update.

Then, instead of just calling `draw()`, you'd say:

```
if (is_dirty) {
    draw();
    is_dirty = false;
}

```

Then you're missing out on any interpolation for smooth motion, but you're ensuring that you're only updating when you've got updates actually happening (rather than interpolations between states).

If you're brave, there's an article called "Fix Your Timestep!" by GafferOnGames.
It approaches the problem slightly differently, but I consider it a prettier solution which does mostly the same thing (depending on your language's features, and how much you care about your game's physics calculations).

---
Tags: architecture, game-loop
---


# Question
Title: XNA seams between 3d primitives in tiled terrain
Every time I draw two primitives side by side, in this case two quads, I always get this seam-like tearing effect right along the sides of them. I'd like to think there is just an easy fix, but the only way I can think of would be reworking my indices, which I think would compromise my ability to draw textures. If anyone reading this can think of any fix, that would be great. Thanks in advance.

# Answer
There's two ways you can fix this.

1. You can apply a half pixel offset to the corners, to make sure you have UVs that point to the center of a texel.
2. You can change your sampling mode to POINT sampling, for Mag, Min, Mip, AddressU and AddressV sampler states, like "untitled" mentioned.
> 3 votes

# Answer
That looks more like a graphical artifact stemming from the texture that you are applying. It would be good if you gave some more information about how you are defining the quads, what vertex structure you are using and what effect you are using to render the quads.
> 0 votes

# Answer
If you're using a texture atlas, What sampler states are you using? Try using magfilter = POINT, minfilter = POINT, mipfilter = POINT, AddressU = WRAP, AddressV = WRAP
> 0 votes

---
Tags: xna, 3d, tiles, terrain
---


title: Jump function of player

text:
# Question
Title: Jump function of player
I'm developing game in marmalade sdk in c++. I have player in the area.and I wanna make him jump when i pressed a button.When I use this player.moveUp(5px); it just go up 5px, but he has to fall down back. so that when i use these: player.moveUp(5px); and player.movedown(5px); it do nothing.Because the fps is 30 and it's performing so fast. how i can fix that?

# Answer
> 1 votes
Jumping is an operation that you need to have take effect over time, not an instantaneous modification to the player location. To make a realistic jump, you're going to want to take into account:

* Velocity
* Gravity (an acceleration downward)
* Time
* Player height (i.e., y coordinate)

The relationship between these will be something like this:

> pos\_y = pos\_y + (velocity\_y * time\_difference) + (gravity\_y * (time\_difference ^ 2) / 2) velocity\_y = velocity\_y + (acceleration\_y * time\_difference)

(That formula is taken from an answer on impulsed jumping.)

The gravity is a constant acceleration downard, which is constantly modifying the velocity. So the velocity starts out going up, and gets pulled progressively downward. The change in time (delta) is used to determine how far along the process we are.

---
Tags: c++, mathematics, physics, marmalade
---


# Question
Title: RPG game engine. Skill application calculations
# Short preface

I am a part of a small team which is entering game development. We're creating a new RPG setting with custom game system and mechanics based on dice rolls. I'm server-side java programmer, so the game engine is my responsibility.

# The problem

I have a problem designing talent classes. Each character may have a set of talents. The problem is, most talents are unique and different from others. For example:
Talent **Season fever** gives character a stat bonus depending on the season of the year, e.g. strength +2 in Winter, dexterity +2 in Spring, etc. Which gives player an opportunity to add and swap talents because of changed stats four times a year.
Talent **Fortune Wheel** allows a player to roll d6 each morning and get a bonus on one of the six stats (strength, dexterity, etc.) for that day.
Talent **Attuned to partner** gives a player +2 on his hit roll if his character has exactly one partner in the battle. If his partner also has this talent, both of them get +4 instead. As you see mechanics of each talent are different. Question is how to universally implement all this different functionalities in Java classes.

# Some technical details

I use latest version of JDK 7.
Springframework stack (spring-data, spring-mvc, spring-security, etc.)
MongoDB for persistent storage.

# My ideas

The solution I came up with:

* Create a parent Talent class with generic fields and methods, like id, name, description, requirements to obtain, etc. and an abstract `apply()` method.
* For each talent in the game extend Talent class and add custom logic by implementing the `apply()` method.
* I also need some trigger mechanism (I don't really know how it would look, so please advise if you have ideas). For example, if character has some talent which gives him bonus to a melee attack in some situations (preconditions) the trigger would fire on each event of melee attack made by the player, when the trigger fires it also checks if preconditions are met and if they are it calls the `apply()` method of a talent.
* I have to implement scheduling for triggering or processing talents which depend on times or periods like the **Season fever** talent described above.

***Disclaimer** I have really small experience of asking questions on stack-exchange, so feel free to point out suggestions on question format and additional info required. Also, English is not my native language, so feel free to correct me if something annoys you (grammar-nazi style)*

# Answer
> 1 votes
What CamFred said in his comments is sensible. If you want more suggestions, here's one.

Use an observer/observable pattern. Make the Talent class an Observer, and the character an Observable. Now, adding a Talent to a character is simply a matter of adding an observer. Whenever something happens that *might* trigger an event, you notify the observers, and *they* decide whether anything happens.

This is really easy to do in Java - it actually has built-in Observer- and Observable-classes that you can extend. Anyway, here's the Wikipedia page \- there's even a Java example.

---
Tags: java, game-design, game-mechanics, rpg, data-structure
---


title: culling lines on the back of a globe

text:
# Question
Title: culling lines on the back of a globe
I am drawing a simple outline of the world using GL\_LINE\_STRIPs (in WebGL).

I want to not draw those lines that are on the other side of the spinning globe.

Using Nicol Bolas approach below I am trying to determine if a point is going away from the camera or not:

```
scene.map = {
    vbo: gl.createBuffer(),
    draw: function(pMatrix,mvMatrix,camera,t) {
        gl.useProgram(this.program);
        gl.uniformMatrix4fv(this.program.pMatrix,false,pMatrix);
        var spin = mat4_rotation(t,[0,1,0]);
        mvMatrix = mat4_multiply(mvMatrix,spin);
        gl.uniformMatrix4fv(this.program.mvMatrix,false,mvMatrix);
        var nMatrix = mat4_inverse(mat4_transpose(mvMatrix));
        gl.uniformMatrix4fv(this.program.nMatrix,false,nMatrix);
        gl.uniform3fv(this.program.camera,camera);
        gl.uniform4fv(this.program.colour,[0,1,0,1]);
        gl.enableVertexAttribArray(this.program.vertex);
        gl.bindBuffer(gl.ARRAY_BUFFER,this.vbo);
        gl.vertexAttribPointer(this.program.vertex,3,gl.FLOAT,false,3*4,0);
        var ofs = 0, parts = this.data.ofs;
        for(var part=0; part<parts.length; part++) {
            var start = ofs;
            ofs += parts[part];
            gl.drawArrays(gl.LINE_STRIP,start,ofs-start);
        }
        gl.disableVertexAttribArray(this.program.vertex);
        gl.bindBuffer(gl.ARRAY_BUFFER,null);
        gl.useProgram(null);
    },
    program: createProgram("precision mediump float;\n"+
            "attribute vec3 vertex;\n"+
            "uniform mat4 pMatrix, mvMatrix, nMatrix;\n"+
            "varying vec3 n;\n"+
            "void main() {\n"+
            "   gl_Position = pMatrix * mvMatrix * vec4(vertex,1.0);\n"+
            "   n = (nMatrix * vec4(vertex,1.0)).xyz;\n"+
            "}\n",
            "precision mediump float;\n"+
            "uniform vec4 colour;\n"+
            "uniform vec3 camera;\n"+
            "varying vec3 n;\n"+
            "void main() {\n"+
            "   if(dot(camera,n) < 0.0) discard;\n"+
            "   gl_FragColor = colour;\n"+
            "}\n",
            ["pMatrix","mvMatrix","colour","camera","nMatrix"],
            ["vertex"]),
    data: getFile("json","data/world.json"),
};
var pts = [], deg2rad = Math.PI/180;
for(var i=0; i<scene.map.data.pts.length; i+=2) {
    var lng = scene.map.data.pts[i] * deg2rad,
        lat = scene.map.data.pts[i+1] * deg2rad;
    pts.push(-Math.cos(lat)*Math.cos(lng),Math.sin(lat),Math.cos(lat)*Math.sin(lng));
}
pts.push(0,0,0); // centre of sphere, for sprite z-culling trick
gl.bindBuffer(gl.ARRAY_BUFFER,scene.map.vbo);
gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(pts),gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER,null);

```

and to draw it:

```
var pMatrix = createPerspective(60,canvas.width/canvas.height,0.1,4),
    eye = [-2,0,0],
    mvMatrix = createLookAt(eye,[0,0,0],[0,1,0]);
scene.map.draw(pMatrix,mvMatrix,eye,t);

```

However, this is only drawing the left hemisphere rather than the front:

How can I correctly compute the normal of a point, and the position of the camera?

# Answer
You can't compute the "Z" of this plane because the plane *has no Z*. If the sphere is not directly in front of the camera, the plane will be tilted relative to the camera. So there isn't a single Z coordinate that will work.

If you were using desktop OpenGL, I would suggest that you compute the plane equation and employ user-defined clip-planes. But that's not available in ES 2.0.

So the only answer that's left is to compute the dot-product between the view direction and the normal at that point. So your vertex shader is going to have to calculate the normal (in camera-space), pass it to the fragment shader, and let the fragment shader do the dot product. If the normal is negative, discard the fragment.

Computing the normal is a bit tricky. See, it's easy to compute it in model space, assuming your planet data set is centered at the origin in model space. You simply normalize the position of the vertex, since the vertex position in model space is a point on the sphere. The problem is transforming that into camera space.

If you can guarantee that `mvMatrix` does not have any non-uniform scaling applied, then you can simply use that. But otherwise, you need to use the inverse-transpose of the model-view matrix. So you'd need to compute that and pass it to your vertex shader.

---

As to the code you posted, the camera in camera space is at the *origin*. That's why it's called "camera space". You don't need to pass it to the shader.

Also, the dot product is between the direction from the camera to the fragment. So you need to compute that. It isn't something you can pass to the fragment shader. You either need to send the camera-space position as a per-vertex varying, or you need to reverse-transform `gl_FragCoord` to get the camera-space position.
> 2 votes

---
Tags: opengl-es
---


title: How to debug Direct3D resource leak?

text:
# Question
Title: How to debug Direct3D resource leak?
When I close my application, I get the following errors in the Direct3D Debug output:

```
Direct3D9: (INFO) :MemFini!
Direct3D9: (ERROR) :Memory still allocated!  Alloc count = 20
Direct3D9: (ERROR) :Current Process (pid) = 0000162c
Direct3D9: (ERROR) :Memory Address: 05fb7d0c lAllocID=50 dwSize=000170d8, ReturnAddr=0615e508 (pid=0000162c)
Direct3D9: (ERROR) :Memory Address: 08c86594 lAllocID=1046 dwSize=00004bc4, ReturnAddr=0614d5ea (pid=0000162c)
(...)
Direct3D9: (ERROR) :Memory Address: 08d0c31c lAllocID=1471 dwSize=00001a40, ReturnAddr=0615e784 (pid=0000162c)
Direct3D9: (ERROR) :Total Memory Unfreed From Current Process = 258932 bytes

```

I've carefully looked over my code and the one thing I found suspect was a texture and a surface I got from the texture. I realised that surface-\>Release() wasn't returning 0, which means, I believe, that someone else still has a reference to it. So just to try something, I released it several times in a while loop until it returned 0. Direct3D then returned the following error:

```
Direct3D9: (ERROR) :A level of a mip-map has been released more often than it has been add-ref'ed! Danger!!

```

I don't get it. That surface is somehow referenced more than once but hasn't been "add-refed" more than once? How can I debug who is holding a reference to it?

Thanks.

# Answer
In my experience, the most likely causes of resource leaks are:

* Failing to call OnLostDevice for any D3DX objects you use (and that implement OnLostDevice) - Effect and Sprite are common criminals here as they will AddRef a texture that they use (to ensure that the texture isn't destroyed while they may still be using it); I *believe* that this shouldn't be necessary during shutdown, however, but if it sounds like something you may have then it's no harm doing it.
* Failing to call Release for each call to GetSurfaceLevel you make. GetSurfaceLevel will increment the reference count on the returned surface, so not Releasing it will cause the leak.
* Failing to call Release for each call to GetRenderTarget or GetBackBuffer you make; likewise increments the reference count on the returned surface (as a general rule, any D3D Get\* call that returns an interface must have a Release call on the returned interface, otherwise it will leak.)

The last two seem probable in your case, so your first step in debugging is to make sure that your code respects this rule; a quick find-in-files for `"->Get"` should help you easily identify anything of this nature you may have.

Once you've checked this out, and if you're still leaking, post back and we'll see what the next steps are.
> 3 votes

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


title: Canvas background from sprite (HTML5)

text:
# Question
Title: Canvas background from sprite (HTML5)
I am starting to develop my fist bigger game in HTML5 and struggling a bit with sprites. I can cut out single items, but I need to repeat them as well. For example, I have a battle ground that consists of grass, dirt path, building and a pond. I have all these in one sprite. But what I really need is to cut out the grass and repeat is as background on whole canvas.

I cannot believe that this wouldn't be possible, using sprites would loose almost completely point there... (apart from single static items of course).

I would appreciate if someone would have solution to this.

# Answer
> 1 votes
You're looking to use an HTML5 pattern - this is documented several places around the web so I'll spare the code implementation. A helpful example can be found here.

---
Tags: sprites, html5
---


title: How does Minecraft update process work?

text:
# Question
Title: How does Minecraft update process work?
When you initially launch Minecraft you open the "launcher", which will check if your client is up to date. If it's not it proceeds to download the latest files & then runs the game.

How does this happen? Is the launcher a separate application, which can execute the main jar file?

# Answer
> 10 votes
Yes, if you examine Minecraft under the hood you can see that it's just a separate file that will launch the JAR file afterwards. However, you're probably more interested in implementing an update solution for your game yourself. If that's the case, check out Sparkle.

---
Tags: java, minecraft-modding
---


title: how to rotate enemy to face player?

text:
# Question
Title: how to rotate enemy to face player?
Okay so i havebeen rotating my enemy to face the player using

```
float targetrotation = Math.Atan2(playerpos-enemypos);
enemy.rotation = targetrotation; (<this line of code i want to change)

```

This simple method has worked fine so far for getting the enemy to look at the player's position. However i decided to add some extra code to get the enemy to gradually rotate towards the player using this method:

```
if(enemy.rotation < targetrotation)
{
   enemy.rotation++;
}

if(enemy.rotation > targetrotation)
{
   enemy.rotation--;
}

```

Now the problem i am having is that when the player moves for example from 360 degree target to 1 degree then the enemy rotates the long way round to move to the 1 degree instead of simply adding 1 degree. Any help on how to correct this problem would be welcomed. I have a picture below:

# Answer
> 3 votes
You could try using this method instead (assuming rotation is represented in degrees):

```
//get difference in degrees between both angles
float rotationDifference = enemy.rotation - targetRotation;

//if difference is greater than 180 degrees, reverse rotating direction
//by adding or subtracting 360 degrees
if(Math.abs(rotationDifference) > 180){
    rotationDifference += rotationDifference > 0 ? -360 : 360;
}

//based on difference, rotate enemy angle
if(rotationDifference < 0){
    enemy.rotation++;
}
else if(rotationDifference > 0){
    enemy.rotation--;
}

```

This method would require some editing if your rotations are not always whole numbers or if the angles are not represented in degrees.

# Answer
> 3 votes
You're probably better off not representing your orientations as angles in the first place, for a couple of good reasons: for one, because there's an inevitable discontinuity of representation *somewhere*; but even more importantly, because it leads to a host of unnecessary trig calls — the `Atan2()` call here is one example of that, but there are no doubt a host of `Cos()` and `Sin()` calls down in the rendering engine somewhere. Instead, I'd recommend representing orientations (and in particular, the enemy's facing) as a (normalized) vector of the direction they're pointing in; this lets you determine which side of your enemy's facing the player is on by doing a simple dot-product test between the vector from enemy to player and the normal to the enemy's facing, and since the normal to a 2d vector (x,y) is just the vector (y, -x), this leads to the following code that replaces all of the awkward code above with two multiplies and a compare:

```
Vector VecToPlayer = Player.Position-Enemy.Position;
if ( (VecToPlayer.X * Enemy.Orientation.Y) > (VecToPlayer.Y * Enemy.Orientation.X) ) {
  Enemy.TurnRight();
} else {
  Enemy.TurnLeft();
}

```

(Note that this code assumes a world where X points rightward and Y points up - that is, where the positive Y axis is 'left' of the positive X axis. If your world works the other way, you'll want to flip the TurnRight() and TurnLeft() calls. Also, you'll need to complicate this *slightly* to handle the case where your enemy is already facing in the correct direction, but I presume that's already being handled somewhere else.)

# Answer
> 1 votes
I'd recommend simply doing the following:

```
    if(enemy.rotation % 360 < targetrotation)
    {
       enemy.rotation++;
    }

    if(enemy.rotation % 360 > targetrotation)
    {
       enemy.rotation--;-
    }

```

This is because, when dealing with degrees, starting from 360 it goes back to 0. Therefore, while 361º may seem to be greater than 30º, 361 is actually just 1º.

# Answer
> 1 votes
@giggas thank you. here is how i managed to get it to work:

float rotationDifference = enemy.rotation - targetrotation;

```
        //if difference is greater than or less than 180 degrees, reverse rotating direction
        if ((rotationDifference) > 180)
        {
            rotationDifference -= 360;
        }
        if ((rotationDifference) < -180)
        {
            rotationDifference += 360;
        }

        //based on difference, rotate enemy angle
        if (rotationDifference < 0)
        {
            enemy.rotation ++;
        }
        else if (rotationDifferencedeg > 0)
        {
            enemy.rotation --;
        }

```

if you are using radians here is how i did it, i had to use radians btw.

```
        //this gets the target rotation based on the player and enemy position in radians
        float targetrotation = (float)Math.Atan2((double)(playerposition.Y - Tanker.Position.Y), (double)(playerposition.X - Tanker.Position.X));

        //calculate the amount of rotaation required
        float rotationDifference = hubrotation - targethubrotation;

        //if difference is greater than or less than pi radians, reverse rotating direction
        if ((rotationDifference) > Math.PI)
        {
            rotationDifference -= (float)Math.PI*2;
        }
        if ((rotationDifference) < -Math.PI)
        {
            rotationDifference += (float)Math.PI*2;
        }
        int rotationDifferencedeg = (int)(MathHelper.ToDegrees(rotationDifference));

        //based on difference, rotate enemy angle
        if (rotationDifferencedeg < 0)
        {
            hubrotation += MathHelper.ToRadians(1);
        }
        else if (rotationDifferencedeg > 0)
        {
            hubrotation -= MathHelper.ToRadians(1);
        }

```

# Answer
> 1 votes
I rotate by the result of:

```
const float Mob::getAngleToVector(irr::core::vector3df target)
{
    irr::core::vector3df mobDirection = IRR.getRotatedVector(irr::core::vector3df(0,0,1), Rotation);
    irr::core::vector3df targetDirection = target - Position;

    mobDirection.normalize();
    targetDirection.normalize();

    irr::core::vector3df targetNormal(-targetDirection.Z, 1, targetDirection.X);

    if(mobDirection.dotProduct(targetNormal) > 0)
    {
        return acos(mobDirection.dotProduct(targetDirection));
    }
    else
    {
        return 0-acos(mobDirection.dotProduct(targetDirection));
    }
}

```

---
Tags: xna, mathematics, game-mechanics, rotation
---


# Question
Title: xna: Methods for having sprite characters in 3d game?
Methods for having sprite characters in 3d game? I am making a game much like Doom. The world is 3d but objects and characters are 2d sprites. I am not asking about billboarding objects. I am asking about methods for having sprite characters that aren't always facing the player and have different frames depending on which way the character is facing. For example when an enemy is walking towards the player it is a 2d texture of a front and when walking away it is a 2d texture of a back.

One way I thought I read about was to draw a cube primitive that is "invisible". This 3d cube allows you to track the orientation of the character. Then you apply a sprite frame to each side of the cube but the 2d texture is only drawn on the side the player is looking at.

The other way I suspected I could do this is to make a 3d plane in a modeling program and import it to XNA. Then use the billboarding method to make sure the plane is always facing the player (you don't see the edge). Apply a the appropriate 2d texture (sprite frame) to the plane based on the direction the character is facing.

I know this is not how Doom did it but please tell me what you think of my ideas or a method on how this can be done.

Thank you.

# Answer
> 1 votes
Billboarding and swapping images is afaik exactly what Doom (and many other games) did. It might not look like it in the source because Doom is not running on a general purpose 3D engine. The game had the advantage to have a fairly locked camera, reducing the amount of possible perspectives (just rotation around 1 axis) and therefor reducing the amount of images required to display a character correctly. You can see this when you run close to a barrel. It still show's you the sideways perspective although you are taller and should see its top.

I never read about the cube technique but it sounds like it has the advantage to already skew and resize the sprite plane (side that is rendered) according to the perspective. I could imagine this adds to the illusion of perspective and may work as a great way to blend between different perspective images of your character. But it is basically the same as rotating a plane in 3D and a plane sounds like less impact.

I would go for the billboarding technique. Depending on your game and visual perfection you aim for you might also want to lock the applied rotation on one axis aswell. You need to implement a way to change your 2D animations anyway and swapping perspective is just that but based on the direction the character is facing and your player is looking. I'm unfamiliar with xna but I could imagine it allows you to create planes at runtime, so you don't need to import it from a 3D program can also easily set the size according to your sprite.

---
Tags: xna, 2d, 3d, sprites, billboarding
---


title: How To Create Scrolling Menu in Xna?

text:
# Question
Title: How To Create Scrolling Menu in Xna?
How To Create Scrolling Menu in Xna like this: http://www.youtube.com/watch?feature=player\_detailpage&v=ijambOyBgPg#t=25s

# Answer
Do you just want a scrolling menu, or is the text zooming necessary as well?

Xna doesn't support freely scaling fonts, as the size is defined at compile time, so if you need the zoom I suggest you either make the menu items as textures, and scale them based on how close they are to the center of the menu or write the text for each item on a RenderTarget2D, which you can then use as a texture.
> 2 votes

---
Tags: xna
---


# Question
Title: Best technique to create oldschool (fake 3D) racing game?
What would be a good approach to develop the render system for an oldschool type racing game that uses a pseudo 3D scenery, like for example **Outrun** or **Lotus Esprit Turbo Challenge**? There's an endless scrolling road and scenery graphics are placed like billboard items, etc. I think you get the idea.

Are these developed in a similar way like Mode7 or is there a different technique behind it? Does the technique has a specific name I could search for on the web? I need to develop something like that in Flash.

# Answer
There's an excellent article out there that explains the 3D rendering of these games in detail. And you'll also find a complete implementation in JavaScript here.

The basic idea is as follows: You divide your screen into a number of strips and use perspective-projection to calculate the texture-coordinates (scaling and y position inside the road-texture) for each strip. Then you draw the portion of the texture into the strip, resulting in a road that vanishes in the distance.
> 23 votes

# Answer
They generate pseudo 3D scenery by using perspective. They have a vanishing point at the center of screen. You can calculate by using perspective projection.
> 1 votes

---
Tags: 3d, rendering, racing
---


# Question
Title: What to use as a Box2D renderer in a release version?
I'm creating a game with libgdx. For testing physics I use a `Box2DDebugRenderer`, which is not fast. When I want to release my full game, what should I use as a renderer?

# Answer
I haven't used Box2D itself (only ports and things based off of it), but the name "Box2DDebugRenderer" suggests that you should not render anything that should be in the final product whatsoever based on it.

Use it to draw collision bounds and collision contact points. This is very useful visual information to see while you're developing your game. The game itself should have its own renderer. Isn't that part of what LibGDX is supposed to provide?
> 2 votes

# Answer
It depends on what you want to render :) Box2d needs step updating to simulate physics only.

```
world.step(boxStep, BOX_VELOCITY_ITERATIONS, BOX_POSITION_ITERATIONS);

if (DEBUG_PHYSICS) {
    debugRenderer.render(world, camera.combined.scale(100f * PHYSICS_SCALE, 100f * PHYSICS_SCALE, 0));
}

```
> 0 votes

---
Tags: box2d, libgdx
---


title: Mobile game textures sizes

text:
# Question
Title: Mobile game textures sizes
I am developing a Windows Phone 7 game using XNA 4.0 which I plan to later port to iOS and android using Monotouch and Monodroid. My question is how to determine what texture size should I include? This is because the in-game objects that utilize the textures dont care about the actual texture size and just re-size them. Windows phone by its own exists in multiple resolution variants. Should I pick the highest resolution emulator and then measure the sizes of my in-game objects, and then re-size their respective textures to be the same?

# Answer
Going from the emulator to an actual mobile device, keep in mind that the mobile device's performance characteristics will not match.

In your particular case, keep in mind that **texture-fetch on a mobile GPU is relatively slow**. Therefore you want to minimise the amount of texture data that you are accessing for each pixel. Ideally you want the texture to be drawn at 1:1 scale on screen.

For example, if you have a large texture that you scale down, then a small rendering region is going to have to load up a large amount of texture data. (Even if texturing only uses a few pixels from the texture, if they're far apart, unused pixels in between will get loaded into cache.)

So, basically, **try and store textures in GPU memory as close to their on-screen size as possible**. Or **use mipmapping**, which will automatically select smaller versions of your textures when needed (and also gives you higher quality when scaling down). Trilinear filtering (interpolating between two mip levels) requires more texture fetch - but is still better than substantial downscaling.

As for the maximum supported texture size, WP7 has a maximum texture size of 2048 (XNA Reach profile), as does iOS (from iPhone 3GS onwards, before it was 1024). The actual size you make your textures is more of a artistic consideration - and a consideration of how much memory you can afford.
> 1 votes

# Answer
Max texture size for WP7 is 1k x 1k and from what I remember there is only 1 physical resolution available for WP7 480x800 so really if you are looking at different texture sizes it would only be for the other platforms. Windows Phone 8 introduced larger resolutions and the capability of utilizing much larger textures. If you want the maximum detail for each platform then you will likely wind up providing different rez variants for each distinct screen resolution in order to minimize the amount of scaling that is done.
> 0 votes

---
Tags: xna, c#, textures, windows-phone-7
---


# Question
Title: What makes movement feel smooth, and what are some standard methods to achieve this?
I'm either not searching correctly or there is really not a lot of material on character movement in 3D games. I'm mostly interested in how people usually implement character movement in games like FPS and action games, where usually the `W``A``S``D` keys are used to move backward and forward and for strafing, with the mouse used for turning. I'd like to learn what methods are generally used, and what makes the movement handling feel right.

For example, I tried to implement movement handling using some 'walking' force to move my character, by integrating the equations of motion. Needless to say, this felt more like handling a spaceship, rather than a human. Others probably use just some velocity to steer the characters, maybe coupled with a deceleration when no buttons are pressed. I tried something similar in following code, but it still feels kinda clunky.

```

if(move_comps_[*entity]->mv_direction != glm::ivec3(0))
{
    glm::vec3 mv_dir(0.0);
    mv_dir += (float)move_comps_[*entity]- > mv_direction.z
        * transform_comps_[*entity]->forwardVec();
    mv_dir += (float)move_comps_[*entity]->mv_direction.x
        * transform_comps_[*entity]->rightVec();
    mv_dir = glm::normalize(mv_dir);

    glm::vec3& velocity = move_comps_[*entity]->velocity_;
    velocity += dt * move_comps_[*entity]->acceleration_ * mv_dir;

    if(glm::dot(velocity, velocity) > sqr(move_comps_[*entity]->max_velocity_))
    {
        velocity = move_comps_[*entity]->max_velocity_ * mv_dir;
    }

    transform_comps_[*entity]->pos_ += dt * velocity + 0.5f
        * move_comps_[*entity]->acceleration_ * sqr(dt) * mv_dir;
}
else if(glm::length(move_comps_[*entity]->velocity_) > 0.0)
{
    glm::vec3& velocity = move_comps_[*entity]->velocity_;
    glm::vec3 mv_dir = glm::normalize(velocity);
    velocity -= dt * move_comps_[*entity]->acceleration_ * mv_dir;

    if(glm::dot(velocity, velocity) < 0.01f)
    {
        velocity = glm::vec3(0.0);
    }
    else
    {
        transform_comps_[*entity]->pos_ += dt * velocity + 0.5f
            * move_comps_[*entity]->acceleration_ * sqr(dt) * mv_dir;
    }
}

```

Here in essence, I use an integer vector which can hold (-1, 0, 1) in each dimension. When a `walk_forward_start` event is fired, for example, this z component is increased by 1 and decreased when the player releases the button. This vector is used to find out in which direction to move the player. I also added a simple deceleration mechanism. As I said, this still doesn't feel right, and is certainly not really smooth. What could I do to improve it?

Others have gone as far as implementing advanced techniques such as inverse kinematics, too. I wouldn't go that far, but how far do you have to go to make a movement system feel good?

Essentially, beyond the sauce, I want to know what makes pushing forward, strafing, turning and stopping feel smooth and what are some standard methods to achieve this. Do you use some impulse/force based method? Do you use a linear velocity method?

Note: This may seem like a subjective question and it might be up to some point, but I think there must be some general consensus or else there would be a big variations on how these controls are handled by games.

# Answer
> 1 votes
It will also help to tie the velocity of the character to the stride length of the animation so that it doesn't appear like the character is sliding along the ground. To go further with that you could also adjust the velocity by adding an acelleration whenever a foot of the character is in a push off position and then an overall decelleration for the rest of the animation(until the next push-off) which would artificially replicate the lurching gate of someone running/walking.

---
Tags: physics, movement, input
---


title: JBox2D simple example for Android?

text:
# Question
Title: JBox2D simple example for Android?
I'm starting to develop an Android game. I've already installed jBox2D but I can't find complete code to develop a simple application from scratch using this framework. Thanks in advance!

# Answer
Have you tried out the testbed? This lets will let you play with the physics and get a feel for how it works, and the source is included for each test, so you can get an idea of what does what. The wiki explains how to add tests. This is the best resource I know of for getting acquainted with the engine, you may look for Box2d examples in C++ and try and adapt them, as it's much more prolific.
> 2 votes

---
Tags: android, box2d
---


# Question
Title: Is there a fully featured OBB class for Ogre3D?
Is there a fully featured OBB (Oriented Bounding Box) class for Ogre3D?

I don't think there is one by default but I am looking for an alternative which has all the features of the `AxisAlignedBox` class.

# Answer
> 3 votes
No, Ogre itself doesn't seem to have an oriented bounding box class (according to the API documentation).

An OBB is a mathematic concept though, and a properly-designed interface to one isn't tied to a particular rendering engine anyhow. Thus you could build your own, possibly referring to implementations you can find around the Internet, or utilize one of those implementations directly (presuming the license permits it).

---
Tags: ogre, bounding-boxes
---


# Question
Title: Unity3D smooth movement with joypad button press
First off, I'm sorry this is such a silly question, but for the life of me I can't seem to get it to work. And I've just spent the last hour trying to do so.

All I want to do is have my camera move up, in a smooth fashion, when I press the shoulder button on my joypad. I have it so that when I press the button, it jumps up. Not in a smooth movement.

The code I have is as follows:

```
    float _maxY = 0.0f;
    if (Input.GetKeyDown(KeyCode.Joystick1Button5))
   {
      _maxY++;
      transform.Translate(0, _maxY, 0);
   }

```

This is found within my update function. I've been looking for the answer to this for hours now, but can't find anything. Can anyone please help me?

# Answer
Read the docs - the GetKeyDown function triggers exactly once, in the frame when the button is pressed. That code will therefore only be executed once per press. If you want to move continuously, you need to use one of the functions that continuously detects that a key is pressed in that frame, and move a small amount each time.
> 3 votes

# Answer
You shouldn't increment from 0 every frame, you should increment from the object's current position.
> 1 votes

# Answer
The easiest solution is to make the movement amount smaller, something like `_maxY+=.05f;`

Additionally, you'll want to modify your code to react to the `GetKeyDown` function. In the update loop you'd have something like:

```
if (Input.GetKeyDown(KeyCode.Joystick1Button5))
{
     goUp = true;
}

if (Input.GetKeyUp(KeyCode.Joystick1Button5))
{
     goUp = false;
}

if(goUp){
     _maxY+=.05f;
     transform.Translate(0, _maxY, 0);
}

```
> 1 votes

---
Tags: c#, unity, input
---


# Question
Title: Best pathfinding for a 2D world made by CPU Perlin Noise, with random start- and destinationpoints?
I have a world made by Perlin Noise. It's created on the CPU for consistency between several devices (yes, I know it takes time - I have my techniques that make it fast enough).

Now, in my game you play as a fighter-ship-thingy-blob or whatever it's going to be. What matters is that this "thing" that you play as, is placed in the middle of the screen, and moves along with the camera.

The white stuff in my world are walls. The black stuff is freely movable.

Now, as the player moves around he will constantly see "monsters" spawning around him in a circle (a circle that's larger than the screen though). These monsters move inwards and try to collide with the player.

This is the part that's tricky. I want these monsters to constantly spawn, moving towards the player, but avoid walls entirely.

I've added a screenshot below that kind of makes it easier to understand (excuse me for my bad drawing - I was using Paint for this).

In the image above, the following rules apply.

* The red dot in the middle is the player itself.
* The light-green rectangle is the boundaries of the screen (in other words, what the player sees). These boundaries move with the player.
* The blue circle is the spawning circle. At the circumference of this circle, monsters will spawn constantly. This spawncircle moves with the player and the boundaries of the screen.
* Each monster spawned (shown as yellow triangles) wants to collide with the player.
* The pink lines shows the path that I want the monsters to move along (or something similar). What matters is that they reach the player without colliding with the walls.

The map itself (the one that is Perlin Noise generated on the CPU) is saved in memory as two-dimensional bit-arrays. A 1 means a wall, and a 0 means an open walkable space. The current tile size is pretty small. I could easily make it a lot larger for increased performance.

I've done some path algorithms before such as A\*. I don't think that's entirely optimal here though.

# Answer
> 3 votes
Interesting problem.

Staring at the picture and thinking about the problem I think a set of feelers might be the way to go.

What you do is just put a couple vectors (lines or whatever) on each side of the agent and each time step you test if they are in a wall or not. If they are in the wall you steer away from it. So if your touching the right one you need to steer left. As you get closer to the wall ramp up that steering force to get away from it.

As long as the agent can fit between the walls it should be able to steer right on through. You already have the data for the walls and procedurally creating a graph sound like a pain the butt considering your situation.

Mix that steering force with your normal movement and they should be fine. It might need some heavy tweaking (feeler length etc) You can also scale the length of the feelers off of the speed the agent is moving so that the reaction time to steer away from a wall is adequate.

Anyhow, I hope this helps.

Edit: Forgot to add. I know it seems obvious from the picture but thought I would say the feelers are kept aligned to the velocity of the agent.

# Answer
> 1 votes
You can use the fact that there's only one target in your path finding problem.

For example, you give regularly the position of your player to a different thread. That thread calculates a map of distances from the player for each cell in the blue circle. (I would have used a blue square around the green square) Diagonal movement usually count as 1.4 movement cost. Once done, the thread replaces the previous calculated distance map. You don't have to redraw this map too often, according to the player and ennemies speed. Each time an ennemi wants to move, he chooses the cell closest to the player in his neighbourhood according to this distance map.

When the ennemies get very close, you can use a different path finding method.

---
Tags: path-finding, sharpdx
---


# Question
Title: Programmatically and efficiently create a graphical ripple effect?
I was developing tower of defence game for a long time. It was about to complete but I have to create ripple effect for one of the weapon that I have used.

First question I want to ask is that is it feasible to use ripple effect for such purpose? Because suddenly fps goes down.

I have created ripple effect for live wallpaper. But I don't know how to create it for normal game activity.

I was not able to understand many things from it. If any one has some knowledge on this then please provide.

Edit : I include the image for ripple effect that I think I have to use for weapon fire.

Also I include code that I use to create ripple effect. Similar code with some changes I used to create live wallpaper and it work perfectly. But in normal game activity I don't able to find my mistake. So please guide on this

```
@Override
public Engine onCreateEngine(EngineOptions pEngineOptions) {

    return new org.andengine.engine.Engine(pEngineOptions) {
        private boolean mRenderTextureInitialized;

        private RenderTexture mRenderTexture;
        private UncoloredSprite mRenderTextureSprite;

        @Override
        public void onDrawFrame(final GLState pGLState)
                throws InterruptedException {
            final boolean firstFrame = !this.mRenderTextureInitialized;

            if (firstFrame) {
                this.initRenderTextures(pGLState);
                this.mRenderTextureInitialized = true;
            }

            final int surfaceWidth = this.mCamera.getSurfaceWidth();
            final int surfaceHeight = this.mCamera.getSurfaceHeight();

            this.mRenderTexture.begin(pGLState);
            {
                /* Draw current frame. */
                super.onDrawFrame(pGLState);
            }
            this.mRenderTexture.end(pGLState);

            /* Draw rendered texture with custom shader. */
            {
                pGLState.pushProjectionGLMatrix();
                pGLState.orthoProjectionGLMatrixf(0, surfaceWidth, 0,
                        surfaceHeight, -1, 1);
                {
                    this.mRenderTextureSprite
                            .onDraw(pGLState, this.mCamera);
                }
                pGLState.popProjectionGLMatrix();
            }
        }

        private void initRenderTextures(final GLState pGLState) {
            final int surfaceWidth = this.mCamera.getSurfaceWidth();
            final int surfaceHeight = this.mCamera.getSurfaceHeight();

            this.mRenderTexture = new RenderTexture(RippleEffectDemo.this
                    .getEngine().getTextureManager(), surfaceWidth,
                    surfaceHeight);
            this.mRenderTexture.init(pGLState);

            final ITextureRegion renderTextureTextureRegion = TextureRegionFactory
                    .extractFromTexture(this.mRenderTexture);
            this.mRenderTextureSprite = new UncoloredSprite(0, 0,
                    renderTextureTextureRegion, RippleEffectDemo.this
                            .getEngine().getVertexBufferObjectManager()) {

                @Override
                protected void preDraw(final GLState pGLState,
                        final Camera pCamera) {

                    this.setShaderProgram(RippleShaderProgram.getInstance());

                    super.preDraw(pGLState, pCamera);

                    if (mCurrentWaveLength > 25)
                        mCurrentWaveLength -= 25;
                    else
                        mCurrentWaveLength = 0;

                    float currentTime = -0.001f * mCurrentWaveLength;
                    float aliveTimer = (float) mCurrentWaveLength
                            / (float) mWaveLength;

                    GLES20.glUniform4f(
                            RippleShaderProgram.sUniformResolution,
                            (float) SCREEN_WIDTH, (float) SCREEN_HEIGHT,
                            RippleEffectDemo.this.mDropCenterX,
                            RippleEffectDemo.this.mDropCenterY);
                    GLES20.glUniform2f(RippleShaderProgram.sUniformTime,
                            currentTime, aliveTimer);
                }
            };
        }
    };
}

@Override
public void onCreateResources() {
    this.mBitmapTextureAtlas = new BitmapTextureAtlas(
            this.getTextureManager(), 512, 512);
    this.mBackgroundTextureRegion = BitmapTextureAtlasTextureRegionFactory
            .createFromAsset(this.mBitmapTextureAtlas, this,
                    "badge_large.png", 0, 0);
    this.mBitmapTextureAtlas.load();

    this.getShaderProgramManager().loadShaderProgram(
            RippleShaderProgram.getInstance());
}

@Override
public Scene onCreateScene() {
    final Scene scene = new Scene();

    final int centerX = (int) ((CAMERA_WIDTH - this.mBackgroundTextureRegion
            .getWidth()) / 2);
    final int centerY = (int) ((CAMERA_HEIGHT - this.mBackgroundTextureRegion
            .getHeight()) / 2);

    backgroundSprite = new Sprite(centerX, centerY,
            this.mBackgroundTextureRegion, this.getEngine()
                    .getVertexBufferObjectManager());
    scene.attachChild(backgroundSprite);

    scene.setOnSceneTouchListener(this);

    return scene;
}

protected void onTap(final int pX, final int pY) {
    // we do not support multiple wave
    if (0 == mCurrentWaveLength) {
        // so skip wave, if it is active
        mCurrentWaveLength = mWaveLength;

        this.mDropCenterX = (float) pX;
        this.mDropCenterY = (float) pY;
    }
}

@Override
public void onClick(final ClickDetector pClickDetector,
        final int pPointerID, final float pSceneX, final float pSceneY) {
}

@Override
public boolean onSceneTouchEvent(final Scene pScene,
        final TouchEvent pSceneTouchEvent) {

    if (pSceneTouchEvent.isActionDown()) {
        onTap((int) pSceneTouchEvent.getX(), (int) pSceneTouchEvent.getY());
        return true;
    }

    this.mDropCenterX = pSceneTouchEvent.getMotionEvent().getX()
            / this.mCamera.getSurfaceWidth();
    this.mDropCenterY = pSceneTouchEvent.getMotionEvent().getY()
            / this.mCamera.getSurfaceHeight();

    return true;
}

public static class RippleShaderProgram extends ShaderProgram {
    private static RippleShaderProgram INSTANCE;

    public static final String VERTEXSHADER = "uniform mat4 "
            + ShaderProgramConstants.UNIFORM_MODELVIEWPROJECTIONMATRIX
            + ";\n" + "attribute vec4 "
            + ShaderProgramConstants.ATTRIBUTE_POSITION + ";\n"
            + "attribute vec2 "
            + ShaderProgramConstants.ATTRIBUTE_TEXTURECOORDINATES + ";\n"
            + "varying vec2 "
            + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + ";\n"
            + "void main() {\n" + " "
            + ShaderProgramConstants.VARYING_TEXTURECOORDINATES + " = "
            + ShaderProgramConstants.ATTRIBUTE_TEXTURECOORDINATES + ";\n"
            + " gl_Position = "
            + ShaderProgramConstants.UNIFORM_MODELVIEWPROJECTIONMATRIX
            + " * " + ShaderProgramConstants.ATTRIBUTE_POSITION + ";\n"
            + "}";

    // private static final String UNIFORM_TOUCH_COORDS = "touchCoords";
    private static final String UNIFORM_RESOLUTION = "resolution";
    private static final String UNIFORM_TIME = "time";

    public static final String FRAGMENTSHADER = "precision mediump float;\n"
            +

            "uniform sampler2D "
            + ShaderProgramConstants.UNIFORM_TEXTURE_0
            + ";\n"
            + "varying mediump vec2 "
            + ShaderProgramConstants.VARYING_TEXTURECOORDINATES
            + ";\n"
            + "uniform vec4 "
            + RippleShaderProgram.UNIFORM_RESOLUTION
            + ";\n"
            + "uniform vec2 "
            + RippleShaderProgram.UNIFORM_TIME
            + ";\n"
            +

            "void main() {\n"
            + " vec2 tap = "
            + RippleShaderProgram.UNIFORM_RESOLUTION
            + ".zw;\n"
            + " tap.x = "
            + RippleShaderProgram.UNIFORM_RESOLUTION
            + ".x - tap.x;\n"
            + " vec2 tPos = -1.0 + 2.0 * tap.xy / "
            + RippleShaderProgram.UNIFORM_RESOLUTION
            + ".xy;\n"
            + " vec2 cPos = -1.0 + 2.0 * gl_FragCoord.xy / "
            + RippleShaderProgram.UNIFORM_RESOLUTION
            + ".xy;\n"
            + " cPos = cPos + tPos;\n"
            + " float cLength = length(cPos);\n"
            + " float radius = 18.0 * "
            + RippleShaderProgram.UNIFORM_TIME
            + ".y;\n"
            + " float amplitude = 0.05 * "
            + RippleShaderProgram.UNIFORM_TIME
            + ".y;\n"
            + " vec2 uv = gl_FragCoord.xy/"
            + RippleShaderProgram.UNIFORM_RESOLUTION
            + ".xy"
            + "+(cPos/cLength)*cos(cLength*radius-"
            + RippleShaderProgram.UNIFORM_TIME
            + ".x *4.0)*amplitude;\n"
            + " vec3 col = texture2D("
            + ShaderProgramConstants.UNIFORM_TEXTURE_0
            + ",uv).xyz;\n"
            + " gl_FragColor = vec4(col,1.0); \n" + // color

            "}";

    // ===========================================================
    // Fields
    // ===========================================================

    public static int sUniformModelViewPositionMatrixLocation = ShaderProgramConstants.LOCATION_INVALID;
    public static int sUniformTexture0Location = ShaderProgramConstants.LOCATION_INVALID;
    public static int sUniformResolution = ShaderProgramConstants.LOCATION_INVALID;
    public static int sUniformTime = ShaderProgramConstants.LOCATION_INVALID;

    // ===========================================================
    // Constructors
    // ===========================================================

    private RippleShaderProgram() {
        super(RippleShaderProgram.VERTEXSHADER,
                RippleShaderProgram.FRAGMENTSHADER);
    }

    public static RippleShaderProgram getInstance() {
        if (RippleShaderProgram.INSTANCE == null) {
            RippleShaderProgram.INSTANCE = new RippleShaderProgram();
        }
        return RippleShaderProgram.INSTANCE;
    }

    @Override
    protected void link(final GLState pGLState)
            throws ShaderProgramLinkException {
        GLES20.glBindAttribLocation(this.mProgramID,
                ShaderProgramConstants.ATTRIBUTE_POSITION_LOCATION,
                ShaderProgramConstants.ATTRIBUTE_POSITION);
        GLES20.glBindAttribLocation(
                this.mProgramID,
                ShaderProgramConstants.ATTRIBUTE_TEXTURECOORDINATES_LOCATION,
                ShaderProgramConstants.ATTRIBUTE_TEXTURECOORDINATES);

        super.link(pGLState);

        RippleShaderProgram.sUniformModelViewPositionMatrixLocation = this
                .getUniformLocation(ShaderProgramConstants.UNIFORM_MODELVIEWPROJECTIONMATRIX);
        RippleShaderProgram.sUniformTexture0Location = this
                .getUniformLocation(ShaderProgramConstants.UNIFORM_TEXTURE_0);

        RippleShaderProgram.sUniformResolution = this
                .getUniformLocation(RippleShaderProgram.UNIFORM_RESOLUTION);
        RippleShaderProgram.sUniformTime = this
                .getUniformLocation(RippleShaderProgram.UNIFORM_TIME);
    }

    @Override
    public void bind(final GLState pGLState,
            final VertexBufferObjectAttributes pVertexBufferObjectAttributes) {
        GLES20.glDisableVertexAttribArray(ShaderProgramConstants.ATTRIBUTE_COLOR_LOCATION);

        super.bind(pGLState, pVertexBufferObjectAttributes);

        GLES20.glUniformMatrix4fv(
                RippleShaderProgram.sUniformModelViewPositionMatrixLocation,
                1, false, pGLState.getModelViewProjectionGLMatrix(), 0);
        GLES20.glUniform1i(RippleShaderProgram.sUniformTexture0Location, 0);
    }

    @Override
    public void unbind(final GLState pGLState)
            throws ShaderProgramException {
        GLES20.glEnableVertexAttribArray(ShaderProgramConstants.ATTRIBUTE_COLOR_LOCATION);

        super.unbind(pGLState);
    }
}

```

# Answer
After hard working I found working code for the ripple effect. I have to say thanks to genius guy named thepi for his effort. The link for correct working code :

http://www.andengine.org/forums/gles1/ripple-effect-t10598.html

I here posted because I think lot other user can get benefit from it and also want to say thank to the people who have tried for this.
> 0 votes

# Answer
The "ripple" effect you are showing is just a radial sinewave: sin(t), where t is the distance from some center.

Image from here

Doing this kind of deformation in a vertex or pixel shader is easy: just set up the center of the wave as a uniform variable `waveCenter`, then move every vertex in z (where z is the "up" direction) by MAGNITUDE*sin( FREQUENCY*t ), where t is the distance the vertex has from that `waveCenter`. FREQUENCY is how fast you want the wave to ripple. You can even make the wave fade out by dividing MAGNITUDE by the distance from the `waveCenter`.
> 14 votes

---
Tags: andengine
---


title: Zoom In/Out Camera To Show Whole World

text:
# Question
Title: Zoom In/Out Camera To Show Whole World
I am developing side scrolling game using AndEngine, and looking for additional camera control. I would like to view the whole level and then zoom/pan the camera to the left corner of the scene.

My whole scene is 4096px wide by 768px high, and my camera resolution is 1024px wide by 768px high. I used AndEngine's ZoomCamera class for this purpose and setZoomFactor to 0.1f to show whole game play.

So how do I pan the camera to the default left corner?

# Answer
> 3 votes
The camera class has several methods to control its use. You've discovered some of them already with setZoomFactor. To move the camera directly you can use this:

```
setCenter(float pCenterX, float pCenterY)

```

Where X and Y are the scene coordinates. If what you're asking is how to move the camera gracefully, rather than simply plopping it in the new location, there are a few ways to accomplish it. One is to use SmoothCamera instead of ZoomCamera. SmoothCamera extends ZoomCamera and comes with a few additional features. When you set the position of the smoothcamera it will "move" to that location, instead of jumping to it. You can also do things like setMaxVelocity() and such to control the speed.

Another option to give you some additional control is to create a sprite (it can be invisible if you like) and set the camera to chase the sprite. Then you can do fun things with the camera by manipulating the sprite using EntityModifiers (e.g., pathEntityModifier to move the camera around, arcmodifier to make it take a curved route there, etc.). I like this approach because you can make the sprite a cross-hair and let it be visible for debugging purposes; turn it off for production, so you know exactly where the camera is looking.

By the way, if you use the smoothcamera, there may be times when you still want it to jump to a location, rather than get there gracefully. For that purpose there's a setCenterDirect() method.

Hope this helps.

---
Tags: camera, andengine
---


# Question
Title: Platform independent replacement for LuaInterface
I'm currently working on a project in C#/XNA, however I'm planning to migrate this to MonoGame so that it can go onto more platforms. The problem is that I am currently using a lot of Lua, and for that in XNA, I am using LuaInterface.

The issue I now have is that LuaInterface only runs on Windows because of the dlls that it requires, but I would like to make this project available on Linux and Macs as well. Does anyone know of a good alternative to LuaInterface that could slot into Mono quite nicely?

Re-writing the parts which are currently in Lua in another language wouldn't be too much of a problem, but I need to be able to use scripting as I want to make large portions of my game open to players for modding.

# Answer
I use KopiLua, which is a Lua interpreter rewritten entirely in plain C#.

KopiLua and LuaInterface can work together and in fact someone did, calling it KopiLuaInterface. Just google that.

Update: For those reading this answer, there have been two other projects that do the same which might be worth looking into as well: NLua and Moonsharp
> 3 votes

---
Tags: xna, lua, monogame
---


title: How rotate a 3D cube at its center XNA?

text:
# Question
Title: How rotate a 3D cube at its center XNA?
I try to rotate a 3D cube on itself from its center, not the edge. Here is my code used.

```
public rotatemyCube()
{
    ...
    Matrix newTransform = Matrix.CreateScale(scale) * Matrix.CreateRotationY(rotationLoot) * Matrix.CreateTranslation(translation);
    my3Dcube.Transform = newTransform;
    ....

public void updateRotateCube()
{
    rotationLoot += 0.01f;
}

```

My cube rotate fine, but not from the center. Here is a schematic that explains my problem.

And i need this:

# Answer
> 5 votes
If you want to rotate an object around.Center must be at the point(0,0,0) To achieve that simply Translate the object to point(0,0,0) Rotate and Translate back

```
example:
Translate(0,0,-1)
Rotate(90)
Translate(0,0,1)

```

---
Tags: xna, c#, models, rotation, transformation
---


# Question
Title: Eclipse/LibGDXgame doesn't load textures
Our LibGDX project doesn't load textures after building on PC/Android but when it's built from Eclipse using Ctrl + F11 (Run/Debug) everything is fine. What could be causing that?

# Answer
You are probably running your application from different working directories. Check the project settings in Eclipse and look for "Debug Directory" or similar. If you run you program from withing that same directory outside Eclipse it will probably work fine.
> 2 votes

---
Tags: libgdx, eclipse
---


# Question
Title: OpenGL ES 1.1 - How to batch draw particles with different translations?
Assuming that I've combined all of my vertex data for many particles into a single array, how would I batch draw all of those particles in a manner that preserves their *unique* translations?

Any code examples would be greatly appreciated.

# Answer
> 1 votes
In my OpenGL ES 1.1 particle system I solved this by **drawing one alpha blended textured triangle per particle**. Another option would be to draw quads (or two-tri strips), but i found single tris to be OK for my application which has many small particles. If you have few large particles, quads might be better (fill-rate vs trig).

For each particle in my list I calculated the corners of the triangle by simple vector math and a pre-calculated look-up table. I would also make sure that each triangle faced the camera using a billboarding helper class. In other words I did not use any OpenGL transformations on the individual particles. This code would also handle rotating the sprite and/or scaling of the individual sprites.

Each corner of the triangle would be appended to the vertex buffers so that 3\*3 floats would be added per triangle.

Here is the snippet from my code that does the actual building of the vertices buffer (method on the particle object, called once per particle per update):

```
void calculateVerticesFromPoints(float[] eye, GraphicsEngine ge, float verts[], float colors[], int offset) {

    BillboardHelper.doBillboard(ParticleSystem.BILLBOARD_MATRIX, mPosition, ge.getActiveCamera().getPosition(), true);

    for (int i = 0; i < 3; i++) {
        final int j = i * ParticleSystem.VECTOR_STRIDE;
        final int k = offset + j;
        mParticleSystem.mTemp[0] = mPosition[0] + ParticleSystem.TRI_CORNERS[j + 0] * mParticleSystem.mSize;
        mParticleSystem.mTemp[1] = mPosition[1] + ParticleSystem.TRI_CORNERS[j + 1] * mParticleSystem.mSize;
        mParticleSystem.mTemp[2] = mPosition[2] + ParticleSystem.TRI_CORNERS[j + 2] * mParticleSystem.mSize;
        mParticleSystem.mTemp[3] = 1.0f;
        Matrix.multiplyMV(verts, k, ParticleSystem.BILLBOARD_MATRIX, 0, mParticleSystem.mTemp, 0);
        colors[k + 0] = 1.0f;
        colors[k + 1] = 0.5f;
        colors[k + 2] = 0.0f;
        colors[k + 3] = 1.0f;
        //Log.d(TAG, String.format(" %d (%.2f,%.2f,%.2f)", k, verts[k + 0], verts[k + 1], verts[k + 2]));
    }

}

```

I have also included my entire billboarding helper for good measure :\>

```
package com.playmio.android.graphicsengine.scene.primitives;

import android.opengl.Matrix;

public class BillboardHelper {

    // This is the original lookAt vector for billboards in world coordinates
    private static final float  billboardLookAt[]   = { 0, 0, 1 };

    private static final float  objToCamProj[]      = new float[3];
    private static final float  objToCam[]          = new float[3];
    private static final float  upAux[]             = new float[3];

    public static void doBillboard(float matrix[], float pos[], float cam[], boolean spherical) {
        Matrix.setIdentityM(matrix, 0);

        // ObjToCamProj is the vector in world coordinates from the local origin to the camera projected in the XZ plane
        objToCamProj[0] = cam[0] - pos[0];
        objToCamProj[1] = 0.0f;
        objToCamProj[2] = cam[2] - pos[2];

        // Normalize both vectors to get the cosine directly afterwards
        mathsNormalize(objToCamProj);

        // Easy fix to determine whether the angle is negative or positive for positive angles upAux will be a vector pointing in the positive y direction, otherwise upAux will point downwards effectively reversing the rotation.
        mathsCrossProduct(upAux, billboardLookAt, objToCamProj);

        // Compute the angle
        float angleCosine = mathsInnerProduct(billboardLookAt, objToCamProj);

        // Perform the first rotation. The if statement is used for stability reasons if the lookAt and objToCamProj vectors are too close together then |angleCosine| could be bigger than 1 due to lack of precision
        if ((angleCosine < 0.99990) && (angleCosine > -0.9999)) {
            Matrix.rotateM(matrix, 0, (float) (Math.acos(angleCosine) * 180 / 3.14), upAux[0], upAux[1], upAux[2]);
        }

        if (spherical) {
            // So far it is just like the cylindrical billboard. The code for the second rotation tilts the object so that it faces the camera objToCam is the vector in world coordinates from the local origin to the camera
            objToCam[0] = cam[0] - pos[0];
            objToCam[1] = cam[1] - pos[1];
            objToCam[2] = cam[2] - pos[2];

            // Normalize to get the cosine afterwards
            mathsNormalize(objToCam);

            // Compute the angle between objToCamProj and objToCam, i.e. compute the required angle for the lookup vector
            angleCosine = mathsInnerProduct(objToCamProj, objToCam);

            // Tilt the object. The test is done to prevent instability when objToCam and objToCamProj have a very small angle between them
            if ((angleCosine < 0.99990) && (angleCosine > -0.9999)) {
                Matrix.rotateM(matrix, 0, (float) (Math.acos(angleCosine) * 180 / Math.PI), (objToCam[1] < 0) ? 1 : -1, 0, 0);
            }
        }
    }

    private static float mathsInnerProduct(float[] v, float[] q) {
        return ((v)[0] * (q)[0] + (v)[1] * (q)[1] + (v)[2] * (q)[2]);
    }

    private static void mathsCrossProduct(float[] a, float[] b, float[] c) {
        (a)[0] = (b)[1] * (c)[2] - (c)[1] * (b)[2];
        (a)[1] = (b)[2] * (c)[0] - (c)[2] * (b)[0];
        (a)[2] = (b)[0] * (c)[1] - (c)[0] * (b)[1];

    }

    private static void mathsNormalize(float[] v) {
        float d = (float) (Math.sqrt((v[0] * v[0]) + (v[1] * v[1]) + (v[2] * v[2])));
        v[0] = v[0] / d;
        v[1] = v[1] / d;
        v[2] = v[2] / d;
    }

}

```

# Answer
> 0 votes
Are your vertices something like topleft position:-1,-1, bottomright position +1,+1? All being rendered to the center of the screen? And you're moving them around with the worldview matrix?

To use vertex arrays and give each particle individual positions you need to do the transformation on the CPU. For each particle you have a set of vertices 4 if you're doing a quad, 6 if it's made from two triangles. Lets say the particle is 2x2 and the center is 0,0.

```
topleft [-1, 1]
topright [1, 1]
bottomleft [-1,-1]
bottomright [1, -1]

```

If you drew this it would create a particle centered around the origin of your scene, how big it appears would depend on your projection matrix. If you've got a position for each particle all you need do is going through all the vertices and add them to the particle position.

```
position = Vector(100, 50, -20)

topleft [-1, 1]  = position + topleft
topright [1, 1] = position + topright
bottomleft [-1,-1] = position + bottomleft
bottomright [1, -1] = position + bottomright

```

Do that for all your particles each time they change position. This is reasonably common solution, you might think it seems quite slow (but it's not too bad) try it out and see how it works in your case.

If you are pushing a lot of particles and find you need things to be faster then it's probably best looking at doing the entire particle effect as a shader, that way you reduce the communication between the gpu and cpu.

# Answer
> 0 votes
Just put your particles coordinates to buffer (geometryBuf in example) considering unique translations for each. And batch draw it with glDrawArrays().

```
glEnableClientState(GL10.GL_VERTEX_ARRAY);

glVertexPointer(2, GL10.GL_FIXED, 0, geometryBuf);

glDrawArrays(GL10.GL_TRIANGLES, 0, count * 6);

glDisableClientState(GL10.GL_VERTEX_ARRAY);

```

Params depend on particles type.

---
Tags: iphone, ios, opengl-es, spritebatch
---


title: Java2D Collision Detection

text:
# Question
Title: Java2D Collision Detection
I've been wrapping my head around Java2D collision detection. I am working with Slick library and trying to figure a simple clean code to check if a collision has occurred.

The idea is fairly simple, I have an Entity class seen as a bound box (a rectangle in my case,but I am not using the intersects method), I am trying to run a check if current entity is colliding with any other entities passed in an arraylist:

```
    public boolean collides(Object o){
    Entity e = (Entity) o;
    return x + width > e.x && x < e.x + e.width && y + height > e.y && y < e.y + e.height;
}

public boolean collisidesAny(ArrayList al){
    for(Object o: al){
        return collides(o);
    }
    return false;
}

```

Now the thing with this code is that it gives me quite a bit of headache. The second method will return true the moment the objects do collide, and if I was to use it with a keyboard I wouldn't be able to move back since it won't allow any commands. Naturally I tried with sending the entity one step back when collision does occur, but the problem is I can't know where did it occur from, so I would have to do a step back both x and y wise. Other way I tried was a priori check, where I would check if a collision would occur if a step was made and if it wasn't I would allow the step, but this has gotten really complicated and buggy very quickly. Therefor I would like to know if there was a way to do collision this way?

Thanks for taking your time to read this, P.

# Answer
> 1 votes
Here are some great resources within the StackExchange Community on collision handling:

And here are some outside stackexchange:

---
Tags: java, collision-detection, slick
---


title: Scene - human speed correlation

text:
# Question
Title: Scene - human speed correlation
I am writing a really simple game with a scene (horizontal plane) and a human moving to the right of the plane (watching the simulation from the +z axis).

The scene contains some trees, which I am moving towards -x axis in order to create the animation effect (by adding a float to their current position).

The human just walks or runs with increasing/ decreasing the angular velocity of one of his legs.

The question comes down to, how can I combine this two entities in order to correlate the change of the speed of the human with the change of the variable that is responsible for making the animation of the scene?

Should I convert the angular velocity to velocity?

# Answer
> 3 votes
Yes. Convert the angular velocity to a linear velocity. Use the human linear velocity to move the scene so that the scenery appears to move at the correct speed to the human walk speed.

You can convert to linear velocity by modeling the leg as a circle and using the length of the arc as the linear distance traveled. Or more simply, the angular velocity times the radius to the circle that represents the leg.

# Answer
> 0 votes
Actually, you should have the velocity of the human (from the distance he moves and the delta time). Just use the velocity to move the ground to the opposite direction.

A question for you: If the camera is always following the human, the trees should be moving backward on your screen already. Why to you need another velocity to move it (which makes them move twice as fast as they should be)? Is it because you want to have different layes of background?

---
Tags: movement
---


title: Not repeating background in platformer

text:
# Question
Title: Not repeating background in platformer
I need to make not repeating background for platformer. I can't find any description of implementation and I developed algorithm but I'm not sure that it's right.

I can't load one big texture per level, because many devices don't support textures more than 2048x2048 pixels and my levels require 4096 pixels at least on the one side. Therefore I have to cut big texture into smalls(512x512, 1024x1024), load them using separate thread and render. Picture shows it:

Green rectangle is screen(for example Nexus S with display 800x480)

**Problems:**

1. In case 2 layers I have to keep in memory 4 big textures.
2. I have to constantly load and unload big textures.
3. Additional thread.

If it's not problems then ok :) But it seems that I'm doing something wrong.

# Answer
I think what you're looking for here is a classical example of tile-mapping which allows you to create levels and the like without consuming a LOT of resources. This is how Mario Bros was written along with other countless side-scrolling games are designed. You simply use a map editor such as Tiled (or a home-brew solution) to design your level from a chunked texture such as this:

(Thanks to OpenGameArt for the graphics!).

The background can be done in a similar fashion, just on a separate layer which scrolls slower (see: parallax) or just by ripping parts off the tile sheet. Say, those birds... you can place them in the sky randomly or clouds. However, if your level is to be the same every playthrough it's best to just build them on a separate parallax layer.
> 2 votes

---
Tags: opengl, architecture, rendering, libgdx, mobile
---


# Question
Title: Will a Game written using HTML5 work on smartphones?
I would like to write a game that could be played on smart phones and was wondering if HTML5 might be a way to write games to work on a wide selection of smart phones.

# Answer
I just ran the HTML5 test:

* My iPod Touch 2nd generation with iOS **3.1.3** scores 125 and 7 bonux points out of 300 in Safari. Of particular note to game development:
    + Full points in Canvas! Great for game rendering.
    + Supports the video element with MPEG-4 and H.264 formats
    + Supports the audio element with PCM, MP3 and AAC formats (great for bgm and sounds!)
    + Session and local storages are supported, as is Web SQL Database! (game save files?)
    + Application Cache is supported; I assume this feature would let you cache game data files (images and such) for faster loading. Sounds great to me!
    + No WebGL support.
    + No WebSocket either; multiplayer games will need to use something else like AJAX polling.
* My Droid Incredible with Android OS 2.1 (+ Sense UI) scores 151 and no bonus points out of 300 on its built-in browser. Again, of particular note:
    + Full Canvas support
    + video element supported but all four codecs had X's on them. I wonder what formats it can play?
    + audio element, same thing as video - supported but formats all have X's.
    + Session and local storage and Web SQL Database all supported
    + Application Cache is supported
    + No WebGL or WebSocket
    + Web workers are supported, which were not supported on my iPod; these could be a good thing in game development for things that act in parallel -- perhaps AI?
* *Edit 2011/1/18:* My Droid Incredible now has Android 2.2 and scores a 176 out of 300. Tchalvak (in the comments) got the same score with his Droid 2, so it seems to be common for the Android 2.2 browser. I also tried the Opera Mobile browser which got a terrible 72 (no bonus points) out of 300, but fully supports canvas!

So as you can see, the iPod/iPhone and Android are very much neck-and-neck and seem to support a decent range of HTML5 features. Canvas is great for 2D browser graphics and the audio element would probably be great for playing background sounds and music, and it's also really cool to see that both platforms support storage (though you could always just use cookies of course, depending on the size of a game save). So overall I'd say you should go for it. The numbers aren't everything; as wkerslake said "none of these numbers inspire confidence" but if you look through what is supported, it seems to be everything you need!

I say go for it! I wish you the best of luck.

By the way, you might want to watch for Vanthia. It's a browser game which utilizes canvas for efficient drawing. I got to play the closed beta and it was sure coming along! The developer has said very little for over half a year now, except that he is definitely developing it but just keeping things somewhat secret.

You could also get some ideas from Google's recent Pacman interactive logo. It wasn't very HTML5 but it sure was functional! It shows that you don't actually need HTML5 to make a browser game (and I think HTML5 is being thrown around as a buzzword far too much, just as AJAX was or still is). There is a github project with a deobfuscated, cleaned up version of the source that you can look through and play with.
> 17 votes

# Answer
HTML5 is a long way from being ubiquitously supported even in web browsers on PC much less phones.

These numbers are based on the html5test

* IE8 on PC = 27/300
* Chrome 5.0.375.125 on PC = 197/300
* Safari 4.0.4 on PC = 207/300
* Safari on iPhone4 = 185/300

None of those numbers inspire confidence
> 3 votes

# Answer
It might seem a little late but I'd like to provide an update on the situation for HTML5 and the mobile browsers now that some time has passed. Lately, quite a few game engines have been developed that will produce HTML5 compatible games (see: Construct 2 and Game Maker Studio). Both produce OK performance but there has been notable issues with physics extensions and fast moving objects on some platforms. iOS still takes the lead when it comes to performance but Android has come a long way with the latest Chrome builds. It should be noted that Dolphin Browser on Android totes even 100% increase in HTML5 performance, as well! You can see a quick comparison done for a test below:

If you're looking to do manual optimization, there's some great advice listed here. Also, with HTML5 games becoming increasingly popular and allowed on sites like Kongregate and previously other flash exclusive game portals - there's no reason to be afraid of writing HTML5 based games anymore for a mobile device.

A few libraries exist as well to keep things easy to use on mobile, I've listed a couple below:

KineticJS

EaselJS

QuarkJS
> 3 votes

# Answer
as of July 2012, you can make smooth mobile HTML5 games. Check out this video
> 1 votes

# Answer
From the technical point of view it's certainly doable. There are some problems/pitfalls though:

* There aren't much frameworks out in the open, so you'll have to basically write everything from scratch. From the renderer, to sound-handling, collision-detection. This can be a lot of work, depending on what you're trying to do.
* You'll have to have a really good understanding of JavaScript. Some usual OOP practices won't work when using this Language. It's probably not the best choice for a game with huge amounts of code :)
* Don't forget about performance. Smartphones are far from the performance of a typical Desktop-PC. You'll have to test performance carefully on different devices. It might also depend on the JavaScript-Engine (Browser) that is installed on the device. This isn't a HTML5 only issue of course.
* Try to reduce the bandwidth needed for the game. Mobile-devices tend to have slower connections and sometimes people pay for the bandwidth they use. Try to use caching whenever possible.
> 0 votes

# Answer
Found a good post about iPad and HTML5: http://mir.aculo.us/2010/06/04/making-an-ipad-html5-app-making-it-really-fast/

Also I would avoid heavy canvas drawing on iPad, for some reason it seems to be pretty slow.
> 0 votes

# Answer
You can use PhoneGap Build:

Just upload a **zip file with the HTML5** code and it will give you the application for: Android, iOS, winphone, Blackbarry, Symbian ..ecc..
> 0 votes

---
Tags: html5
---