# Question
Title: Libgdx detect when player is outside of screen
Im trying to learn libGDX (coming from XNA/MonoDevelop), and I'm making a super simple test game to get to know it better. I was wondering how to detect if the player sprite is outside of the screen and make it so it is impossible to go outside of the screen edges.

In XNA you could do something like this:

```
// Prevent player from moving off the left edge of the screen
if (player.Position.X < 0)
    player.Position = new Vector2(0, player.Position.Y);

```

How is this achieved in libgdx? I think it's the Stage that handles the 2D viewport in libgdx?

This is my code so far:

```
private Texture texture;
private SpriteBatch batch;
private Sprite sprite;

@Override
public void create () {
    float w = Gdx.graphics.getWidth();
    float h = Gdx.graphics.getHeight();
    batch = new SpriteBatch();

    texture = new Texture(Gdx.files.internal("player.png"));
    sprite = new Sprite(texture);
    sprite.setPosition(w/2 -sprite.getWidth()/2, h/2 - sprite.getHeight()/2);
}

@Override
public void render () {
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    if(Gdx.input.isKeyPressed(Input.Keys.LEFT)){
        if(Gdx.input.isKeyPressed(Input.Keys.CONTROL_LEFT))
            sprite.translateX(-1f);
        else
            sprite.translateX(-10.0f);
    }
    if(Gdx.input.isKeyPressed(Input.Keys.RIGHT)){
        if(Gdx.input.isKeyPressed(Input.Keys.CONTROL_LEFT))
            sprite.translateX(1f);
        else
            sprite.translateX(10f);
    }

    batch.begin();
    sprite.draw(batch);
    batch.end();
}

```

# Answer
> 3 votes
The most surefire way to do this is to test each frame if the sprite has exceeded the desired boundaries (either physical screen or camera viewport), and if so to clamp them back to the exact boundary. This will prevent any weird bouncing effects from trying to correct the position using an offset, and enable the sprite to collide snugly with the boundaries.

I also come from an XNA background so I made changes along with the code to hopefully make the structure more familiar to you. Anyway, modifying your existing code:

```
private static final float SPEED = 10f; // 10 pixels per second
private static final float SPEED_SLOW = 1f; // 1 pixel per second

private Texture texture;
private SpriteBatch batch;
private Sprite sprite;

@Override
public void create () {
    float w = Gdx.graphics.getWidth();
    float h = Gdx.graphics.getHeight();
    batch = new SpriteBatch();

    texture = new Texture(Gdx.files.internal("player.png"));
    sprite = new Sprite(texture);
    //sprite.setPosition(w/2 -sprite.getWidth()/2, h/2 - sprite.getHeight()/2);

    // Set the origin of the sprite (where its position is relative to) to the center of the sprite.
    // The default origin is the bottom-left corner which is why you were making the adjustment above
    // to make it appear centered.  This also allows the sprite to rotate around its center, scale around
    // its center, etc.
    sprite.setOriginCenter();
    sprite.setPosition(w * .5f, h * .5f);
}

@Override
public void render () {
    final float dt = Gdx.graphics.getDeltaTime();

    update(dt);
    draw();
}

private void update(final float dt)
{
    // Get input for this frame
    final boolean left = Gdx.input.isKeyPressed(Input.Keys.LEFT);
    final boolean right = Gdx.input.isKeyPressed(Input.Keys.RIGHT);
    final boolean up = Gdx.input.isKeyPressed(Input.Keys.UP);
    final boolean down  = Gdx.input.isKeyPressed(Input.Keys.DOWN);
    final boolean slow = Gdx.input.isKeyPressed(Input.Keys.CONTROL_LEFT);

    // Calculate directional speed
    float speedX = slow ? SPEED_SLOW : SPEED;
    speedX *= (left ? -1f : right ? 1f : 0f);
    // Scale by our delta time for smooth movement.  Optional
    speedX *= dt;

    float speedY = slow ? SPEED_SLOW : SPEED;
    speedY *= (down ? -1f : up ? 1f : 0f);
    // Scale by our delta time for smooth movement.  Optional
    speedY *= dt;

    // Move sprite to new position
    sprite.translate(speedX, speedY);

    // Get the bounding rectangle that describes the boundary of our sprite based on position, size, and scale.
    final Rectangle bounds = sprite.getBoundingRectangle();

    // Get the bounding rectangle that our screen.  If using a camera you would create this based on the camera's
    // position and viewport width/height instead.
    final Rectangle screenBounds = new Rectangle(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

    // Sprite
    float left = bounds.getX();
    float bottom = bounds.getY();
    float top = bottom + bounds.getHeight();
    float right = left + bounds.getWidth();

    // Used for adjustments below since our origin is now the center.
    final float halfWidth = bounds.getWidth() * .5f;
    final float halfHeight = bounds.getHeight() * .5f;

    // Screen
    float screenLeft = screenBounds.getX();
    float screenBottom = screenBounds.getY();
    float screenTop = screenBottom + screenBounds.getHeight();
    float screenRight = screenLeft + screenBounds.getWidth();

    // Current position
    float newX = sprite.getX();
    float newY = sprite.getY();

    // Correct horizontal axis
    if(left < screenLeft)
    {
        // Clamp to left
        newX = screenLeft + halfWidth;
    }
    else if(right > screenRight)
    {
        // Clamp to right
        newX = screenRight - halfWidth;
    }

    // Correct vertical axis
    if(bottom < screenBottom)
    {
        // Clamp to bottom
        newY = screenBottom + halfHeight;
    }
    else if(top > screenTop)
    {
        // Clamp to top
        newY = screenTop - halfHeight;
    }

    // Set sprite position.
    sprite.setPosition(newX, newY);
}

private void draw()
{
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    batch.begin();
    sprite.draw(batch);
    batch.end();
}

```

Note this is written off the cuff and untested. Take with a grain of salt and an eye for mistakes. :)

# Answer
> -1 votes
```
add the following conditions:

        if(Gdx.input.isKeyPressed(Input.Keys.LEFT))
    {
            if(Gdx.input.isKeyPressed(Input.Keys.CONTROL_LEFT) && sprite.getX() > 1f)
    {
                sprite.translateX(-1f);
    }
            elseif ( sprite.getX() > 10f)
    {

                sprite.translateX(-10.0f);
    }
}

```

this will prevent the user from getting outside of the screen tell me if you need an explain for the code above.

---
Tags: collision-detection, libgdx, sprites, viewport
---


# Question
Title: Objects disappear when zoomed out in Unity
Ignore the palm trees here.

I have some oak-like trees when I'm zoomed in:

They disappear when I zoom out:

Is this normal? Is this something to do with draw distance? How can I change this so my trees don't disappear?

The reason I ask is because my installation had a weird terrain glitch. If this isn't normal I'm going to reinstall right away because I'm always thinking 'is that a feature? Or a glitch'?

# Answer
> 1 votes
Hmm..maybe I should stop firing off questions.

Try hitting this button if you get into this situation:

Click the terrain, and in the contextual inspector, there is a refresh button (bottom right of this screen shot). Click that if you've updated your trees.

I scaled up my tree mesh because they were tiny. I scaled it up, but the billboards remained tiny ( I mean really tiny) so they can't be seem when you zoom out. When I click refresh, the billboards are re-generated from the larger resized mesh so they stop appearing to disappear

---
Tags: unity
---


title: How can I draw an Xbox Live avatar?

text:
# Question
Title: How can I draw an Xbox Live avatar?
I want to replace the main character of my 2D game by an Xbox avatar. How can I do that? How can I add an avatar to my project? How can I draw an avatar?

For example, I draw my main character like that:

```
spriteBatch.Begin();
  spriteBatch.Draw(Main_Character,Main_Character_Position,Color.White);
spriteBatch.End();

```

What must be changed to draw an avatar?

# Answer
> 2 votes
XNA includes APIs for performing animation and rendering of avatars. To get an avatar into your game, you need to initialize the gamer services component by adding a new instance of `GamerServicesComponent` to your game's component list (typically in your game's constructor):

```
Components.Add(new GamerServicesComponent(this));

```

Then you'll need to get the `AvatarDescription` for the player in question. The method provided to do this is asynchronous (since for remotely-connected gamers, it may involve a download). You'll need the `Gamer` object for the player you want to get the avatar of, then you can do:

```
AvatarDescription.BeginGetFromGamer(gamer, LoadAvatar, null);

```

You must write the `LoadAvatar` function yourself; it should look like this:

```
void LoadAvatar(IAsyncResult result) {
  var description = AvatarDescription.EndGetFromGamer(result);
  if (description.IsValid) {
    // Store the description in a member variable for later access if
    // the retrieval was successful.
    m_description = description;
  }
}

```

(An avatar may be invalid if the player doesn't have one. In that case you may want to fall back to using the gamer's profile picture, which is already available in an easy-to-use format you can turn into a texture.)

Now that you have the avatar data, you can use it with the `AvatarRenderer` class by passing the avatar to the `Draw` method of an `AvatarRenderer`:

```
var renderer = new AvatarRenderer(m_description);
var animation = new AvatarAnimation(AvatarAnimationPreset.Stand0);
renderer.World = // ...an appropriate world matrix...
renderer.View = // ...an appropriate view matrix...
renderer.Projection = // ...an appropriate projection matrix...

renderer.Draw(animation.BoneTransforms, animation.Expression);

```

This will render the avatar into the current render target. If you want to animate the avatar, the `animation` object has an `Update` method you can pass your elapsed game time into. If you just want to capture a single frame and re-use it, you may want to look into setting up a texture render target and rendering via the above into that target once, then drawing that texture as a sprite.

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


# Question
Title: How can I put a Unity3D game on an Xbox 360 disc?
I've made a simple shooter in Unity that I'd like to play on an Xbox 360. Mass production not required, just a one-off game, completely non-profit. Perhaps burning to a DVD?

Is it a relatively simple procedure to burn the game to disc? I have a nasty feeling the Xbox 360 needs to be chipped. Is this the case?

# Answer
> 7 votes
You need a license for that, one from Microsoft and one from Unity.

> Anyone wishing to deploy to Xbox 360 must sign up via an approved publisher such as Microsoft Studios.

**UPDATE**
if you get and independent developer license, you don't pay anything link

Get going with Unity for consoles and Developing Games for Xbox

# Answer
> -4 votes
Considering you aren't interested in licensing, putting the game on one disc shouldn't be hard . It may require a high level dvd disc in order to store your finished game, however, as well as the correct encoding. The encoding should come with Unity's platform abilities.

---
Tags: unity, xbox360
---


title: Unity3D : Retry Menu (Scene Management)

text:
# Question
Title: Unity3D : Retry Menu (Scene Management)
I'm making a simple 2D game for Android using the Unity3D game engine. I created all the levels and everything but I'm stuck at making the game over/retry menu. So far I've been using new scenes as a game over menu. I used this simple script:

```
#pragma strict

var level = Application.LoadLevel;

function OnCollisionEnter(Collision : Collision)
{
    if(Collision.collider.tag == "Player")
    {
        Application.LoadLevel("GameOver");
    }
}

```

And this as a 'menu':

```
#pragma strict

var myGUISkin : GUISkin;

var btnTexture : Texture;

function OnGUI() {
GUI.skin = myGUISkin;

if (GUI.Button(Rect(Screen.width/2-60,Screen.height/2+30,100,40),"Retry"))
    Application.LoadLevel("Easy1");

if (GUI.Button(Rect(Screen.width/2-90,Screen.height/2+100,170,40),"Main Menu"))
    Application.LoadLevel("MainMenu");
}

```

The problem stands at the part where I have to create over 200 game over scenes, obstacles (the objects that kill the player) and recreate the same script over 200 times for each level. Is there any other way to make this faster and less painful?

# Answer
There are several different solutions, but I would recommend using PlayerPrefs. This has the extra benefit of persisting even when the application is closed and then re-opened.

In your Awake() function of your Main Menu class, you can get the current level and store it in a static string of your Main Menu class. If it is the player's 1st time, use the name for level 1.

Something like this:

```
static string currentLevelName;
void Awake()
{
    currentLevelName = PlayerPrefs.GetString("CurrentLevel");
    if (currentLevelName == defaultValue)
    {
       currentLevelName = "Level1"
    }
}

```

Then, modify your button to do this instead:

```
if (GUI.Button(Rect(Screen.width/2-60,Screen.height/2+30,100,40),"Retry"))
    Application.LoadLevel(currentLevelName);

```

Whenever the player advances to the next level, set the string in PlayerPrefs to the new level name:

```
PlayerPrefs.SetString("CurrentLevel", Application.loadedLevelName);

```
> 1 votes

# Answer
Another option would be to make something like a singleton LevelManager MonoBehavior and add it to an object named "Level Manager". Use the DontDestroyOnLoad function to make the object persist even when you load another level.

```
class LevelManager : MonoBehavior
{
    static LevelManager _instance;
    public string currentLevelName;
    public string killedBy;

    function Awake ()
    {
       if (_instance == null)
       {
          _instance = this;
           DontDestroyOnLoad(gameObject);
       }
       else
       {
          Destroy(gameObject); // Make sure we never have more than 1 Level Manager.
       }
    }

    LevelManager Instance
    {
       get
       {
          if (_instance == null)
          {
             GameObject levelManagerObject = GameObject.Find("Level Manager");
             _instance = levelManagerObject.GetComponent<LevelManager>();
          }
          return _instance
       }
    }
}

```

Then, from the main menu class, you can always access the Level Manager like so:

```
Debug.Log("Killed by " + LevelManager.Instance.killedBy);

```

or

```
LevelManager.Instance.currentLevelName = Application.loadedLevelName;

```
> 1 votes

---
Tags: unity, menu
---


# Question
Title: How to optimize a box2d simulation in action game?
I'm working on an action game and i use box2d for physics. The game use a tiled map.

I have different types of body:

* Static ones used for tiles
* Dynamic ones for player and enemies

Actually i tested my game with ~150 bodies and i have a 60fps constantly on my computer but not on my mobile (android). The FPS drop as the number of body increase.

After having profiled the android application, i saw that the `World.step` took around 8ms in CPU time to execute.

Here are few things to note:

1. Not all the world is visible on screen, i use a scrolling system
2. Enemies are constantly moving toward the player so there is alaways to force applied to their body
3. Enemies need to collide between each others
4. Enemies collide with tiles

I also now that i can active/desactive or sleep/awake bodies.

**Considering the fact that only a part of the enemies are possibly displayed on screen, is there any optimizations i can do to reduce the execution time of box2d simulation?**

I found a guy trying an optimization based on distance of enemies from the player (link). But i seems like he just desactives far bodies (in my case, i could desactive bodies that are not visible). But my enemies need to move even when they are not visible on screen, and applying forces will not workd on inactive bodies. **Should i play with sleeping bodies here**?

Also, enemies are composed by two fixtures and are constantly colliding with each others and with tiles but i really never need to get notified about that. Is there anything i can do to optimize this kind of scenario?

Finally, am i wrong to try to run simulation at 60FPS on mobile and should i try to make it run at 30FPS?

# Answer
> 5 votes
Now that I think about it some more, there may be a way.

**Basic Idea**

You say you are using a tile-based map, so you might consider implementing tile-based collision detection far away from the player. Consider the following diagram:

Dashed Lines:

* **Green** Screen Limits (Camera). Everything intersecting or inside this box is on-screen.
* **Red** Box2d Limits. Everything intersecting or inside this box is being updated by box2d.
* **Blue** Gameplay Limits. Everything inside this box is being updated.\*

\*I will refer to the space inside the blue box, but outside the red box as the tile-region.

Entities:

* **Circle** The player. The camera follows the player around (could be always centered on the player's position in the simplest case), but the red and green box always share the same center.
* **Red Shapes** Enemies. Constantly moving towards the player.
* **Black Squares** Obstacle Tiles.

Filled vs. Unfilled:

* **Filled Shapes** Box2d Active. These shapes contain active box2d bodies.
* **Unfilled Shapes** Box2d Inactive.

**Updating**

The key here is to update your enemies in 2 ways: when they are inside the red box, update them as you normally do.

When they are outside the red box (b2body is inactive), update their position discretely. That is, allow them to move to the next tile after a set amount of time (in accordance with the speed they are allowed to move as a box2d body). If you want info on how to do the path-finding, check out these two answers.

To do this you could maintain a list of tile-enemies, and a list of box2d enemies. Then you need to update the list of tile-enemies each turn.

If you are using a an ECS the implementation becomes much clearer: enemies in the tile region have a `TileMove` component. Which looks something like this:

```
TileMove

 - timeOnTile //The amount of time the enemy has spent on the current tile
 - timeToMove //The amount of time required to spend on the current tile before moving again
 - currentDestination //Probably the player
 - currentTile //The tile the enemy occupies

```

The `TileMoveSystem::update` it, or `TileMove::update` code might look like this:

```
timeOnTile += dt
if (timeOnTile >= timeToMove){
    //Decide where to move; probably includes some pathfinding and/or steering behaviours
    oldTile->occupant = NULL //Tell the old tile it's no longer occupied
    newTile->occupant = self //Tell the new tile it's now occupied
    timeOnTile = 0.0;
}

```

**Crossing the Tile Region - Box2d Boundary**

You also need to be able to check if enemies are crossing the red box boundary and decide what to do with them.

*Box2d to Tiled Region* \- On the box2d side, it's pretty easy. I would reccomend making a sensor body that is updated with the camera's position and orientation. The dimensions of the sensor body are the same as the red box. Whenever the `endContact` callback is triggered from the sensor, deactivate the b2body belonging to that entity, and create/restore a `TileMove` component.

*Tiled Region to Box2d* \- Going the other way, you need to do your own area check to see if any of your tiled enemies have entered the red box. This is probably the trickiest bit. My gut feeling is that you should get the AABB of the red box, and query all the tiles (a rectangular sub-region of the global grid) to see if there is an enemy/obstacle that currently occupies each tile. For each entity found with a `tileMove` component, do a narrow phase test to see if it's actually inside the red box.

Alternatively, just make the red box the AABB that's centered with the green box, like in the figure below

In this case there doesn't need to be a narrow phase; every occupied tile in the AABB region will activate its occupant. The drawback here is that there will need to be a few more active enemies than there would be otherwise.

In any case, once you have determined that an entity needs to move back into the box2d region you need to:

* create/restore the `PhysicsBody` component
* Set the transform of the box2d body to the current tile position.
* (re)activate the box2d body
* Remove the `MoveTile` component

**Drawbacks**

First, this means there is a whole other group of objects you have to maintain (the tile-entities). Also, you say you have ~150 bodies in the simulation. There's a lot of changes I've suggested, and the overhead cpu cost of determining when enemies/obstacles are inside/outside the box2d region (and transforming them appropriately) might not give the net performance gain you desire.

What I can say, is that, the more enemies you have in your game, the better this method will perform vs. the pure box2d implementation.

Finally, although I am somewhat uncertain as to the impact it will have on the overall performance, I am confident that this answers your core question: **it will reduce the execution time of the box2d simulation.**

---
Tags: box2d, optimization
---


title: Separate parts of a game engine

text:
# Question
Title: Separate parts of a game engine
I'm pretty new in developing videogames. By now I only used SDL with C/C++ to create games. I'm currently learning OpenGL and I realized that to be fluid and easy to maintain the code must be logically separated. Since I want to use OpenGLES on iOS and Android I was wondering how the engine must be imagined in a technical way, some questions came up:

* **Do I have to separate input/update functions from draw functions in different threads?**
* **Is there only one proper way to think a game engine/loop?**
* **What kind of assets should I use to create a 3D game using openGl ES to get better performance?**

EDIT: I figured that I had more questions lacking of answers reading the links DMGregory refered me to. I'll keep reading it till I fully understand it and than ask for the good questions. Thanks a lot.

# Answer
With regard to engine design, Entity Component Systems are currently very popular. They're not the only way to think about game engines & loops by any means, but many developers have found them to be a useful standard.

The principle of composition over inheritance they emphasize tends to be well-suited to game development for a few reasons:

1. **Flexibility (Non-Brittleness):** When the design changes at the 11th hour in response to playtest data, juggling a few components is often simpler than uprooting a whole inheritance hierarchy.
2. **Code Cleanliness:** (With appropriate discipline...) component classes tend to be smaller, simpler, and have narrower focus & responsibilities than the sprawling Player classes of older games. They're a better fit for the amount of code a human can hold in their mind at a time, making it a bit less easy to create unintended side effects and hard-to-track-down bugs.
3. **Reuse & Remixing:** Composition makes it easy to create new behaviours, by sticking together existing components like LEGO bricks. This is a huge help on larger teams where you have many non-coders who need to tune complex interactions - like a designer refining AI archetypes or an artist creating a new effects sequence. If they can chain together existing components to do it, it removes a dependency on programmer time, letting everyone get more done.

This is also significant for games with **procedually generated** or **user-generated content** \- it creates a useful level of granularity for these systems to work on. Level editing tools
4. **Performance:** This isn't automatic, and it's certainly possible to code an ECS implementation with terrible performance. But if you make it a priority from the ground up, ECS can be made particularly amenable to "data-oriented design", making it easier to support multithreading and data locality for efficient cache usage. It does this by encouraging smaller, single-purpose update functions, operating on batches of contiguous component data, with standardized dependency patterns between components/systems (more on this in the links below).

These articles have been very influential to my thinking about ECS, particularly with regard to structuring for performance:

Component - Game Programming Patterns

Data Locality - Game Programming Patterns

Data Oriented Design - Game Developer Magazine September 2009 (p43, which is 45 in the PDF) and September 2010 (p31, which is 33 in the PDF)

CppCon talks on Data Oriented Design

These resources should give you some good ideas for ways you can create your own systems.
> 0 votes

---
Tags: android, multithreading
---


title: glGetActiveAttrib on Android NDK

text:
# Question
Title: glGetActiveAttrib on Android NDK
In my code-base I need to link the vertex declarations from a mesh to the attributes of a shader. To do this I retrieve all the attribute names after linking the shader. I use the following code (with some added debug info since it's not really working):

```
int shaders[] = { m_ps, m_vs };
if(linkProgram(shaders, 2))
{
    ASSERT(glIsProgram(m_program) == GL_TRUE, "program is invalid");

    int attrCount = 0;
    GL_CHECKED(glGetProgramiv(m_program, GL_ACTIVE_ATTRIBUTES, &attrCount));

    int maxAttrLength = 0;
    GL_CHECKED(glGetProgramiv(m_program, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &maxAttrLength));

    LOG_INFO("shader", "got %d attributes for '%s' (%d) (maxlen: %d)", attrCount, name, m_program, maxAttrLength);

    m_attrs.reserve(attrCount);

    GLsizei attrLength = -1;
    GLint attrSize = -1;
    GLenum attrType = 0;

    char tmp[256];
    for(int i = 0; i < attrCount; i++)
    {
        tmp[0] = 0;
        GL_CHECKED(glGetActiveAttrib(m_program, GLuint(i), sizeof(tmp), &attrLength, &attrSize, &attrType, tmp));
        LOG_INFO("shader", "%d: %d %d '%s'", i, attrLength, attrSize, tmp);
        m_attrs.append(String(tmp, attrLength));
    }
}

```

`GL_CHECKED` is a macro that calls the function and calls `glGetError()` to see if something went wrong. This code works perfectly on Windows 7 using ANGLE and gives this this output:

```
info:shader: got 2 attributes for 'static/simplecolor.glsl' (3) (maxlen: 11)
info:shader: 0: 7 1 'a_Color'
info:shader: 1: 10 1 'a_Position'

```

But on my Nexus 7 (1st gen) I get the following (the errors are the output from the GL\_CHECKED macro):

```
I/testgame:shader(30865): got 2 attributes for 'static/simplecolor.glsl' (3) (maxlen: 11)
E/testgame:gl(30865): 'glGetActiveAttrib(m_program, GLuint(i), sizeof(tmp), &attrLength, &attrSize, &attrType, tmp)' failed: INVALID_VALUE [jni/src/../../../../src/Game/Asset/ShaderAsset.cpp:50]
I/testgame:shader(30865): 0: -1 -1 ''
E/testgame:gl(30865): 'glGetActiveAttrib(m_program, GLuint(i), sizeof(tmp), &attrLength, &attrSize, &attrType, tmp)' failed: INVALID_VALUE [jni/src/../../../../src/Game/Asset/ShaderAsset.cpp:50]
I/testgame:shader(30865): 1: -1 -1 ''

```

I.e. the call to `glGetActiveAttrib` gives me an `INVALID_VALUE`. The opengl docs says this about the possible errors:

> GL\_INVALID\_VALUE is generated if program is not a value generated by OpenGL.

This is not the case, I added an ASSERT to make sure `glIsProgram(m_program) == GL_TRUE`, and it doesn't trigger.

> GL\_INVALID\_OPERATION is generated if program is not a program object.

Different error.

> GL\_INVALID\_VALUE is generated if index is greater than or equal to the number of active attribute variables in program.

`i` is 0 and 1, and the number of active attribute variables are 2, so this isn't the case.

> GL\_INVALID\_VALUE is generated if bufSize is less than 0.

Well, it's not zero, it's 256.

Does anyone have an idea what's causing this? Am I just lucky that it works in ANGLE, or is the nvidia tegra driver wrong?

# Answer
> 0 votes
After lots of trial and error I found that calling `glDetachShader(...)` on the vertex shader before `glGetActiveAttrib(...)` will lead to the results I saw. I can't find anything about this in the docs, so I assume it's implementation specific.

The solution is to get all the data you need before detaching the individual shaders.

---
Tags: android, opengl-es2, ndk
---


title: Sorting for 2D Drawing

text:
# Question
Title: Sorting for 2D Drawing
* I am drawing a game in 2D (isometric)
* My objects have their own arrays. (i.e. Tiles\[\], Objects\[\], Particles\[\], etc)
* I want to have a draw\[\] array to hold anything that will be drawn.
* Because it is 2D, I assume I must prioritise depth over any other sorting or things will look weird.
* My game is turn based so Tiles and Objects won't be changing position every frame. However, Particles probably will.

So I am thinking I can populate the draw\[\] array (probably a vector?) with what is on-screen and have it add/remove object, tile & particle references when I pan the screen or when a tile or object is specifically moved. No idea how often I'm going to have to update for particles right now. I want to do this because my game may have many thousands of objects and I want to iterate through as few as possible when drawing.

I plan to give each element a depth value to sort by.

So, my questions:

1. Does the above method sound like a good way to deal with the actual drawing?
2. What is the most efficient way to sort a vector? Most of the time it wont require efficiency. But for panning the screen it will. And I imagine if I have many particles on screen moving across multiple tiles, it may happen quite often.

For reference, my screen will be drawing about 2,800 objects at any one time. When panning, it will be adding/removing about ~200 elements every second, and each new element will need adding in the correct location based on depth.

# Answer
> 1 votes
What you're describing is called (view frustum) culling and is something that almost everyone has to do. Doing that efficiently on large scenes often requires some sort of tree based approach if you want to do it dynamically in a 3D world, e.g. octree or bounding volumes. In your case you can probably get away with a static 2d grid of the world where each cell contains a list of items that's inside it (an object can be in multiple cells at the same time). Then you can find all the cells that the camera overlaps and only draw those objects.

Unless you've profiled your code and are seeing performance issues with the sorting, I shouldn't worry about it. You will most likely start seeing problems with the amount of draw calls before the sorting becomes an issue. Sorting 2800 floats on my old Core 2 Quad using std::sort takes 0.000182 seconds.

So yes, in general it sounds like a good plan. I would start with doing everything each frame (i.e. find all objects in camera view and sort them) and wait with keeping lists between frames until you really have to. Making sure everything is in sync can be a nightmare.

---
Tags: c++, 2d, vector
---


# Question
Title: Inertia in flight simulation using box2d
I'm trying to simulate flight using box2d and libgdx.

The main problem I am currently experiencing is with inertia: since there is no air, the plane looks like it were drifting.

I wasn't able how to turn off inertia.

I have two ideas:

1. Imitate air resistance by applying force
2. Imitate flight using linear velocity without using any box2d physics

Are any of these two ways correct? Or maybe there is way to turn off inertia?

# Answer
> 2 votes
I would try creating a simulation of all the forces that are applied to an airplane. So collect the forces that you need and apply all of them to the rigidobject. I'm no expert, but I would start with:

* Air resistance as (e.g. `F=-c*v^2` where `c` is some factor and `v` is the velocity). The `c` factor will most likely change based on velocity and orientation of the airplane since the surface is very different because of the wings.
* Engine power applied in the airplane's direction.
* Lift based on velocity.
* Gravity.

Then you'll probably need some fake forces to get around the ones you're missing.

---
Tags: physics, box2d
---


# Question
Title: Is it safe StringToHash() to use in Unity?
I'm currently browsing through the Unity tutorials and saw that they're recommending to use `Animator.StringToHash("some string")` to created *unique ids* for animation properties (see here).

Since I'm a programmer, to me the word "hash" doesn't represents something unique. Like the Java documentation for hashValue() states:

> It is not required that if two objects are unequal \[...\], then calling the hashCode method on each of the two objects must produce distinct integer results.

So, according to this (and my definition of "hash"), *two strings may have the same hash value*. (You can also argue that there are an infinite number of possible strings but only 2^32 possible `int` values.)

**So, is there a possibility that `StringToHash()` will give me an id that actually belongs to another property (than the one I requested the hash for)?**

# Answer
Assuming that the hash function used by StringToHash doesn't have serious bias, the chance of two hashes being alike is one in 4 billion. When you generate a lot of hashes, the chance of a collision gets larger than one would expect (see birthday problem), but when you have 100 different strings, the overall chance of a collision is still at about a million to one.

I assume that you will have less than 100 animation properties. I would also assume that your names are constants and that you have control over the names you choose, so in the unlikely chance that you do get a collision, you could easily change one of the involved names.
> 5 votes

# Answer
Yes there are possible collisions for every hashing algorithm when the amount of information of the hash value is less than the input value. That's a general unavoidable problem.

Depending on the case but generally hashing algorithm are designed to minimize the probability of a collision. I don't know which algorithm Unity3D uses to implement that method, but the collision is very unlikely to happen.

If you have the suspect you have a collision check your hash values (and eventually signal the problem to Unity staff since the algorithm should be robust enough to avoid it, and Mecanim should have internal mechanism to detect that 2 parameters have colliding hashes).
> 3 votes

---
Tags: unity, scripting
---


# Question
Title: How to implement soft edge areas with particles
My game is created using Phaser, but the question itself is engine-agnostic.

In my game I have several environments, essentially polygonal areas that player characters can move into and be affected by. For example ice, fire, poison etc' The graphic element of these areas is the color filled polygon area itself, and particles of the suitable type (in this example ice shards). This is how I'm currently implementing this - with a polygon mask covering a tilesprite with the particle pattern:

The hard edge looks bad. I'd like to improve by doing two things: 1. Making the polygon fill area to have a soft edge, and blend into the background. 2. Have some of the shards go out of the polygon area, so that they are not cut in the middle and the area doesn't have a straight line

for example (mockup):

I think 1 can be achieved with blurring the polygon, but I'm not sure how to go about with 2.

How would you go about implementing this?

# Answer
1.If you want something that's close to your mockup I'd use particles (It doesn't have to be a fully blown particle system).

Render your particles in the form of the polygon on a RenderTexture. Make sure to use additive blending on the particles. The particles inside of the polygon will smoothly blend into each other while the particles on the outside will give the soft edge that you want. (An example of the effect can be watched in this youtube video: Additive Particles Video Now render the RenderTexture onto your main screen and you're done. The RenderTexture is necessary so that the particles don't blend with your background.

You can try to put the triangles directly onto the particle texture and see how this works out. Otherwise render them on top of your "particle soup" as a separate layer.

Created a quick mockup in an updated jsfiddle that looks like this You can find the updated demo here

2.Each particle has a velocity and an origin. When your player touches the polygon, you change each particles velocity proportional to the players velocity. The farther a particle is away from your player, the less it is affected by the players velocity.

The formula to calculate a particles velocity would be something like this:

```
//player.velocity and particle.velocity are vectors
//k is a factor to enhance or weaken the influence of players velocity
var distanceToPlayer = (player.position - particle.position).length();
particle.velocity = particle.velocity + ((k * player.velocity) + particle.velocity) * (1/distanceToPlayer);

```

To calculate the position of the particle you put this in your update method:

```
var speedY = -(springConstant * (particle.position.y - particle.origin.y)) - (dampingFactor * particle.velocity.y);
var speedX = -(springConstant * (particle.position.x - particle.origin.x)) - (dampingFactor * particle.velocity.x);

particle.position.y = particle.position.y + speedY;
particle.position.x = particle.position.x + speedX;

particle.velocity.x = particle.velocity.x + speedX;
particle.velocity.y = particle.velocity.y + speedY;

```

This should give you a "fluid" where each particle swings around its origin when the player stirs the fluid. The springConstant changes how much a particle swings away from its origin and the dampingFactor how fast the particle comes to rest. You may have to tweak the code since its the modified version of a 1d simulation I use in my game.

Now with a demo: Demo Just tweak the 3 constants at the top until the fluid behaves like you want it to.
> 2 votes

# Answer
My thoughts about these two points:

1. You could use shader blur, but that's going to be very expensive. Instead I would draw an extra border of triangles that fade from translucent in the center to transparent at the edges, to simulate the "blur". I've done that in a game of mine and it works pretty well. Here are two screenshots of a rainbow-ish booster in my game.

The outer border has a gradient. In my situation, the border doesn't start at the same opacity as the inner part, but if you set those opacities equal, you will have a nice fade.
2. I would program a particle system and make the particles follow the polygon. By doing so, you don't have to worry about what will happen at the edges. The dynamics of your particle system will make sure that the particles are inside the polygon and evenly distributed. You could try to make the closest particles push each other away, but make it with a lot of "mass" so you have inertia and it looks smooth. To make this thing fast, there are some possibilities, but the big problem is going to be the time complexity of the pushing each other mechanism. If you make each particle push every other particle, you will have O(n^2), which is not good, if you're having for example 100 particles in your system. A good read about how you can optimize this is this presentation of PixelJunk: http://fumufumu.q-games.com/gdc2010/shooterGDC.pdf

A simpler approach would be to connect each particle to three or four other particles when constructing the particle system. Now every particle will only have to push the four other particles it is connected to. However, this approach makes turbulences in your particle system impossible. But this doesn't seem to be a problem, since your current situation uses a static texture. This approach will be O(n) which is great.
> 4 votes

# Answer
The idea i had when reading your post was this one :
• build a set of tiles that you'll use for your areas.
• render the area polygon on a small temporary canvas at the tile resolution (ex : if tiles are 16X16, render at a (16X,16X) lower resolution).
• use that temporary canvas to decide wether to render tiles or not on the main canvas :
if a point is set on the low-res canvas, draw a 'random' tile on the main canvas. if a point is just a neighbor of a set point, draw a 'random' tile at a lower opacity (to make transition) on the main canvas.

I was afraid that lowering resolution would create a block effect, but even with 20X20 tiles, it looks quite good :

Steps for this are : take your polygon :

Draw the polygon at your tile resolution : (!! yes it's the mall red thing).

Then use the imageData of the low-resolution canvas to decide wether to draw a tile or note.
If a pixel is set on the low-res canvas, it means we should draw the tile : pick up a 'random' tile index to choose which tile to draw. That random index should always be the same for a given area/tile.
If a point is empty but next to a filled point, also draw a tile, but with half opacity.

So let's draw the tiles :

For the polygon i just draw several times the polygon, scaling it down, and increasing opacity on each draw (one might use the globalCompositeOperation 'lighter', also ).

Once you add up everything, it gives :

fiddle is here :

http://jsfiddle.net/gamealchemist/T7b4Y/

let me know if this helps.
> 3 votes

# Answer
Just an idea:

In your tile, the "pieces" are about 80px wide at most. I would suggest, making 2 areas. You draw your original polygon, and you make a mockup of it about 80 pixels out from each edge. You then draw your tiles into the bigger polygon.

Then, All "pieces" which have a pixel outside of the inner polygon, and no intersection with the inner polygon you can flood fill them out with transparency.

This is very high level, but I figured I'd share it with you. There's a lot of detail to be determined here.

A crude image to demonstrate:

If the inner black polygon were the original, you would erase all of the polygons with a red dot.
> 1 votes

---
Tags: 2d, graphics, particles, phaser
---


# Question
Title: Loading Wavefront Data into VAO and Render It
I have successfully loaded a triangulated Wavefront (.obj) into 6 vectors, the first 3 vectors contain the locations for vertices, UV coords, and normals. The last three have the indices stored for each of the faces.

I have been looking into using VAO's and VBO's to render, and I'm not quite sure how to load and render the data. One of my biggest concerns is the fact that indexed rendering only allows you to have one array of indices, meaning I somehow have to make all of the first three vectors the same size, the only way I thought of doing this, is to make 3 new vertex's of equal size, and load in the data for each face, but that would completely defeat the purpose of indexing.

Any help would be appreciated.

# Answer
> 1 votes
You need to reindex the mesh, something like this:

```
std::vector<Vector3> positions;
std::vector<int> positionIndices;
std::vector<Vector3> normals;
std::vector<int> normalIndices;

std::vector<Vertex> verts;
std::vector<int> newindices;
for(int i = 0; i < positionIndices.size(); i++)
{
    Vertex v;
    v.pos = positions[positionIndices[i]];
    v.normal = normals[normalIndices[i]];

    auto ipos = verts.begin();
    for(; ipos != verts.end(); ++ipos)
    {
        if(memcmp(&v, &(*ipos), sizeof(v)) == 0)
            break;
    }

    if(ipos == verts.end())
        ipos = verts.insert(ipos, v);

    newindices.push_back((int)std::distance(verts.begin(), ipos));
}

```

I usually do this offline to avoid doing it for every mesh at startup. But if you don't have that many faces it doesn't really matter.

---
Tags: opengl, c++, vertex-arrays, index-buffer, vertex-buffer
---


title: RenderState in XNA 4

text:
# Question
Title: RenderState in XNA 4
I was going through this tutorial for having transparency which can be used to solve my problem here. The code is written in XNA 3 but I'm using XNA 4.

What is the alternative for the following code in XNA 4?

```
device.RenderState.AlphaTestEnable = true;
device.RenderState.AlphaFunction = CompareFunction.GreaterEqual;
device.RenderState.ReferenceAlpha = 200;
device.RenderState.DepthBufferWriteEnable = false;

```

I searched a lot but didn't find anything useful.

# Answer
> 1 votes
You can Alpha test in pixel shader by discarding the pixel if its alpha is below a certain level:

```
clip(color.a<0.1?-1,1);

```

or:

```
if(color.a<0.1)
 discard;

```

These two have the same effect which is discarding the pixel if its alpha is below 0.1. I am not sure what exactly is referencealpha in the renderstate but I am guessing it is an unnormalized alpha value, so 200 would be 200.0/255.0 in pixel shader. You can turn off depth write by:

```
device.DepthStencilState = DepthStencilState.DepthRead;
//device is your GraphicsDevice

```

---
Tags: xna, xna-4.0, graphics, xna3.1
---


# Question
Title: Interpolation using a sprite's previous frame and current frame
**Overview**

I'm currently using a method which has been pointed out to me is extrapolation rather than interolation. As a result, I'm also now looking into the possibility of using another method which is based on a sprite's position at it's last (rendered) frame and it's current one.

Assuming an interpolation value of 0.5 this is, (visually), how I understand it should affect my sprite's position....

**This is how I'm obtaining an inerpolation value:**

```
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++;
   }

   interpolation = (float)(System.currentTimeMillis() + skipTicks - nextGameTick) / (float)skipTicks;
   render(interpolation);
}

```

**I am then applying it like so (in my rendering call):**

```
render(float interpolation) {
    spriteScreenX = (spriteScreenX - spritePreviousX) * interpolation + spritePreviousX;
    spritePreviousX = spriteScreenX; // update and store this for next time
 }

```

**Results**

This unfortunately does nothing to smooth the movement of my sprite. It's pretty much the same as without the interpolation code. I can't get my head around how this is supposed to work and I honestly can't find any decent resources which explain this in any detail.

My understanding of **extrapolation** is that when we arrive at the rendering call, we calculate the time between the last update call and the render call, and then adjust the sprite's position to reflect this time (moving the sprite forward) - And yet, this (**Interpolation**) is moving the sprite back, so how can this produce smooth results?

Any advise on this would be very much appreciated.

**Edit**

I've implemented the code from OriginalDaemon's answer like so:

```
@Override
public void onDrawFrame(GL10 gl) {

    newTime = System.currentTimeMillis()*0.001;
    frameTime = newTime - currentTime;
        if ( frameTime > (dt*25))
            frameTime = (dt*25);
    currentTime = newTime;

        accumulator += frameTime;

        while ( accumulator >= dt )
        {
            SceneManager.getInstance().getCurrentScene().updateLogic();
            previousState = currentState;
                    t += dt;
            accumulator -= dt;

        }

        interpolation = (float) (accumulator / dt);

        render();
}

```

Interpolation values are now being produced between 0 and 1 as expected (similar to how they were in my original loop) - however, the results are the same as my original loop (my original loop allowed frames to skip if they took too long to draw which I think this loop is also doing).

I appear to have made a mistake in my previous logging, it is logging as I would expect it to (interpolated position does appear to be inbetween the previous and current positions) - however, the sprites are most definitely choppy when the render() skipping happens.

**Edit**

I was saving my object's old position during rendering when it should have been saved during logic updating like so:

```
 render(float interpolation) {
    drawSpriteAtX = (spriteScreenX - spritePreviousX) * interpolation + spritePreviousX;
    drawSprite(drawSpriteAtX , spriteScreenY);
 }

updateLogic(){

     spritePreviousX = spriteScreenX; // update and store this for next time
     moveSprite();

}

```

# Answer
Here is an excellent article on the subject.

The final implementation of the game loop here is very clean and clear;

```
double t = 0.0;
double dt = 0.01;

double currentTime = hires_time_in_seconds();
double accumulator = 0.0;

State previous;
State current;

while ( !quit )
{
    double newTime = time();
    double frameTime = newTime - currentTime;
    if ( frameTime > 0.25 )
        frameTime = 0.25;
    currentTime = newTime;

    accumulator += frameTime;

    while ( accumulator >= dt )
    {
        previousState = currentState;
        integrate( currentState, t, dt );
        t += dt;
        accumulator -= dt;
    }

    const double alpha = accumulator / dt;

    State state = currentState * alpha +
        previousState * ( 1.0 - alpha );

    render( state );
}

```

What you have is a flow that is rendering as fast as possible, but always updating in 0.01s windows (which makes it update at 100 fps). If you wanted the while() loop could be augmented to have a loop count so it updates a maximum of n times before drawing but I'd recommend against this.

The most important thing for you here is the "State state = ..." as this is essentially showing how to do the interpolation. Any code to interpolate between the state at the previous frame and the current state should in some way resemble this. For example, if interpolating the x position of the sprite then you use;

```
interpolatedX = currX * alpha + prevX * (1.0 - alpha);

```

If you want you could pass the alpha value through to the render routine so you can perform these interpolations just before rendering.

Keep in mind the alpha value will always be between 0 and 1 as accumulator will be reduced to a value smaller than dt by the above loop. So if you clamp the loop to a maximum number of iterations, don't forget to adjust the alpha value accordingly. I would advise against clamping it though.

## Edit

Had a crack at editing the code in the question. I prefer to do things in seconds so velocities can be expressed as m/s etc. Change the doubles to floats or fixed point if you think it's necessary, but for now I've made it all doubles for simplicity. So I think this should work for you;

```
double t = 0.0;
double dt = 1 / 60;
double currentTime = System.currentTimeMillis() * 0.001;
double accumulator = 0.0;
double newTime;
double frameTime;

@Override
public void onDrawFrame(GL10 gl) {

        newTime = System.currentTimeMillis() * 0.001;
        frameTime = newTime - currentTime;

        if ( frameTime > (dt * 25) ) // allow a maximum of 25 updates before drawing
            frameTime = dt * 25;

        currentTime = newTime;

        accumulator += frameTime;

        while ( accumulator >= dt )
        {
            previousState = currentState; //Do this is the level classes
            SceneManager.getInstance().getCurrentScene().updateLogic(dt);
            t += dt;
            accumulator -= dt;
        }

        double interpolation = accumulator / dt;

        Log.v("NewTag","Interpolation amount: "+interpolation); //Always 0
        Log.v("NewTag","Accumulator amount: "+accumulator);  //Always 0

        state = X * interpolation + previousX * (1.0 - interpolation);

        render(state);

```
> 2 votes

# Answer
EDIT: This whole question was rewritten after I discovered that I had misunderstood the original question.

The definite resource on the subject is this article: http://koonsolo.com/news/dewitters-gameloop

Based on advice from that, my approach was based on an accumulator member variable where each call to render() would add the time since last render() in fractional seconds and then call update() in a loop removing a constant amount of time for each until the accumulator was below 0.0;

Untested example code:

```
private float lastTime=(float)System.currentTimeMillis()/1000.0f;
private float accumulator=0.0f;
private final float RESOLUTION=1.0f/100; //constant step time for update in fractions of a second.

public void onDrawFrame(GL10 gl) {
    final float now=(float)System.currentTimeMillis()/1000.0f;
    final float interval=now-lastTime;
    accumulator+=interval;
    while(accumulator>0.0f){
       SceneManager.getInstance().getCurrentScene().updateLogic(RESOLUTION);
       accumulator-=RESOLUTION;
    }
    render(interval);
    lastTime=now;
 }

```

Also, you want to look into swap interval or vsync. Android exposes the native refreshrate for the screen(s) through some API that I can't remember. By enabling this you will avoid spending resources rendering frames that will never be drawn to screen. You will also avoid tearing and other artifacts.
> 0 votes

# Answer
It has come to my attention that nobody has taken notice that in the Gaffer "fixed timestep" method tutorial's sourcecode he actually uses a "rk4 intergrator". The math shown in this question, is Euler intergration.

A different intergrator is required because the rendering can only be precise in Euler intergration if it truly recieves a fixed timestep, this, is not the case with the game loop being shown. Hence, also causing objects to "stutter" or to move further than intended. (Physics engines such as Box2D etc, do this by default I believe, and thus preventing the choppy movement.)

For further info, about Game Physics intergrators, here is a link to an article also written by Gaffer, which uses RK4 intergrator as an example.
> 0 votes

---
Tags: java, android, movement, interpolation, extrapolation
---


# Question
Title: Load previous (last) scene used in unity3d
Im making a 2D game for android and I made over 200 levels/scenes.I also made a game over scene that opens when the players collides with an obscale.In the GameOver scene I added a retry button which I wanna make it so it opens the last level played.Im new in Unity and scripting.I've read other similar questions but none of them fixed my issue.Anyone has any idea that could help ? Im doing this because I don't wanna create over 200 game over scenes and edit each obscale in game.

Thank you.

Edit : Im using javascript.

# Answer
> 2 votes
You have plenty of options, and it really just depends on what your style is and the design of your game.

One of the easier ways to handle this is with a simple scene manager. The first thing you need for scene manager is a script that persists between scenes. This can be done with a method called `DontDestroyOnLoad`. A very simple scene manager would look something like this (written in C#, because that's what I use, but it should be easy enough to convert):

```
public class SceneManager: MonoBehaviour {

    static string lastScene;
    static string currentScene;

    void Awake () {
        DontDestroyOnLoad (this.transform.gameObject);
    }

    public static void ChangeScene(string sceneName) {
        lastScene = currentScene;
        currentScene = sceneName;
        Application.LoadLevel(currentScene);
    }

    public static void LoadLastScene() {
        string last = lastScene;
        lastScene = currentScene;
        currentScene = last;
        Application.LoadLevel(currentScene);
    }

}

```

Next, simply attach your script to an empty game object, and make sure that scene manager game object is created in the first scene. Then, just use the scene manager to handle all your scene changes, and you'll easily be able to go back a level.

---
Tags: android, unity, scene
---


# Question
Title: Best way to store a large amount of game objects and update the ones onscreen
Good afternoon guys! I'm a young beginner game developer working on my first large scale game project and I've run into a situation where I'm not quite sure what the best solution may be (if there is a lone solution). The question may be vague (if anyone can think of a better title after having read the question, please edit it) or broad but I'm not quite sure what to do and I thought it would help just to discuss the problem with people more educated in the field.

Before we get started, here are some of the questions I've looked at for help in the past:

1. Best way to keep track of game objects
2. Elegant way to simulate large amounts of entities within a game world
3. What is the most efficient container to store dynamic game objects in?

I've also read articles about different data structures commonly used in games to store game objects such as this one about slot maps, but none of them are really what I'm looking for. Also, if it helps at all I'm using Python 3 to design the game. It has to be Python 3, if I could I would use C++ or Unityscript or something else, but I'm restricted to having to use Python 3.

My game will be a form of side scroller shooter game. In said game the player will traverse large rooms with large amounts of enemies and other game objects to update (think some of the larger areas in Cave Story or Iji). The player obviously can't see the entire room all at once, so there is a viewport that follows the player around and renders only a selection of the room and the game objects that it contains. This is not a foreign concept.

The part that's getting me confused has to do with how certain game objects are updated. Some of them are to be updated constantly, regardless of whether or not they can be seen. Other objects however are only to be updated when they are onscreen (for example, an enemy would only be updated to react to the player when it is onscreen or when it is in a certain range of the screen).

Another problem is that game objects have to be easily referable by other game objects; something that happens in the player's update() method may affect another object in the world.

Collision detection in games is always a serious problem. I need a way of containing the game objects such that it minimizes the number of cases when testing for collisions against one another.

The final problem is that of creating and destroying game objects. I think this problem is pretty self explanatory.

To store the game objects then I've considered a number of different methods. The original method I had was to simply store all the objects in a hash table by an id. This method was simple, and decently fast as it allows all the objects to be looked up in O(1) complexity, and also allows them to be deleted fairly easily. Hash collisions would not be a major problem; I wasn't originally planning on using computer generated ids to store the game objects I was going to rely on them all using ids given to them by the game designer (such names would be strings like 'Player' or 'EnemyWeapon4'), and even if I did use computer generated ids, if I used a decent hashing algorithm then the chances of collisions would be around 1 in 4 billion.

The problem with using a hash table however is that it is inefficient in checking to see what objects are in range of the viewport. Considering the fact that certain game objects move (as well as the viewport itself), the only solution I could think of in order to only update objects that are in the viewport would be to iterate through every object in the hash table and check if it is in the viewport or not, updating only the ones that are in the valid area. This would be incredibly slow in scenarios where the amount of game objects exceeds 500, or even 200.

The second solution was to store everything in a 2-d list. The world is partitioned up into cells (a tilemap essentially), where each cell or tile is the same size and is square. Each cell would contain a list of the game objects that are currently occupying it (each game object would be inserted into a cell depending on the center of the object's collision mask).

A 2-d list would allow me to take the top-left and bottom-right corners of the viewport and easily grab a rectangular area of the grid containing only the cells containing entities that are in valid range to be updated. This method also solves the problem of collision detection; when I take an entity I can find the cell that it is currently in, then check only against entities in it's cell and the 8 cells around it.

One problem with this system however is that it prohibits easy lookup of game objects. One solution I had would be to simultaneously keep a hash table that would contain all the positions of the objects in the 2-d list indexed by the id of said object.

The major problem with a 2-d list is that it would need to be rebuilt every single game frame (along with the hash table of object positions), which may be a serious detriment to game speed.

Both systems have ups and downs and seem to solve some of each other's problems, however using them both together doesn't seem like the best solution either.

If anyone has any thoughts, ideas, suggestions, comments, opinions or solutions on new data structures or better implementations of the existing data structures I have in mind, please post, any and all criticism and help is welcome.

Thanks in advance!

**EDIT:** Please don't close the question because it has a bad title, I'm just bad with names!

# Answer
This is a pretty big question and I think you might be better served by asking each part separately.

That said, two of your points (viewport and collision) are essentially about accessing "nearby" objects efficiently. The way to do this is to use some kind of *spatial data structure* (aka *spatial index*).

The simplest one is to have a two-dimensional array (if your world is two-dimensional), where each array element corresponds to a 'tile' or 'chunk' of the world (divide world coordinates by tile size to get an array index) and is a list of every object which intersects that tile. (Note that an object may therefore be listed in multiple tiles.) Your objects also store their locations and sizes, and any time that changes, you remove the object from the old positions in the array and add it to the new ones.

(That last part is key: the information is stored in two ways (in the object, and in which parts of the array have the object) and *kept in exact synchronization*. This is an important general technique for allowing different operations to both be efficient, and it is why we call the data structure an *index*: it stores no new information, but allows getting an answer to a specific question efficiently.)

More complex data structures such as *quad trees* avoid establishing a fixed chunk size (so you don't slow down due to lots of objects in a small space or waste memory for few objects in a big space).

A lot has been written on these topics; I hope this answer gives you the keywords you need to learn more.
> 2 votes

---
Tags: architecture, python, data-structure, gameobject, storage
---


title: Applying textures to 3D models

text:
# Question
Title: Applying textures to 3D models
I want to apply textures to a 3D `Model` in XNA 4.

Whatever I saw on the internet was to apply the textures in the modeling tool and then load the model (\*.fbx) into XNA. Is it possible to load the `Model` into XNA game first and then apply the `Texture` into its `Meshes` somehow?

# Answer
> 1 votes
Sure, you have to set it to a shader which you draw your model with. If it is a hand-written shader then you have to set it tothe shader:

```
Texture2D texture;
Effect ef;
ef.Parameters["xTexture0"].SetValue(texture);

```

Specify a Texture in it and a sampler, for example:

```
Texture xTexture0;
sampler TextureSampler0 = sampler_state {
                                        texture = <xTexture0>;
                                        magfilter = anisotropic;
                                        minfilter = anisotropic;
                                        mipfilter = linear;
                                        AddressU = wrap;
                                        AddressV = wrap;
                                       };

```

Then sample it:

```
float4 color = tex2D(TextureSampler0, coordinates);
//coordinates is a float2 for a 2D texture, but float3 for a cubemap

```

If you want to use it with an XNA effect (Basiceffect for example) then you just have to set it before drawing to that effect:

```
Texture2D texture;
BasicEffect ef;
ef.Texture=texture;
ef.TextureEnabled=true;

```

Please note that normally you will have to have texture coordinates specified in your model file to use textures this way, except if you are using projective texturing.

---
Tags: xna, textures, xna-4.0, models, 3d-meshes
---


title: NVidia control panel SSAO not working

text:
# Question
Title: NVidia control panel SSAO not working
I am just before implementing screen space ambient occlusion in my game, but first I wanted to try enabling it from NVidia control panel only to find out that it is greyed out so that I can not enable it. With this I could enable SSAO for some other games, but not every one. I know this technique requires the depth buffer and (optionally) a normal map texture to sample information from which I already have access to given I have a deferred renderer working.
After that I actually thought to roll back to a previous version of my game which still uses forward rendering so the depth buffer is actually bound to the backbuffer which I render to from the get-go so that maybe the NVidia control panel would somehow make use of it. It was not working with forward rendering either. (I also tried FXAA in the control panel and that works - but it doesn't need any depth or normal texture)
So my question is that how can I enable this function so that it would work by enabling it in the NVidia control panel?

# Answer
I've never seen an SSAO option in the NV control panel. Does it only show up for specific games? If so, it's probably something that NV collaborated with the developer on, perhaps integrating NV's HBAO filter into the game.

The NV driver can't just insert SSAO in any old game, because SSAO has to go in the middle of the frame, and the game's lighting shaders have to factor in the SSAO value, etc. The driver can't magically figure out all that for any arbitrary game. FXAA, in contrast, is just one extra pass at the end, which the driver can easily do by just hooking the Present() call. (Even then, it's not perfect, since it blurs the game's UI. It's better for the game to include AA itself.)
> 2 votes

---
Tags: nvidia
---


# Question
Title: Why do the order of uniforms gets changed by the compiler?
I have the following shader, everything works fine when setting the value of one of the matrices but I've discovered that getting a value back is incorrect for `View` and `Projection`, they are in reverse order.

```
#version 430

precision highp float;

layout (location = 0) uniform mat4 Model;
layout (location = 1) uniform mat4 View;
layout (location = 2) uniform mat4 Projection;

layout (location = 0) in vec3 in_position;
layout (location = 1) in vec4 in_color;
out vec4 out_color;

void main(void)
{
    gl_Position = Projection * View * Model * vec4(in_position, 1.0);
    out_color = in_color;
}

```

When querying their location they are effectively reversed, I did a small test by renaming `View` to `Piew` which puts it before `Projection` if sorted alphabetically and the order is correct.

Now if I do remove `layout (location = ...)` from the uniforms, the problem disappears !?

I am starting to think that this is a driver bug as explained in the wiki.

Do you know why the order of the uniforms is changed whenever the shader is compiled ?

(using an AMD HD7850)

# Answer
> 1 votes
When you specify `layout (location = x)`, the compiler is supposed to respect that absolutely. It should not be changing the uniform locations as long as your specified layout is valid.

If you're absolutely sure it's not your fault (double-check you're not re-using any locations across all active shader stages, for instance), then it does sound like a driver bug. Make sure you're using the latest drivers, then if it persists, it would be good to report it to AMD.

---
Tags: glsl, sorting
---


title: Constrained A* problem

text:
# Question
Title: Constrained A* problem
I've got a little problem with an A\* algorithm that I need to Constrained a little bit.

Basically : I use an A\* to find the shortest path between 2 randomly placed room in 3D space, and then build a corridor between them. The problem I found is that sometimes it makes chimney like corridors that are not ideal, so I constrict the A\* so that if the last movement was up or down, you go sideways.

Everything is fine, but in some corner cases, it fails to find a path (when there is obviously one).

Like here between the blue and red dot :

(i'm in unity btw, but i don't think it matters)

Here is the code of the actual A\* (a bit long, and some redundency)

```
while(current != goal)
    {
        //add stair up / stair down
        foreach(Node<GridUnit> test in current.Neighbors)
        {
            if(!test.Data.empty && test != goal) continue;
            //bug at arrival;
            if(test == goal && penul !=null)
            {
                Vector3 currentDiff = current.Data.bounds.center - test.Data.bounds.center;
                if(!Mathf.Approximately(currentDiff.y,0))
                {
                    //wanna drop on the last
                    if(!coplanar(test.Data.bounds.center,current.Data.bounds.center,current.Data.parentUnit.bounds.center,to.Data.bounds.center))
                    {
                        continue;
                    }
                    else
                    {
                        if(Mathf.Approximately(to.Data.bounds.center.x, current.Data.parentUnit.bounds.center.x) &&
                           Mathf.Approximately(to.Data.bounds.center.z, current.Data.parentUnit.bounds.center.z))
                        {
                            continue;
                        }
                    }
                }
            }
            if(current.Data.parentUnit != null)
            {
                Vector3 previousDiff = current.Data.parentUnit.bounds.center - current.Data.bounds.center;
                Vector3 currentDiff = current.Data.bounds.center - test.Data.bounds.center;

                if(!Mathf.Approximately(previousDiff.y,0))
                {
                    if(!Mathf.Approximately(currentDiff.y,0))
                    {
                        //you wanna drop now :
                        continue;
                    }
                    if(current.Data.parentUnit.parentUnit != null)
                    {
                        if(!coplanar(test.Data.bounds.center,current.Data.bounds.center,current.Data.parentUnit.bounds.center,current.Data.parentUnit.parentUnit.bounds.center))
                        {
                            continue;
                        }else
                        {
                            if(Mathf.Approximately(test.Data.bounds.center.x, current.Data.parentUnit.parentUnit.bounds.center.x) &&
                               Mathf.Approximately(test.Data.bounds.center.z, current.Data.parentUnit.parentUnit.bounds.center.z))
                            {
                                continue;
                            }
                        }
                    }
                }

            }
            g = current.Data.g + HEURISTIC(current.Data,test.Data);
            h = HEURISTIC(test.Data,goal.Data);
            f = g + h;
            if(open.Contains(test) || closed.Contains(test))
            {
                if(test.Data.f > f)
                {
                    //found a shorter path going passing through that point
                    test.Data.f = f;
                    test.Data.g = g;
                    test.Data.h = h;
                    test.Data.parentUnit = current.Data;
                }
            }
            else
            {
                //jamais rencontré
                test.Data.f = f;
                test.Data.h = h;
                test.Data.g = g;
                test.Data.parentUnit = current.Data;
                open.Add(test);

            }
        }
        closed.Add (current);
        if(open.Count == 0)
        {
            Debug.Log("nothingfound");
            //nothing more to test no path found, stay to from;
            List<GridUnit> r = new List<GridUnit>();
            r.Add(from.Data);
            return r;
        }

        //sort open from small to biggest travel cost
        open.Sort(delegate(Node<GridUnit> x, Node<GridUnit> y) {
            return (int)(x.Data.f-y.Data.f);
        });
        //get the smallest travel cost node;
        Node<GridUnit> smallest = open[0];
        current = smallest;
        open.RemoveAt(0);
    }

    //build the path going backward;
    List<GridUnit> ret = new List<GridUnit>();

    if(penul != null)
    {
        ret.Insert(0,to.Data);
    }
    GridUnit cur = goal.Data;
    ret.Insert(0,cur);

    do{
        cur = cur.parentUnit;
        ret.Insert(0,cur);
    } while(cur != from.Data);

    return ret;

```

You see at the start of the foreach i constrict the A\* like i said.

If you have any insight it would be cool.

Thanks

# Answer
> 1 votes
It might be useful to just weight against undesirable characteristics as part of the path's score. Your current approach means you can't pathfind through actual chimneys, for example.

What if, say, you used the longest single direction run as a tiny penalty against the cost? Say, one millionth times the actual run length. Your pathfinder will then do diagonal lines to minimize the length of the single longest run in a best path, but with paths under a half million cells in length it's guaranteed to never have incentive to deviate from an actual best path.

The key understanding here, in my opinion, is that there are *many* best paths of matching lengths, and if you can get A\*'s heuristic to actually measure which paths are more desirable, it will find the one you want without any hoop jumping at all.

---
Tags: unity, path-finding, bug
---


# Question
Title: How do I draw text once a countdown ends?
I created a countdown in *Game Maker* using a variable of time. The countdown works properly and is displayed at the proper coordinates. However, when the countdown reaches zero, I want to make the countdown disappear and display "GO" instead.

How can I do that?

# Answer
The simple way to do this is to have two objects and then use instance\_change() two swap into the next object when the countdown finishes.

**Example:**

```
if (countdown <= 0) {
    instance_change(obj_go, true);
}

```
> 2 votes

---
Tags: software-engineering, timer, game-maker, text
---


# Question
Title: How to move an object using X and Y coordinates in JavaScript
I am making a 2d baseball game with JavaScript and HTML5 and am trying to move an image that I have drawn with JavaScript like so:

```
    //canvas
    var c = document.getElementById("gameCanvas");
    var ctx = c.getContext("2d");
    //baseball
    var baseball = new Image();
    baseball.onload = function() {
        ctx.drawImage(baseball, 400, 425);
    };
    baseball.src = "baseball2.png";

```

I'm not sure how I would move it though, I have seen many people seem to just type something like `ballX` and `ballY` but I don't understand where the actual x and y definition comes from. Here is my code so far:

http://jsfiddle.net/xRfua/

I have a different image source but it is a local source so I didn't include it. Thanks in advance for any help at all!

# Answer
> 2 votes
One reasonable approach would be to use a `requestAnimationFrame` loop to update your X and Y, and draw again repeatedly. This would involve computing delta time, and using it to animate your coordinates. Here's an example jsfiddle:

```
//canvas
var c = document.getElementById("gameCanvas");
var ctx = c.getContext("2d");
//baseball
var baseball = new Image();

var drawFunc = function() {
    //do animation logic
    updateBall();

    //draw new stuff
    ctx.clearRect(0, 0, c.width, c.height);
    ctx.drawImage(baseball, baseballX, baseballY);

    //wait for next frame
    //requestAnimationFrame(drawFunc);

    //because the web is annoying, here's a hack to make it work
    if (window.requestAnimationFrame) {
        requestAnimationFrame(drawFunc);
    } else if (window.webkitRequestAnimationFrame) {
        webkitRequestAnimationFrame(drawFunc);
    } else if (window.mozRequestAnimationFrame) {
        mozRequestAnimationFrame(drawFunc);
    }
};

baseball.onload = function() {
    drawFunc();
};
baseball.src = "http://a3.mzstatic.com/us/r30/Purple6/v4/aa/65/fe/aa65fe9a-9a78-2abb-567c-d439c782d9c8/mzl.xwveiniy.175x175-75.jpg";

//ball movement
var baseballX = 0;
var baseballY = 0;
var lastTime = new Date().getTime();
var speed = 0.25;

var updateBall = function() {
    //calculate time passed
    var rightNow = new Date().getTime();
    var elapsedTime = rightNow - lastTime;
    lastTime = rightNow;

    //animate
    baseballX += speed * elapsedTime;
    if (baseballX>300) baseballX = 0;

    baseballY += speed * elapsedTime;
    if (baseballY>425) baseballY = 0;
}

```

---

A less effective, but simpler, approach would be to use a fixed timestep. This can be achieved with a function like `setInterval` or `setTimeout`. Be warned there are issues with these routes: `setInterval` might create a queue of frames to draw faster than they can be pushed. `setTimeout` might leave you waiting too long for your next frame. With that said, here is another example jsfiddle

```
// main changes only
...
baseball.onload = function() {
    setInterval(drawFunc, 1000/fps);
};
...
//ball movement
var baseballX = 0;
var baseballY = 0;
var fps = 48;
var speed = 0.25;

var updateBall = function() {
    //calculate time passed
    var elapsedTime = 1000 / fps;
...

```

---

EDIT: and just for completeness, an example showing the css 3 transitions method

```
.loading {
    transition: 1s all;
    -webkit-transition: 1s all;
    -moz-transition: 1s all;
    position: absolute;
    top: 0px;
    left: 0px;
}

.animated {
    top: 250px;
    left: 300px;
}

```

# Answer
> 1 votes
MickLH's answer was the right one, but your response was "is there a way I could do it without using the time?"

And yes, hilariously, there is. Use CSS to set your locations, and set a transition. This would be a very bad idea for most games; keeping animations in sync this way would be a huge pain in the ass, and since you said baseball, you're very likely in that group. You should do it MickLH's way.

But if you're doing something where sync doesn't matter, like a board or card game, then this is the hella easy way.

Made you something to look at: https://github.com/StoneCypher/chessboard\_html

Or, I gather some people prefer codepens: http://codepen.io/StoneCypher/pen/taKsk

Note that we have nice smooth implicit animation, no tracking of time or state of any kind, and in fact essentially no javascript to speak of other than updating the properties.

---
Tags: 2d, javascript, html5, movement, html-canvas
---


# Question
Title: Version Not Final, Does Not Represent Actual Game Footage?
Just curious about this. Frequently, a lot of gameplay videos from big studios have small subtitled text at the lower part of the screen, reading something like:

* Pre-Alpha Gameplay -- Footage not Final
* Game Footage not Final
* Pre-Alpha, Game here is not final

Is there some sort of reason they do this? Is there some sort of legal ramification that they need to go through by adding this? I have especially seen some gameplay vids whose titles are "Alpha x.x.x", yet still, in the video itself, it always something like "footage not final, game may change".

# Answer
The final shipped game generally looks better than the earliest footage, but our audiences aren't always sensitive to that when evaluating early peeks at a game. These lines aren't legal protection so much as a gesture to temper the "this game looks like shit" reaction.

By overlaying it on the frame, they ensure that if any secondary source - like a video blogger or gaming news outlet - later repackages the old footage (after newer, shinier stuff is available, or after release), that it won't be confused with gameplay in the shipped game, leading to a skewed perception of its visual quality.

On the other hand, many game companies enhance promotional material to fake certain features the product doesn't have yet. Examples are:

* Recording gameplay videos on extremely high graphic settings even the best systems can only render as a slideshow, and then fake a fluent framerate by running the game engine in slow-motion and speeding up the finished video. The assumption is that when the game is finally released, the graphic engine will be more optimized and graphics hardware will have evolved so fluent gameplay is possible on that quality level.
* Digitally enhancing screenshots and videos to add graphic effects the graphic engine doesn't do yet but which are planned to be added.
* Pre-scripting and staging gameplay events which are supposed to be procedurally generated in the final version.

However, there is always a risk that these features will never make it into the finished game because of time and budget constraints or simply because they don't work out as expected. A "Not the final version" disclaimer protects the company from false advertising claims in this case.
> 4 votes

---
Tags: legal, publishing, trailer
---


# Question
Title: how to design transparent screen in libgdx
this question is for LibGdx geeks. I want to make transparent screen in my game. For example, when level completes I want a new transparent screen pop up and show player's high score, buttons to navigate on next level etc like in angry birds kind of screen.

This type of screen can also use, when user click on pause button, to show pause screen. Please guide me to design this kind of screen.

Or if I am going wrong to make transparent screens for this kind of situation. Please guide me for better one.

# Answer
I use a screen stack system to handle this kind of thing. Think of your screens as objects containing individual update and render logic that can be stacked on top of each other. These screens are then updated top -\> bottom so that the most recent screen always has control. They are rendered bottom -\> top so that overlays (pause screens/transparent screens as you say) and other effects can be implemented.

I do this using two classes:

ScreenService.java (handles individual screen objects):

```
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.utils.Disposable;
import org.jetbrains.annotations.NotNull;

import java.util.Stack;

/**
 * The screen service class.
 */
public class ScreenService implements Disposable {
    private final Stack<Screen> screenStack;

    /**
     * Constructs a ScreenService instance.
     */
    public ScreenService() {
        screenStack = new Stack<>();
    }

    /**
     * Adds the specified screen to the service.
     *
     * @param screen
     *         The screen.
     */
    public void add(@NotNull final Screen screen) {
        screen.create();
        screen.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        screenStack.push(screen);
    }

    /** Releases all resources of this object. */
    @Override public void dispose() {
        for(Screen screen : screenStack) {
            if(screen == null) continue;
            screen.dispose();
        }
        screenStack.clear();
    }

    /**
     * Draws all screens in the service.
     */
    public void draw() {
        for(Screen screen : screenStack) {
            if(screen == null) continue;
            screen.draw();
        }
    }

    /**
     * Pauses all screens in the service.
     */
    public void pause() {
        for(Screen screen : screenStack) {
            if(screen == null) continue;
            screen.pause();
        }
    }

    /**
     * Called when the game window is resized.
     *
     * @param width
     *         The new game window width (in pixels).
     * @param height
     *         The new game window height (in pixels).
     */
    public void resize(final int width, final int height) {
        for(Screen screen : screenStack) {
            if(screen == null) continue;
            screen.resize(width, height);
        }
    }

    /**
     * Resumes all screens in the service.
     */
    public void resume() {
        for(Screen screen : screenStack) {
            if(screen == null) continue;
            screen.resume();
        }
    }

    /**
     * Updates the screen service.
     *
     * @param tt
     *         The total amount of time, in seconds, since the game started.
     * @param dt
     *         The total amount of time, in seconds, since the last update.
     */
    public void update(final float tt, final float dt) {
        boolean coveredByOtherScreen = false;
        for(int i = screenStack.size() - 1; i >= 0; i--) {
            Screen screen = screenStack.get(i);
            if(screen == null) {
                screenStack.remove(i);
                continue;
            }
            screen.update(tt, dt);
            if(coveredByOtherScreen) remove(screen);
            if(!screen.isOverlay()) coveredByOtherScreen = true;
        }
    }

    /**
     * Removes the specified screen from the service.
     *
     * @param screen
     *         The screen.
     */
    private void remove(@NotNull final Screen screen) {
        screen.dispose();
        screenStack.remove(screen);
    }
}

```

Screen.java (implements individual screen logic):

```
import com.badlogic.gdx.utils.Disposable;
import com.spacehorde.util.GameServices;
import org.jetbrains.annotations.NotNull;

/**
 * An abstract screen class.
 */
public abstract class Screen implements Disposable {
    private final GameServices gameServices;

    /**
     * Constructs a Screen instance.
     */
    protected Screen(@NotNull final GameServices gameServices) {
        this.gameServices = gameServices;
    }

    /**
     * Called when the screen is created.  Used for initialization.
     */
    protected void create() { }

    /**
     * Draws the screen.
     */
    protected abstract void draw();

    /**
     * Gets the game services.
     *
     * @return The game services.
     */
    protected GameServices getGameServices() {
        return gameServices;
    }

    /**
     * Determines if the screen is an overlay or not.  Overlays will not cause screens below it to automatically exit.
     *
     * @return {@code true} if the screen is an overlay; otherwise, {@code false}.
     */
    protected abstract boolean isOverlay();

    /**
     * Pauses the screen.
     */
    protected void pause() { }

    /**
     * Called when the screen is resized.
     *
     * @param width
     *         The new game window width (in pixels).
     * @param height
     *         The new game window height (in pixels).
     */
    protected void resize(final int width, final int height) { }

    /**
     * Resumes the screen after a pause.
     */
    protected void resume() { }

    /**
     * Updates the screen.
     *
     * @param tt
     *         The total amount of time, in seconds, since the game started.
     * @param dt
     *         The total amount of time, in seconds, since the last update.
     */
    protected abstract void update(final float tt, final float dt);
}

```
> 3 votes

# Answer
In the same situation, I've used an ad-hoc game state interface encased in a `Screen` subclass. This approach is somewhat Lispy in that `GameState` objects are very small inner classes using a lot of outer class stuff.

```
    // This is all inside a Screen implementation...

    interface GameState {
            void draw();
            void update(float delta);
    }

    GameState state;

    // And the four states for this example tetris:

    class PausedState implements GameState {
            GameState returnState;
            public PausedState(GameState returnState){
                    this.returnState = returnState;
            }

            public void draw(){
                    returnState.draw();

                    // Draw an overlay...
                    batch.draw(pause_sprite, 0, 0);
            }

            public void update(float delta){
                    // Note 'touched' and 'state' are outer class stuff.
                    if(touched(Assets.pauseResume)){
                            state = returnState;
                    }

                    // et cetera
            }
    }

    class GameOverState implements GameState {
            // Elided, much of the same as PauseState
    }

    class PieceState implements GameState {
            boolean[][] piece = popPiece();

            // et cetera, much of the gameplay is in here
    }

    class ClearingState implements GameState {
            // animated row removal...
    }

    @Override
    public void render(float delta) {
            // set up common drawing stuff....

            state.draw();
            state.update(delta);

            // and tear down drawing stuff.
    }

```

The intended virtues of this approach are that there is never any "nonsense" state and there is also very little code here versus typical approaches. (The "final" product contains most of the game in this file and it's under 500 lines.) For a very complex game, you might want something designed to split across classes more elegantly (e.g. deadpixelsociety's approach).
> 0 votes

# Answer
Just make a panel and add component such as label to that panel. Then, show this panel on the top! In other words, draw this panel last. (Thank you @Heckel!)
> 0 votes

---
Tags: java, libgdx, transparency, screen
---


title: Bouncing ball slowing down over time

text:
# Question
Title: Bouncing ball slowing down over time
I use the unreal engine 4 to bounce a ball off of walls in a 2D space, but over time the ball gets slower and slower.

Movement happens in the tick function of the ball

```
FVector location = GetActorLocation();

location.X += this->Velocity.X * DeltaSeconds;
location.Y += this->Velocity.Y * DeltaSeconds;

SetActorLocation(location, true);

```

When a wall gets hit I get a Hit Event with the normal of the collision. This is how I calculate the new velocity of the ball:

```
FVector2D V = this->Velocity;
FVector2D N = FVector2D(HitNormal.X, HitNormal.Y);

FVector2D newVelocity = -2 * (V.X * N.X + V.Y * N.Y) * N + V;

this->Velocity = newVelocity;

```

Over time, the more the ball bounced around, the velocity gets smaller and smaller. How do I prevent speed loss when bouncing off walls like that? It's supposed to be a perfect bounce without friction or anything.

# Answer
One way to circumvent the accumulation of rounding errors is to re-normalize your vector when you calculate `newVelocity`. This might look like such:

```
FVector2D V = this->Velocity;
FVector2D N = FVector2D(HitNormal.X, HitNormal.Y);

FVector2D newVelocity = -2 * (V.X * N.X + V.Y * N.Y) * N + V;
newVelocity *= targetSpeed / newVelocity.Size();

this->Velocity = newVelocity;

```
> 2 votes

---
Tags: c++, physics, unreal
---


title: collision detection algorithm issue

text:
# Question
Title: collision detection algorithm issue
here is the jsfiddle i am working on so far : http://jsfiddle.net/TLYZS/

if you debug the code and check the collision function you can see that the collision is working fine when the user overlap with the other character wish in a fighting game the collision should not work like this :

1. you can see that when i punch or kick the character from a little distance the collision detection function does not work even if you can see it on the screen that the user is punishing the character
2. how can i fix this collision detection function to make it work fine ?

```
function Collision(r1, r2) {
        return !(r1.x > r2.x + r2.w || r1.x + r1.w < r2.x || r1.y > r2.y + r2.h || r1.y + r1.h < r2.y);
    }

```

# Answer
This is not a collision test issue.
This is a 'my whole code is a mess' issue.

There are **many many** points to fix :
1- reuse existing code,
2- use parameters instead of hard-coding constants,
3- check that your characters are drawn where you expect them to be (it is not the case),
4- check that you are using the right character width (not the case),
5- check your animation frames are correctly defined (not the case),
6- do not draw in your update method (...),
7- do not confuse width with current frame width (...)
8- Have a more friendly animation constructor to avoid 100 lines per animation (...)
9- In fact your whole animation loading is a mess.
10- do not launch a game before its assets are loaded.
\- ...

I did a few fix on some of the above issues (1+2+3), you can find them here : http://jsfiddle.net/gamealchemist/TLYZS/9/

I hope my remarks will help.

Happy coding.
> 1 votes

# Answer
Here's an implementation of a fairly simple rectangle hittest algorithm, which looks like what you were trying to achieve

```
function Collision(r1, r2)
{
    return ((r1.X + r1.Width >= r2.X) &&
            (r1.X <= r2.X + r2.Width) &&
            (r1.Y + r1.Height >= r2.Y) &&
            (r1.Y <= r2.Y + r2.Height)
    );
}

```
> 0 votes

---
Tags: javascript, html5, html-canvas
---