# Question
Title: JME3 Transparent Image Shows Geometries Behind
I'm using jME3 (JMonkeyEngine). I’m setting a geometry (a box with a bullet hole material/texture) to show transparency using

```
material.getAdditionalRenderState().setBlendMode(BlendMode.Alpha);
geometry.setQueueBucket(Bucket.Transparent);
geometry.setMaterial(material);

```

I guess it works, but this happens:

Basically, instead of the transparent part of the image (bullet hole) showing iron man’s (first model) red armor, it shows the ninja’s green clothing, which is in the same position but behind the iron man model. This happens even when the geometry is in front (between the camera and the both models) of the models, so idk what’s happening. Any help is appreciated!

# Answer
> 2 votes
Queue buckets are not deprecated and are absolutely intended to solve this very problem.

Objects are rendered in the scene in bucket order, i.e. Opaque is rendered then later on Transparent - there are other buckets too.

Within the bucket they are sorted based on a geometry comparator. For the opaque bucket this draws near to far, for the transparent bucket it draws far to near.

This is to reduce overdraw on opaque objects (so after you draw a large object in the foreground you don't also both drawing the pixels for all the small objects behind it). For transparent objects though you must draw the furthest away ones first so they appear behind the ones nearby and to allow transparent objects to be drawn as well as possible. Unfortunately it's impossible to sort objects correctly in all cases (for example overlapping objects) but the engine will try.

You also have alpha discard etc available for transparent objects to prevent them writing to the depth buffer in transparent areas to help improve this.

So putting the object in the transparent bucket means that all the opaque objects are drawn first. Only afterwards is your bullet hole drawn, so this then gives the result you are looking for.

Before the objects were all in the opaque bucket so they were being sorted near-\>far. The bullet hole was being drawn first and writing to the depth buffer. The man was then being drawn, but because the depth buffer thought the bullet hole had already drawn over that area nothing was drawn there.

I'm not sure why the green man was still being drawn as I'd expect him to be drawn last, maybe the extents of the model just pushed in front of the bullet hole or something though.

# Answer
> 1 votes
This problem is caused by sorting order and depth buffer. You get this result when the green model is rendered first, then the translucent polygon and finally the rest of the model. The translucent polygon is blended with whatever is behind it **at that moment**. It also writes the whole polygon to the depth buffer and nothing behind it is rendered anymore after that.

To solve the problem in this case you can first render all opaque models and then all translucent models. This gives correct results if there are no overlapping translucent polygons. If there are, the problem gets a lot harder. See Rendering order and What is the order-less rendering technique that allows partial transparency?

# Answer
> 0 votes
Using

```
geometry.setQueueBucket(Bucket.Translucent);

```

seems to have solved it, though I don't really know why. Maybe SceneProcessor is messing with my render order?

---
Tags: java, jmonkeyengine
---


title: Collision detection in libgdx

text:
# Question
Title: Collision detection in libgdx
I am currently writing a little zelda like game and have a little bit of a problem with collision detection.

It works but the the character stands to far away from the object.

Here is my player class:

public class Player extends Sprite {

```
/** the movement velocity */
private Vector2 velocity = new Vector2();

private float speed = 60 * 2, gravity = 6 * 1.8f, animationTime = 0;

private Animation still, left, right, up , down;
private TiledMapTileLayer collisionLayer;

private String blockedKey = "blocked";

public Player(Animation still, Animation left, Animation right,
        Animation up, Animation down, TiledMapTileLayer collisionLayer){
    super(still.getKeyFrame(0));
    this.still = still;
    this.left = left;
    this.right = right;
    this.up = up;
    this.down = down;
    this.collisionLayer = collisionLayer;
}

public void draw(SpriteBatch spriteBatch){
    update(Gdx.graphics.getDeltaTime());
    super.draw(spriteBatch);
}

public void update(float delta){

    //save old position
    float oldX = getX(), oldY = getY();
    boolean collisionX = false, collisionY = false;

    //move on x
    setX(getX() + velocity.x * delta);

    if(velocity.x < 0) // going left
        collisionX = collidesLeft();
    else if(velocity.x > 0) // going right
        collisionX = collidesRight();

    //react to x collision
    if(collisionX){
        setX(oldX);
        velocity.x = 0;
    }

    //move on y
    setY(getY() + velocity.y * delta);

    if(velocity.y < 0) // going down
        collisionY = collidesBottom();
    else if(velocity.y > 0) // going up
        collisionY = collidesTop();

    //react to y collision
    if(collisionY){
        setY(oldY);
        velocity.y = 0;
    }

    // update animation
    animationTime += delta;
    setRegion(velocity.x < 0 ? left.getKeyFrame(animationTime) : velocity.x > 0 ? right.getKeyFrame(animationTime) : velocity.y > 0 ? up.getKeyFrame(animationTime) : velocity.y < 0 ? down.getKeyFrame(animationTime) : still.getKeyFrame(animationTime));
    if(velocity.x == 0 && velocity.y == 0) animationTime = 0;

}

private boolean isCellBlocked(float x, float y) {
    Cell cell = collisionLayer.getCell((int) (x / collisionLayer.getTileWidth()), (int) (y / collisionLayer.getTileHeight()));
    return cell != null && cell.getTile() != null && cell.getTile().getProperties().containsKey(blockedKey);
}

public boolean collidesRight() {
    for(float step = 0; step < getHeight(); step += collisionLayer.getTileHeight() / 2)
        if(isCellBlocked(getX() + getWidth() , getY() + step))
            return true;
    return false;
}

public boolean collidesLeft() {
    for(float step = 0; step < getHeight(); step += collisionLayer.getTileHeight() / 2)
        if(isCellBlocked(getX(), getY() + step))
            return true;
    return false;
}

public boolean collidesTop() {
    for(float step = 0; step < getWidth(); step += collisionLayer.getTileWidth() / 2)
        if(isCellBlocked(getX() + step, getY() + getHeight()))
            return true;
    return false;
}

public boolean collidesBottom() {
    for(float step = 0; step < getWidth(); step += collisionLayer.getTileWidth() / 2)
        if(isCellBlocked(getX() + step, getY()))
            return true;
    return false;
}

```

I guess it has something to do with the sprite sheet. Here is my Spritesheet:

Here is the pack file for the spritesheet:

> linksprite.png format: RGBA8888 filter: Nearest, Nearest repeat: none stillup rotate: false xy: 0, 0 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 still rotate: false xy: 0, 64 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 stillleft rotate: false xy: 0, 32 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 up rotate: false xy: 0, 0 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 up rotate: false xy: 32, 0 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 up rotate: false xy: 64, 0 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 up rotate: false xy: 96, 0 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 up rotate: false xy: 128, 0 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 up rotate: false xy: 160, 0 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 left rotate: false xy: 0, 32 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 left rotate: false xy: 32, 32 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 left rotate: false xy: 64, 32 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 left rotate: false xy: 96, 32 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 left rotate: false xy: 128, 32 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 left rotate: false xy: 160, 32 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 down rotate: false xy: 0, 64 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 down rotate: false xy: 32, 64 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 down rotate: false xy: 64, 64 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 down rotate: false xy: 96, 64 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 down rotate: false xy: 128, 64 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 down rotate: false xy: 160, 64 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 right rotate: false xy: 0, 96 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 right rotate: false xy: 32, 96 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 right rotate: false xy: 64, 96 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 right rotate: false xy: 96, 96 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 right rotate: false xy: 128, 96 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1 right rotate: false xy: 160, 96 size: 32, 32 orig: 16, 16 offset: 0, 0 index: -1

# Answer
> 0 votes
I haven't read into your code too much but the collision logic appears to be flawed. Imagine a projectile moving at over 200 pixels every updates. The projectile will just fly right through everything.

In order to fix this problem, loop from 0 to the amount of pixels to move in whichever direction you entity is moving towards. On top of that, you need to loop from 0 to \[HEIGHT\_OF\_ENTITY\] for horizontal movement and WIDTH\_OF\_ENTITY for vertical movement, to ensure that the entity does not get stuck inside blocked tiles. This will ensure correctly working collisions in any scenario, and should never fail.

Here is some old code I wrote a few months back. I cleaned it a little bit and documented it so it would be easier to understand.

It's my base collision code, I rewrite this every time I want tile based collisions and it works perfectly.

It's in C# but it should be very easy to understand for you since Java's syntax is almost exactly the same.

```
public bool resolveCollisions() {
    if (xa == 0 && ya == 0) return false;
    if (xa != 0 && ya != 0) throw new ArgumentException("Can only resolve collisions along one axis at a time");

    if (xa != 0) { //horizontal movement
        if (xa < 0) { //movement towards the left
            for (int i = 0; i > xa; i--) {
                for (int j = OffsetY; j < OffsetY + Height; j++) { //OffsetX and OffsetY is in case you want to adjust the hitbox of your entity a bit
                    Vector2 cVec = new Vector2(Location.X + OffsetX + i, Location.Y + j) / Tile.Size;
                    Tile t = level.GetTile((int) cVec.X, (int) cVec.Y);
                    if (t.OnCollide(this)) { //t.OnCollide is the tile's handling when collided with an entity. (ie, damage if spikes etc.)
                        Velocity.X = i + 1;
                        return true; //COLLISION!
                    }
                }
            }
        } else if (xa > 0) { //movement towards the right
            for (int i = 0; i < xa; i++) {
                for (int j = OffsetY; j < OffsetY + Height; j++) { //OffsetX and OffsetY is in case you want to adjust the hitbox of your entity a bit
                    Vector2 cVec = new Vector2(Location.X + OffsetX + Width + i, Location.Y + j) / Tile.Size;
                    Tile t = level.GetTile((int) cVec.X, (int) cVec.Y);
                    if (t.OnCollide(this)) { //t.OnCollide is the tile's handling when collided with an entity. (ie, damage if spikes etc.)
                        Velocity.X = i; //stop movement!
                        return true; //COLLISION!
                    }
                }
            }
        }
        return false;
    } else if (ya != 0) { //vertical movement
        if (ya < 0) { //up movement
            for (int i = 0; i > ya; i--) {
                for (int j = OffsetX; j < OffsetX + Width; j++) { //OffsetX and OffsetY is in case you want to adjust the hitbox of your entity a bit
                    Vector2 cVec = new Vector2(Location.X + j, Location.Y + OffsetY + i) / Tile.Size;
                    Tile t = level.GetTile((int) cVec.X, (int) cVec.Y);
                    if (t.OnCollide(this)) { //t.OnCollide is the tile's handling when collided with an entity. (ie, damage if spikes etc.)
                        Velocity.Y = i + 1;
                        return true; //COLLISION!
                    }
                }
            }
            InAir = true; //A boolean which indicts that the entity is not on ground!
        } else if (ya > 0) { //down movement
            for (int i = 0; i < ya; i++) {
                for (int j = OffsetX; j < OffsetX + Width; j++) { //OffsetX and OffsetY is in case you want to adjust the hitbox of your entity a bit
                    Vector2 cVec = new Vector2((int) (Location.X + j), (int) (Location.Y + OffsetY + Height + i)) / Tile.Size;
                    Tile t = level.GetTile((int) cVec.X, (int) cVec.Y);
                    if (t.OnCollide(this)) { //t.OnCollide is the tile's handling when collided with an entity. (ie, damage if spikes etc.)
                        Velocity.Y = i;
                        if (InAir) //Is the player in the airs?
                            OnLand(); //Entity is landing, make sure you set InAir to false inside this method
                        return true; //COLLISION!
                    }
                }
            }
        }
        return false;
    } else {
        //sanity check
        throw new ArgumentException("Can only resolve collisions along one axis at a time");
    }
}

```

Plug that method into your entity class and then these two calls into your update method

```
resolveCollisions(velocity.x, 0);
resolveCollisions(0, velocity.y);

```

The code loops complicated and very math/logic intensive but it really isn't and is fairly straightforward once you get the meaning behind it. The same logic is repeated 4 times essentially. (4 different directions)

A few clarifications

* This code was written for a platformer, with gravity. But it can easily be edited to fit the needs of a top-down view game.
* OffsetX and OffsetY are variables to help define a better hitbox in conjunction of the Width and Height variables
* The tile classes should have a method OnCollide with a parameter of type Entity that will return true if this tile should block passage or false if not. You can also add special handling like damaging the entity if it's spikes or whatever.
* I'm not entirely sure why you shouldn't check collisions along both x and y axis at the same time but I remember I had problems when doing it that way, so I only check along x and y, separately. You can't check along x-axis and y-axis both in the same method call because we can't return two booleans, duh! (Unless we returned a Tuple of two booleans of course)

---
Tags: java, collision-detection, libgdx
---


# Question
Title: How can I provide a scrollable inventory list?
Does XNA have a built in method for drawing a scrollable list?

There would be a scroll bar on the right that can be selected and moved up and down to scroll the list inside the inventory screen. The list would not be all visible at once so as you scroll down the top items disappear and the bottom ones appear next in the list.

Visually it's like scrolling a webpage but within a smaller window.

Can this be done without using Windows Forms?

# Answer
There isn't a built-in way in the XNA API to provide this kind of UI (or really, any UI at all). There are a handful of third-party projects that provide UI frameworks. Two that come to mind are XUI and Ruminate, which may provide what you want.

Alternatively, you can roll your own. Fundamentally this not much different from implementing scrolling behavior in any other kind of domain (such as scrolling your map):

* You have a list of items in the inventory list, and functionality to render them however you like.
* You have the rectangular region on the screen where the inventory is located.
* You have a value that represents the user's scroll position within the inventory, which you update when the user drags or interacts with some other UI widget such as a scroll bar you've drawn next to the inventory.

That is the basic information you need to assemble to then understand which of the items should be rendered into the inventory window.
> 5 votes

# Answer
Scrolling isn't too hard - but it's not trivial either. I'll give you some starting points, but the actual implementation will depend on the structure of your game.

To begin with, you need your scroll region (probably a `Rectangle`), the scroll offset of the content within that region (probably `int`), and the length of the scrollable content (probably `int`).

Then you need a way to clip your scrolling content to display only within the scroll region. This means `Viewport`, `ScissorRectangle`, or a stencil buffer if you want a non-rectangular region. `Viewport` will change the origin of the display, whereas `ScissorRectangle` just clips.

To make your content move up and down within this region, use a translation matrix (`Matrix.CreateTranslation`). If you use `SpriteBatch`, the `Begin` method has an overload that takes a transformation matrix (MSDN).

To determine whether clicking is happening within the scroll region, use `Rectangle.Contains`. You can also use this to determine whether the user is clicking on your scroll bar.

If you want scroll-wheel support, use `Mouse.ScrollWheelValue` (note that this is a cummulative value, see MSDN).

You'll have to do all the maths for the scrolling yourself, but it should be fairly simple. `Math.Min` and `Math.Max` should help to keep your scroll offset in the desired bounds. You can calculate the height for your scrollbar with something like:

```
(int)Math.Max(1, (float)region.Height / (float)content.Height)

```
> 5 votes

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


# Question
Title: How can I make a global scoring system in C++?
How do I make it so that in a multiple-level game the score will stay where it was from the previous level?

# Answer
Store the score *outside* of the level, probably in the game object that manages which level you are on:

```
class Game {
  int score;
  Level * currentLevel;
  ...
};

```

If there is code within a given level object that might need to manipulate the score, you can pass that information to the level when it is constructed. You could simply pass a pointer to the score integer (the simplest, most straightforward option) or you could encapsulate the score in its own interface:

```
struct Score {
  int GetCurrentPoints () const;
  void AddPoints (int points);
  ...
};

struct Level {
  Level (Score * globalScore)
  : score(globalScore) {
  }

private:
  Score * score;
};

class Game {
  Score score;
  Level * currentLevel;
  ...
};

```

Pass the a pointer to the game's instance of the single global score to each level, which they store and manipulate, and it will persist across levels as you'd like.
> 2 votes

---
Tags: c++, scoring
---


# Question
Title: How to loop through objects in class (XNA)?
In my game I have an `Enemy` class, and in that I have a constructor which I use to make `Enemy` objects.

How do I add all `Enemy` objects to a list or loop through all of them using a `foreach` loop?

I have tried various variations of this:

```
foreach(object E in Enemy){
        //Do collision detection, set AIs next move, etc.
}

```

However, it always rejects the second part of the `foreach` loop, saying that `Enemy` is a type but is used as a variable.

# Answer
The error you state is correct, 'Enemy' is a type. What you have there is equivalent to 'foreach (object E in integer)' or 'foreach (object E in string)'.

You need to add the enemy instances to a list or array. It should be roughly:

```
//Creating enemies
List<Enemy> enemyList = new List<Enemy>();

Enemy e = new Enemy();

enemyList.Add(e);
etc...

```

then to iterate:

```
foreach (Enemy anEnemy in enemyList)
{
 if (anEnemy.IsDoingWhatever)
  etc...

}

```
> 3 votes

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


# Question
Title: Movement / aiming algorithm in 2d / tiled based game
I'm trying to create simple 2D / tiled base game in JavaScript. Entities are able to move by any number of pixels, but only in one direction at once (can't go in diagonal way). AI for enemies is simple 'zombie movement' (if you see target - go to him).

Currently I've got problem with my shooting mechanism. In my code I've got statement which say something like this:

```
if (distance_to_target <= weapon_range) {
    shoot_in_current_direction();
}

```

As you can see on example below my problem exist when target is in range in diagonal way. Red rectangle is 'shooter', blue rectangle is 'target', black dots are 'bullets' and black arc line is a weapon range.

**My question is:** how to implement restrictions which allow to shoot only if target is in good direction, but not exactly on that same x/y coordinate (allow for some margin)? Should I implement more intelligent movement algorithm (i.e A\*)?

To be clear... I'm not looking for ready code but rather for some algorithm help.

# Answer
> 1 votes
In order to implement a simple algorithm to do the shooting only in the horizontal or vertical, you can use your player's and the enemy's bounding boxes and their width and height in order to check whether the enemy is "aligned to" the player's bounding box.

Basically, you need to check in all 4 directions whether the enemy's bounding box is within the region cast by the player bounding box's extended edges.

By using this image as a reference, you'd need to check whether the region defined by the `t` and `b` points is inside any of the regions defined by the black lines.

In order to do that, you can check (assuming T=(Tx, Ty), B=(Bx, By), t=(tx, ty) and b=(bx, by)):

```
if player_in_range and (ty > Ty and ty < By) or (by > Ty and by < By) or (tx > Tx and tx < Bx) or (bx > Tx and bx < Bx) then
  enemy is inside player's horizontal or vertical reach

```

Of course, you can make these horizontal and vertical regions more limited if you want by adding a threshold (margin) value to the comparisons above.

---
Tags: javascript, ai, movement, aiming
---


# Question
Title: How can I add a bullet every time the player clicks?
I'm not understanding how to dynamically add object instances in my games.

I'm really having trouble understanding the general concept. If I want to quickly generate unknown numbers of objects, going through and declaring them one by one does not seem to be plausible. This problem is exemplified by bullets. If the player can fire 100 bullets, how do I declare and define these objects in a simple manner. Obviously I need formulas to tell the bullets where to appear and where to go, but I can do that. How do I get to the point where I can begin to define those formulas?

Here is the code up to the point I have tried, the current problem being that B cannot be assigned because it is the essence of the foreach loop:

```
if (ms.LeftButton == ButtonState.Pressed)
{
    shotFired = 0;
    foreach (Bullet B in bulList)
    {
        if(B != null)
        {
            B = new Bullet(main.Location, enball, spriteBatch);
            shotFired = 1;
        }
     }
    //if all bullets are not "null," essentially delete one and replace it.
}

```

# Answer
To fire a bullet every time the mouse is clicked, with no limit to the number of bullets that can exist, simply do:

```
if (ms.LeftButton == ButtonState.Pressed) {
  var bullet = new Bullet(main.Location, enball, spriteBatch);
  bulList.Add(bullet);
}

```

If you want to have a fixed number of bullets (represented by `bulList`) and use the first `null` entry in the list you find to hold the newly-fired bullet, use a `for` loop instead (because as you noted, you cannot modify the `foreach` enumeration variable in that fashion):

```
if (ms.LeftButton == ButtonState.Pressed) {
  for (var index = 0; index < bulList.Count; ++index) {
    if (bulList[index] == null) {
      bulList[index] = new Bullet(main.Location, enball, spriteBatch);
      break;
    }
  }
}

```

You can also implement that "if no bullets were `null`, re-use an existing one" logic in the latter example if you like.

Note that a better way to handle the above is to instead partition your list and keep a "dead index" such that every live bullet is below the dead index and every dead (`null`) bullet is above it. This can help you avoid the costly linear search through the bullet array every time you fire.
> 4 votes

# Answer
This is a very simple question.
When you get the click event, **add** a new bullet into your bullet array. Then, you can update and draw the bullets at their positions every frame. When you update bullets, you can make them go forward, and check their collisions with objects. Then just draw them.
It is not as hard as you think.
Here are some links:
http://en.wikibooks.org/wiki/Creating\_a\_Simple\_3D\_Game\_with\_XNA
http://www.riemers.net/
> 0 votes

---
Tags: xna
---


# Question
Title: Adding Screenshots Specifically For 4-inch, 7-inch, and 10-inch Screen
My boss invited me and assigned me now as publisher for the app in Google Play. I have a 7-inch Google Nexus 7 tablet to take screenshot of any one of my sample projects I've made and post and upload it into the 7-inch screenshot section. Now, I want to take some screenshots and post it this time into the 4-inch screenshot section. However, I got a 4.5-inch smartphone that runs on Android ICS.

I was wondering. Is it valid if I posted on the 4-inch screenshot section using all my snapshots taken from the 4.5-inch screenshot image or there is a specific requirement for that like the width and height in pixels?

# Answer
> 2 votes
The size of the screen does not directly dictate the number of pixels. You should be taking screenshots at *different resolutions*, not different screen sizes. I have a 16 inch screen on my laptop, and a 5 inch screen on my phone, but they both have the same resolution (1920x1080).

Use the most common devices to get some average screen resolutions for the different form factors. Then you can produce all the screenshots on a device that has the highest resolution (as long as you can change the resolution of your game to whatever you wish).

---
Tags: resolution, pixel, publishing, google-play, screenshot
---


# Question
Title: Why don't we use octogonal maps instead of hexagonal maps?
I understand the advantage of hexagonal tiles over square ones. But why aren't octagons used instead? I would think they would provide better, more natural movement in eight directions.

I was thinking about using that kind of map in some game, but I haven't seen any games using it, so I wonder if I missed something obviously flawed about using it?

# Answer
> 73 votes
Octogons:

Hexagons:

The gaps in the octogons make for an unappealing game world.

Typically, if you wanted to allow for eight directions of movement, you would just use squares.

# Answer
> 74 votes
To summarize and elaborate upon what has been said in other answers and in comments, triangles, squares and hexagons are the only mathematically possible regular tilings aka regular tessellations of the Euclidean plane. So yeah, this sucks. Triangles are completely useless here, squares suck because you can't move diagonally without having a somewhat unwieldy factor of 1.4142135623730950488016887242096980785696718753769480 ... give or take; and hexagons suck because you can't even move straight in both directions. Don't get me wrong, I still prefer them over squares within the constraints of the crappy reality mathematics left us with and go Civ5 for finally switching to hex grids. But still, if it *were* possible to tessellate with octagons, nobody would ever take a second look at hexagons.

You could say "Well, I don't care if there are gaps. I just pretend they aren't there." You'd get the truncated square tiling which is called *square* tiling not because there are little square gaps but because those octagons are in fact just glorified squares in terms of tiling the plane. Those little squares are what's left from truncating the corners off the squares that would actually tile the plane and in game terms, the reason to not use squares in the first place was to have an equal distance for straight and diagonal moves and this is what you don't have here. Diagonal moves have to bridge the same distance between tile centers as they would with square tiles. Conversely, if you pretend your magic digital space had actual holes, you can of course do that but what's the difference from just using square tiles and making diagonal moves just as expensive as straight ones?

Now this all wouldn't be so bad if there were really good alternatives that aren't Euclidean. Often, our grid is on some kind of planet anyway, so why not use an elliptic geometry, i.e. the surface of a sphere? Unfortunately, spheres are even much, much worse when it comes to regular tilings. Where in the plane you can at least use as many or as little tiles as you like, on spheres there are five arrangements, the Platonic solids. That's it. And only two of them don't use triangles. https://en.wikipedia.org/wiki/Spherical\_polyhedra

However, the *hyperbolic* plane really rocks when it comes to tessellations. There aren't just three, in fact there's an infinite number of regular tessellations, including an octagonal one.

The only problem is that the hyperbolic plane isn't something as nice as a flat surface or a sphere but basically the surface of a Pringle. You'd need one hell of a story hook to justify a game on a Pringle ;)

Still, the octagonal tiling is so elegant and the Poincaré disc looks so awesome that I'm really surprised it's almost never been done (previously I said "never been done" here but then I read MartianInvader's comment pointing to HyperRogue).

Implementation-wise, while I've never done it myself, it should be fairly straightforward to implement this with today's 3D architectures, since a Poincaré disc view can be constructed by putting everything on the surface of a hyperboloid and doing a perspective projection (see Relation to the hyperboloid model).

Just one more thing to conclude this, in case you think about doing a grid-based space game and going to three dimensions, hoping that things might look rosier there ... better just give up. Not only would you need a regular convex polyhedron with 14 faces which doesn't exist, the only way to tessellate 3D Euclidean space with regular convex polyhedra is with cubes. Booooring. In hyperbolic space you can at least get *something* vaguely like the analogon to a hex grid by tessellating with dodecahedra (i.e. 12-faced polyhedra; that's *almost* 14, right?) but now you're in total brainfuck land and still haven't got the counterpart to an octagonal tiling:

Beautiful as hell? Oh my God, yes! Would I panic beyond measure if alien spaceships came after me in this and I was expected to react in a sensible way? You bet I would. This is probably the reason why most people just use either cubes or hexagonal prismatic stacks.

# Answer
> 30 votes
The author of HyperRogue here.

HyperRogue actually uses a tesselation made of hexagons and heptagons, here is the reason why this particular tesselation has been chosen, instead of only octagons or heptagons, for example: Hyperbolic geometry in Hyperbolic Rogue Basically, the octagons are too big.

Also some consequences of using hyperbolic geometry in a game (what works in hyperbolic and do not work in Euclidean, and vice versa) are listed in that post.

And yes, as Christian guessed, HyperRogue internally uses the hyperboloid model.

I am not allowed to comment on Christian's answer, but there is a tesselation of the 3D space with 14-faced polyhedra: Bitruncated Cubic Honeycomb (why 14 faces, anyway?)

# Answer
> 9 votes
Basically what you want is a monohedral tesselation (or tiling), that is a coverage of the entire plane (assuming 2d) with a single shape where the tiles do neither overlap nor leave gaps.

There are lots of shapes with which this can be done but when we introduce other constraints, usually orientation should stay the same or they should conform to a natural movement direction, basically only squares and hexagons remain.

Take the triangle for examples (which you might know from the tesselation of 3d objects). To fill the gaps between two triangels another triangle has to be inserted, but flipped upside down. This is obviously a hassle to generate when dealing with sprites for example since a seamless connection is important. Also triangular movement sucks.

The most natural, with regard to movement at least, is the square which happens to be the most frequently used. Hexagons are the next best thing and allow for more direct approach to a higher number of movement directions, i.e. not over the corner movement like 8-way movement on squares does. Usually they are used in more tactical games where the increase in movement is important.

Anyway, if you want to read up more, take a look at http://euler.slu.edu/escher/index.php/Tessellations\_by\_Polygons.

---
Tags: grid, level-design, hexagonal-grid
---


# Question
Title: Detecting collision of two sprites that can rotate
I have a problem with collision detection in a 2D Java game.

Normally, what I would do is create a getBounds() method for an object that can collide with other objects. This method would return a `new Rectangle(x,y,width,height)`, where `x` and `y` are the coordinates for the top-left corner of the sprite, and `width` and `height` are the width and height of the sprite.

But in the game I'm currently working on, there is a "tank" controlled by the user. The sprite of this tank rotates as long as the player holds one of the left or right arrow buttons. In other words, it can rotate to any angle. The tank's sprite is a rectangle.

So I can't simply do what I always do in this case.

How can I detect collision with this kind of sprite? Thanks

# Answer
The simplest way to handle rotating 2D collisions is to use circles instead of rectangles. For most practical purposes, circles are a good approximation, simple to implement, and nobody will be able to tell the difference anyway. Two objects are colliding if the distance between the centres (using Pythagorean theorem) is less than the sum of the radiuses.
> 3 votes

# Answer
I agree with the other answer, to use circles as the simplest approach, although it only works with roughly square/circular objects. One alternative though would be to actually draw the objects and check for overlap, this gives pixel-perfect collision detection.

Give all "shootable" objects a unique id and have a buffer representing the screen. Render into the screen buffer the id of the object for the position it is in. I.e. if the Tank is 1 write a 1 in each location it occupies. If an enemy is 3 write a 3 there.

Once your scene is drawn then as your bullet moves check the stored value of the spaces it occupies (and spaces it moves through if it is moving fast enough that tunnelling is an issue). The number found is the id of the object you hit, 0 means continue. (Don't write bullets to that buffer unless you want them to hit each other).
> 0 votes

---
Tags: collision-detection, sprites, rotation
---


# Question
Title: Attaching a Body to another, without the new body impacting the physics of the first in ANY WAY
Basically I want to add a vision / sight cone to an enemy body,

So I have the sight cone body, and enemy body, but every joint or weld I have tried so far has caused the sight cone to severely affect and disrupt the physics and movement of my enemy, most of the time causing the poor guy to go into tailspins.

I only want the sight cone as a sensor, a sensor that has NO physics impact whatsoever on its parent body (the enemy) except simply to stay stuck to it as it moves, matching its position and rotation. but all I can seem to find is weighted attachments, that set up new anchors and whole new physics properties to me new joined body.

I hope you can help.

# Answer
`Fixture.IsSensor = true;` is what you need. A sensor will detect collisions but will not automatically respond to them.
> 2 votes

# Answer
Instead of using a joint, what you probably want to do is add sensor `Fixture` to the original `Body`.

The code would be something like this:

```
var fixture = FixtureFactory.Attach...(..., body);
fixture.IsSensor = true;

```

Sensor fixtures take part in collision *detection* but not collision *response* (basically so they can fire collision events when they "sense" something).

Sensor fixtures can have mass, so be sure to set its density to 0, otherwise it can affect the physics behaviour of the parent body.
> 0 votes

---
Tags: xna, c#, farseer-physics-engine
---


# Question
Title: How to modify normal vectors with a tranformation matrix
Transformation is quite simple when it comes to Position or Color of the vertex, for Position just multiply matrix * vector and for color just don't do anything, but my question now is: How to handle normal vectors? If my thoughts are correct I would just need the rotation part of the matrix and apply it to the normal vectors, but how can I do that? Or is it better not to use a matrix for that, but instead allow only direct transformations, one at a time, so I can handle them differently for different vertex attributes?

# Answer
Simply multiply the normal vector with the inverse transpose of the 3x3 sub matrix used to transform points.

> Normaltransformed = Inverse ( transpose ( mat3 ) ) * Normal;

The rational behind this is that Normal vectors has the property of being perpendicular to the surface so you need the inverse transpose to retain that property. You need the 3x3 matrix and not the full 4x4 matrix is that normals are direction and shouldn't be translated. Alternatively, you can set the normal vector `w` component to 0, but normals are usually vec3.

Note that if your matrix only contains rotation, the inverse transpose will result in the same original matrix so you don't need to do anything.

> Normaltransformed = mat3 * Normal; // In case mat3 is only rotation.

More on the topic here.
> 4 votes

---
Tags: 3d, matrix, vector, geometry
---


title: Countdown Timer for Racing Game

text:
# Question
Title: Countdown Timer for Racing Game
I want to make a countdown timer for my racing game such as "3... 2... 1... GO!" I'm using GLUT, OpenGL, and C++. I was wondering what the most appropriate method to handle this in C++. clock()? glutTimerFunc()? I plan on having 4 textured polygons that shrink and fade one after the other.

# Answer
> 2 votes
You need to *accumulate* time in your `update` loop. Don't think in terms of "what time it is", instead, keep a `double` variable, called `timeTotal`. Each frame, increment it by (`1.0/60.0`) (or whatever your fixed timestep is). When the game starts, you can reset the timer, and your race start introduction would just go something like this:

```
void update()
{
  totalTime += 1.0/60.0 ; //increase time

  if( timeTotal > 1 )  // 3.
  else if( timeTotal > 2 )  // 2.
  else if( timeTotal > 3 )  // 1
  else { GO } // race on

}

```

You can refactor this in any number of ways, but this is the basic idea of how to trip time based events in a game system.

---
Tags: c++, opengl, timer, glut
---


# Question
Title: Directional, Triangular Collision Detection in Pygame
I am trying to create a game in Pygame, with Python 3, and am trying to figure out an algorithm that will tell me which direction a rectangle is colliding with a rectangle, so that I can push it back the correct direction. I know I can detect rect-to-rect, and I could (possibly?) use pixel-to-pixel collision, but I was wondering if there was a better way. My collision algorithm currently loops through all of the "entity" objects in a Pygame sprite.Group(), and testing for collision using the colliderect() method, then I test which direction the rect is coming from by testing which sides overlap. Is there something similar that I could do with a collision between a triangle and a rectangle, too? Pseudocode would be nice.

# Answer
The safest way would be to find the intersection point of each of the 4 line segments of the rectangle with each of the 3 line segments of the triangle : if any of those is on the triangle and the rectangle, there's intersection. From the pictures you provided, though, it looks like we can assume the triangles are half rectangles, when a collision happens there's only one corner of the rectangle inside the triangle (no need to check for high speed and related sweeping), and every body nicely stays axis aligned.

This makes things simpler : If we call the triangle ABC, and the rectangle EFGH, first find the point D that makes ABCD a rectangle. If there's no rectangle collision between ABCD and EFGH, you know there won't be any between ABC and EFGH either. If there is, though, you still need to check that either E, F, G, or H (you can even possibly predict which one it will be) are on the same side of the line AC that B.

If the assumptions are wrong please correct me, and if you need implementation details just ask.
> 1 votes

---
Tags: collision-detection, python, pygame
---


# Question
Title: If SpriteBatch.Draw's SourceRectangle is null does a rectangle still get created?
If you use the following `SpriteBatch.Draw` overload, does a `Rectangle` get created for the texture?

```
spriteBatch.Draw(texture, textureRectangle, null, Color.White, 0f, textureOrigin, SpriteEffects.None, 1f);

```

If so how would you access the `Rectangle`?

# Answer
You can create an equivelent rectangle like so:

```
Rectangle sourceRect = new Rectangle(0, 0, texture.Width, texture.Height);

```

Or simply use `texture.Bounds`.

Note that there's no GC overhead to creating a `Rectangle` as it is a value type (`struct`), and the construction cost is negligible (relatively). So you don't need to worry about the cost of creating your own, or any internal cost inside `SpriteBatch`.
> 2 votes

# Answer
The SourceRectangle is used to extract only parts of a texture. This is useful when dealing with spritesheets.

By using null you are saying you want to draw the whole texture.

Let's say you wanted to only draw the tree from this texture. If each tile were 16 by 16 pixels you would enter.

```
spriteBatch.Draw(myTilesheet, // The Texture2D
                 new Rectangle(10, 10, 16,16), // This rectangle positions the texture on the screen and scales it can also be a Vector2
                 new Rectangle(0, 80, 16,16), // This describes where to find the tree tile
                 Color.White,
                 0f,
                 Vector2.Zero,
                 SpriteEffects.None,
                 1f);

```
> 1 votes

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


# Question
Title: How do I implement references or relations for entities within a serialized savegame?
I have a 2D tile based RPG for which I'm developing save game function. In particular, I'm trying to save this structure:

A caster can have multiple buffs that he maintains. Each buff can have multiple effects applied to players or monsters. The pattern has links both ways (caster has buff, buff knows who cast it)

If I serialize caster, buffs and effects, how can i restore the relationship: caster - buff - effect - target?

**Would I need to implement something like unique identifiers for monster, buffs and players and then link them all together once the save game is loaded?**

# Answer
Unique identifiers are a good option. However, they don't need to be used in game, only when writing and then reading the data from a save. Hopefully you'd already have some way to differentiating between entities you can use, otherwise you can make something up (typically an `int` or `long`)

Pick a unique ID for each entity, then proceed to writing the entities. For each entity, write its ID and when you write its components, add that ID as a header to the component information. Also write the ID for any target info. Then, when you're reading back in, you can use something like a dictionary to store the entities in, referenced by their ID. Then when you read a component, you can get the ID and index into the dictionary and add that component to that entity.

When I read and write entities, I write all of the entities first, without their components. This makes it much easier when reading in the components later because you have all the entities available to you. It avoids the situation where you're reading in an entity that has a component that targets another entity, but you haven't created that target entity yet because it's deeper in the file.
> 4 votes

---
Tags: architecture, savegame, serialization
---


# Question
Title: How do I get the position of a static body in Jbox2D?
I'm trying to get the position of a static body in JBox2D, how do I do that?

# Answer
> 1 votes
I haven't used JBox2D, but I think this is accurate. I looked at the source for the project and learned a lot (and you can too). Primarily that body contains a `Transform`, and that the `Transform` contains the position.

Since all those variables are public, it's likely you'll be able to access the position from:

`myStaticBody.m_xf.p`

---
Tags: jbox2d
---


# Question
Title: How can I load a large tile map with cocos2d?
I am try to design a cocos2d game with a big world. The world's tile map is very big, maybe 20 iPad screen sizes worth of tiles.

I want to know how to load this using a `CCTMXTiledMap`? If I directly add it to screen, will it use too much memory? If so, is there a solution to solve this problem?

# Answer
> 1 votes
Although the comments suggest that `CCTMXTiledMap` will perform poorly under large tile maps, it's hard to say in general if that is going to be "slow enough" to be a problem for your game.

So I would advise you to simply try it first, and see if it works for you. If it does, you have a simple solution.

If it doesn't, you can usually solve this kind of issue by breaking up a large map into segments and loading those independently, keeping only the segment the player is currently on (and potentially the immediately-adjacent segments) in memory and unloading old ones (and loading up new ones) as the player traverses the map. This is the basic technique used to present large, apparently seamless worlds.

---
Tags: cocos2d-iphone, ios, maps, tilemap
---


# Question
Title: Do UDK mutators only apply on local games?
I have developed a pretty simple mutator. It works exactly as intended on a local game against bots, but it doesn't work (nor do any of the stock mutators) on a listen server.

Is this to be expected of UDK (May Beta Release by the way)?

# Answer
The documentation certainly suggests they work for multiplayer games due to the number of references to "servers" and the like. It's possible your configuration is just such that mutators are disabled on your servers for some reason.
> 1 votes

---
Tags: udk
---


# Question
Title: How can I access the translation part of a skinned Model object's bone transformation?
I have an animated `Model`, which I process with the `SkinnedEffectProcessor`. How I can access translations of that model during animation?

It's always a `BoneTransform` I am working with, but I'd like to know which X, Y and Z values are currently changing.

So, during the update I added this line

```
Debug.WriteLine(_model.GetBoneTransform("RootNode").Translation.ToString());

```

but all it outputs is

```
{X:0 Y:0 Z:0}

```

when I trigger the jump-animation. I'm expecting the Y value to go up, since the model is jumping in that animation.

# Answer
The transforms are stored in the bone transformation matrix, and you should be able to extract them via:

```
model.GetBoneTransform("NodeName").Translation

```

However, as noted, they might not be the values you *expect*, because it's possible your animation was exported in such a way that the root node does not animate and all other nodes that are its children do.
> 1 votes

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


# Question
Title: Why do I get an access violation while reading the pixels of an SDL_Surface as follows?
I'm trying to write a software rasterizer and I'm in the step to texture a triangle. I'm trying to get a pixel from an `SDL_Surface` which is an image, 100x60 at 24 bits of color depth.

I got a read access violation exception. For instance I try to say

```
Uint32 * pixels = (Uint32 *)texture->pixels;

```

then

```
int pixel = pixels[5900];

```

It gives an access violation. However the calculated pixels count is correct

```
int pixel_count  = (texture->pitch / texture->format->BytesPerPixel) * texture->h;

```

Is this wrong? How can I access the pixels of this surface?

# Answer
> 3 votes
It sounds like you're reading off the end of the 24-bit data, because you're treating it as if it was 32-bit.

That is I suspect texture-\>pitch is 300 and texture-\>format-\>BytesPerPixel is 3. sizeof(Uint32) is of course 4.

The simplest solution is to use a 32-bit image.

---
Tags: c++, sdl
---


# Question
Title: Assimp renders a partial amount of vertices
I'm building a 3D game, and i'm trying to load some assets with the nice Assimp library. The model should look like the one in the first picture, but instead, it takes the form of some kind of avant-garde sculpture, as the second picture shows.

At least i'm proud that i get to see something, but hey, i can do better.

It's not a problem with shaders (it simply isn't, i pass no normals and no textures, just the vertex coordinate, since i set a static colour). Here is my code:

**MODEL LOADING (only vertex coordinates)**

```
void Mesh::open(const std::string file)
{
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(file, aiProcess_Triangulate);
if(!scene)
    throw STREAM("Could open mesh '" << file << "'!");

std::vector<float> g_vp;
count = 0;

for(uint m_i = 0; m_i < scene->mNumMeshes; m_i++)
{
    const aiMesh* mesh = scene->mMeshes[0];
    g_vp.reserve(3 * mesh->mNumVertices);
    count += mesh->mNumVertices;

    for(uint v_i = 0; v_i < mesh->mNumVertices; v_i++)
    {
        if(mesh->HasPositions())
        {
            const aiVector3D* vp = &(mesh->mVertices[v_i]);
            g_vp.push_back(vp->x);
            g_vp.push_back(vp->y);
            g_vp.push_back(vp->z);
        }
    }
}

glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, count * 3 * sizeof(float), &g_vp[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL);
}

```

**SCENE RENDERING**

```
void renderScene()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

program.use();
program.setUniform("transformMat", modelMat);
glBindBuffer(GL_ARRAY_BUFFER, m.vbo);
glDrawArrays(GL_TRIANGLES, 0, m.count);

SDL_GL_SwapWindow(window->mWin);
}

```

Depth testing is enabled, and i'm using OpenGL 4.0 with v400 shaders too.

The error will possibly be stupid, but i can't find it, and my head is all boiling at this very moment.

Thanks for your help!

# Answer
> 2 votes
*Reposting comment as answer.*

In the for loop below you are only ever reading from the first mesh in the scene. Depending on how you've modeled it, it may be composed of multiple meshes. I have fixed the loop below replacing `scene->mMeshes[0]` with `scene->mMeshes[m_i]` to ensure that all meshes' positions are added to the vertex buffer.

```
for(uint m_i = 0; m_i < scene->mNumMeshes; m_i++)
{
    const aiMesh* mesh = scene->mMeshes[m_i];
    g_vp.reserve(3 * mesh->mNumVertices);
    count += mesh->mNumVertices;

    for(uint v_i = 0; v_i < mesh->mNumVertices; v_i++)
    {
        if(mesh->HasPositions())
        {
            const aiVector3D* vp = &(mesh->mVertices[v_i]);
            g_vp.push_back(vp->x);
            g_vp.push_back(vp->y);
            g_vp.push_back(vp->z);
        }
    }
}

```

---
Tags: opengl, glsl, models, loading, assimp
---


# Question
Title: Indirect indexing (uv coords read from texture)
In the vertex shader, I need to make a texture fetch, where the texture coordinate itself is read from some other texture.

```
vec2 uv = texture(someTexture,coords).xy;
vec4 val = texture(otherTexture,uv).xyzw;

```

As far as I know, the second sample has undefined results, because the value of uv is outside of uniform flow control.

Is there any way to efficiently (i.e., not copy back the contents of the texture and upload it as a uniform to the shader or something) do what I want to do?

# Answer
> 1 votes
Indirect texture lookups are supported by ***all*** hardware that implements GLSL (and even by GL's predecessor assembly shader language).

In early shader models there was a limit to the number of indirections you could perform (e.g. at most, you could do 4 indirect lookups in a single invocation) but modern hardware no longer suffers from any such limitation. This is even less of an issue since your question mentions this is a vertex shader that you are doing the texture lookups in. Vertex texture fetches are a Shader Model 3.0 feature.

As for doing this efficiently, that is a different story. Generally dependent lookups are not cache/pre-fetch friendly, but sometimes if the access pattern (e.g. monotonic coordinate change) is correct this is less of an issue.

An interesting point to note is that any time a texture coordinate is computed (as opposed to taken directly from a per-vertex / per-fragment input) while the shader is being invoked, it is *technically* a dependent lookup. You do not need to fetch something from another texture in order to create this situation (though this is most often what people associate with ***dependent***).

---
Tags: opengl, glsl
---


# Question
Title: How to smoothly track and draw player movement?
I am currently using C# XNA Framework to simply connect some development concepts that I've learned/used over the past few months. Right now I have a Web Service that keeps track of connected clients and their 2D positions. I have a very small map that uses triangles to represent clients and their positions.

What I am seeing is my client updates very smooth (because I update my own position locally before sending it off to the web service), however, other triangles come in and appear choppy.

I use a web service that is called approximately every 20ms (and responds pretty quickly might I add). However, I know that XNA framework calls its update/draw methods approximately 60 times per second correct? Given this, there is ALWAYS going to be the appearance of choppiness.

Is there some strategy or pattern to handling this? I thought about implementing a method on the client side that basically says, give me start position and end position and I'll transition the triangle between the two points smoothly. But this may not be the right answer.

What are folks thoughts?

I am using a NetTcpBinding from WCF (Duplex). Is this technology simply too slow?

Is the right strategy simply to let the Service always tell me where the other clients are and the client simply draws them there?

Or does the client compute other information and make assumptions etc?

Thanks for any information on this topic!

# Answer
> 0 votes
> Or does the client compute other information and make assumptions etc?

I think what your looking for is Client Side prediction. You need to predict where other clients are going to move using previous movements. Whenever you get an update from the server, you need to start reconciling the errors introduced by your prediction algorithm. Your prediction algorithm doesn't need to be brilliant, calculating a player's trajectory based on previous positions would be fine.

When you reconcile errors, you might want to consider using curves to interpolate your value displayed on the player's screen to the actual value received from the server. If you just snap to the correct value, you will get a lot of jitter in your output.

Really good links for further reading:

---
Tags: xna, c#, 2d
---


title: Walking Sprite animation Cocos2D

text:
# Question
Title: Walking Sprite animation Cocos2D
I am new to cocos2D development. Basically I want to develop game in which i want to move sprite forward with walking kind animation, must look real. Any help will be appreciated.

# Answer
Basic sprite animation is really simple:

```
int frame_to_play = (game_tick * target_fps / tick_rate) % number_of_frames;

```

The result will tell you which frame (the `frame_to_play`-th) to show.

`game_tick` would be some kind of frame counter that just counts up (has to tick at least as fast as your animation is meant to be played).

`target_fps` is the framerate at which your animation should play (this must not be larger than `tick_rate`).

`tick_rate` is the amount of increments to `game_tick` per second.

`number_of_frames` is really just the number of frames in your animation cycle.

Note that this will create a linear/repeating animation (i.e. no partial loops or "ping pong" playback). If you want something else, you'll have to add some more logic.

How to make it look right/real? That once again requires some experimentation: Experiment with the speed your character moves (most likely something fixed/predetermined) as well as the framerate of your animation.
> 1 votes

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


# Question
Title: Hobbyist game dev, want to create async multiplayer game. Are server costs manageable?
I want to make the game I want to play, and that game happens to be an asynchronous multiplayer game. Think Hero Academy or Hearthstone, where there are 2 players and each submits moves to a central server. Alternatively (and not ideally), clients connect to each other and play is limited to a fixed window of connection, but still there needs to be a central server to acquire new opponents.

That said, this is very much going to be a hobby type endeavor - I'm just one guy after all. This is not going to commercially support itself. If I have 100 players ever, that would be fantastic.

Given that I'm going to have to eat server costs myself, what are my options for getting a server? I don't need much bandwidth or CPU, due to the nature of async games - only the sending of the gamestate/current move, and perhaps some checking of legal moves. Going to Amazon or getting dedicated hosting seems drastically overkill for what I want.

If it makes a difference, I'm intending to learn and use Unity for this.

# Answer
> 2 votes
This really depends on your actual game, the networking code, and (especially) the number of concurrent users.

However, creating some asynchronous gameplay is really trivial and easy to scale, as long as you keep your data to a manageable amount.

You won't need any expensive or powerful server for this. A typical HTTP server with scripting support (e.g. PHP, Perl, ASP, etc.) should be sufficient for a start.

There won't be permanent traffic or connections. A game client would connect to the server and use a simple HTTP request to get the status of games. It can then use a second request to download the current state of a game as well as submit it's changes/current state as a third request.

If done right, this kind of games causes hardly more traffic than some kind of blog or forums. Just make sure to not hardcode IPs. Use a (sub) domain you're in control of, that you can just redirect to a new/better server (or load balancer) if the need to do so arises later on.

As for actual server hosting, a simple hosting package for maybe 10 or 20 $ a month should be more than sufficient. You might also be able to host the server at home for a start (especially during an early beta of some kind; e.g. using a barebone system like Zotac's ZBox), but this is of course depends on your own internet connection etc. Before picking any offer, just make sure the hosting of games (not necessarily game servers) is allowed. Unless you want to write your own server from scratch, you won't need root access.

---
Tags: multiplayer, server, costs
---


title: Animating values using splines

text:
# Question
Title: Animating values using splines
I'm trying to create a system similar to Blender's f-curves or Unity's animation curves (google it, I'm not allowed to post more than two links yet). It's basically a 2D spline where time is on the X-axis and the value is Y. Given any X value there's only one Y, so no loops. The user can then add points and modify the tangents for those points. Something like this:

My current implementation uses cubic bezier curves, but I'm kinda stuck on how to calculate the Y value given a certain X (which is the time). After looking around a bit I found two interesting descriptions of it here and here, and also some code for one solution (h\**ps://github.com/hfink/pixelnoir/blob/master/player/src/roots.h). The problem is that I need to calculate t by solving the cubic bezier curve for X, which seems like a lot of work (for the CPU).

Is this the way it's usually done? Are there any better ways to represent the spline that avoids solving the equation?

My usecase is simple scaling/rotation/translation animations for 2D sprites to get some nice groovy feeling (like most 2D games released for mobile).

**Edit**

I'll describe the problem a bit more in depth to avoid confusion.

In my implementation the curve is 2D, i.e. the control points are (x,y) pairs. This means that I can freely move around all of them on a 2D plane. I'd say this is the most common case of bezier curves in graphics (think Illustrator, HTML5 canvas, QGraphicsScene, etc). This makes it possible to create the following two curves by just changing one of the control points:

These are drawn with Y on the vertical axis and X on the horizontal.

When evaluating a 2D bezier curve equation you're actually evaluating two equations, `Y(u)` and `X(u)` (I'm using `u` instead of `t` to avoid confusion further down). So when moving one of the control points (`P1` or `P2`, using wikipedia's names) along the X-axis I'm changing `X'` (the `X` derivative) in its corresponding point.

When editing the curve it's usually presented with the `X` axis as time and `Y` as the actual value. I.e. `X` increases by some `dt` each tick. So to calculate the `Y` value at a certain point in time I need to find which `u` to use since `Y` is defined as `Y(u)`. In my case I know that `X(u) = t` which means that I need to solve that equation to get `u` and then plug that in to `Y(u)`.

I could switch to a 1D curve, but that doesn't give the same flexibility since the control points in the middle would be scalars. I.e. I wouldn't be able to scale them, just define the start/end derivative in the point.

So the questions are:

* Can I convert this 2D curve to 1D given my contraints?
* Is there any other way increase the flexibility? Maya seems to have "weighted" and "non-weighted" tangents.

# Answer
> 0 votes
You didn't specify language, but this is my implementation, P1 and P2 are curve points, while CP is control point for that segment, you would probably need only Y coordinate is my guess:

```
float temp1 = 1.0f - position;
float temp2 = temp1*temp1;
float temp3 = position*position;

float x = temp2*p1.x + 2*temp1*position*cp.x + temp3*p2.x;
float y = temp2*p1.y + 2*temp1*position*cp.y + temp3*p2.y;

```

---
Tags: mathematics, animation, splines
---


# Question
Title: How can I have my third-person camera track slightly ahead of the player as he or she moves?
I have a 3rd person camera controller in a top-down game. I have my cameran following the player and I currently use linear interpolation to make the movement smooth and a little laggy. But I would like to do the opposite: when the player moves in a certain direction the camera moves a little bit ahead, so as to reveal more of what is ahead of the player.

```
    void Update ()
    {
            var newX = player.transform.position.x;
            var newZ = player.transform.position.z - 17;
            var y = transform.position.y;
            var targetPosition = new Vector3 (newX, y, newZ);
            transform.position = Vector3.Lerp (transform.position, targetPosition, 0.01f);
    }

```

# Answer
> 3 votes
This is a lot easier when you put an emplty child object on your character for the camera to track instead.

Imagine your player is being pulled by an invisible dog whenever he moves and when not moving the dog sits next to the player. If your camera is lerping its position to that invisible dog instead of the player, the result is your character still moves and is controller by your character controller but your camera tracks ahead to the empty game object (or our invisible dog called Bingo.)

If you want the camera to *always* be ahead of the character then child an empty game object to your player and place it N number of units ahead of your character (however far you like according to your prefences.) If you want it to return to the player when he isn't moving then leave it at 0,0,0 local position.

In your script (which I assume is attached to the camera) you can reference that objects transform using the Unity3D insepctor instead of using your player transform so your camera will lerp toward where the player is looking.

```
public Transform trackingHelper;

void Update ()
{
        var newX = trackingHelper.position.x;
        var newZ = trackingHelper.position.z - 17;
        var y = transform.position.y;
        var targetPosition = new Vector3 (newX, y, newZ);
        transform.position = Vector3.Lerp (transform.position, targetPosition, 0.01f * Time.deltaTime);
}

```

**Please note:** as you are using Update and not FixedUpdate that you should multiply your last Lerp argument by Time.deltaTime to attribute for frame stutter.

If you want it so this only occurs when your character moves then you can lerp the position of the child empty game object in another script so that it moves from 0 to N units when the player is moving. I am assuming the axis is the Z axis for the tracking helper being 5 units in front of your player and that this script is attached to the helper itself:

```
public float distanceAhead = 5f;
public GameObject character;

private Vector3 prevPosition;

void Update()
{
     float newZ = 0;
     if(!CheckCharacterIdle){
         newZ = distanceAhead;
     }
     Vector3 targetPosition = new Vector3(0,0,newZ);

     transform.localPosition = Vector3.Lerp (transform.position, targetPosition, 0.01f * Time.deltaTime);
}

//If your characters utilise rigidbodies you can probably use
// the isSleeping() function to check for movement / interaction
// otherwise use manual comparison of position each frame
bool CheckCharacterIdle(){
    Vector3 curPos = character.transform.position;
    if(lastPos == curPos){
        lastPos = curPos;
        return true;
    }else{
        return false;
    }
}

```

This should sort the issue, I hope it helps.

---
Tags: unity, camera, third-person-view
---


# Question
Title: How can I make an animation using arrays?
I want to take an array of sprites, for example

```
sf::Sprite animation[3] = { stepLeft, inMiddle, stepRight };

```

and construct an animation by looping them. Is this possible? How do I go about it?

# Answer
> 3 votes
Yes, you can perform sprite animation by using an array of sprites. However, you cannot simply loop over them using a for loop for example, as only the last the sprite in the array would be rendered.

To avoid this you can track the current index into the array, and use this to submit the corresponding sprite to the renderer. After each frame you can accumulate the frame times and after a desired length of time increment the current animation index so that the next sprite in the animation is rendered.

E.g.

```
if( m_accumulatedTime >= m_animFrameTime )
{
    // Reset timer
    m_accumulatedTime = 0;

    // Move to next frame of animation
    m_currentAnimIndex++;

    // Loop the animation
    if( m_currentAnimIndex > m_animClipSize - 1 )
        m_currentAnimIndex = 0;

}

```

---
Tags: c++, animation, sfml
---


title: Level Editor for iOS Games

text:
# Question
Title: Level Editor for iOS Games
What would be the best way to design "Angry Birds" - levels. I wanna develop my own Angry Birds but I don't know how I should design the levels. Is there any good tool/level editor for that?

The app is going to be an iPhone app and I use SpriteKit.

# Answer
> 1 votes
Build your own level editor - it's the conclusion I came to after having developed several games. A simple editor would involve creating some simple buttons (the items in the levels) and some simple logic for positioning, rotating and scaling them on stage. After you have all the items in a level just push their details (position, type, etc) to an/or several arrays and encode these to string.

All you have to do in your game is decode the level strings and loop through your data and place the items in the level that has just started.

Good luck with your game.

---
Tags: game-design, ios, iphone, level-design, xcode
---


# Question
Title: How can I load all of my scenes at startup?
I want all of my scenes to load when the loading screen is shown (but only one should be shown at a time) so I can switch between them quickly I have tried this:

```
if (Application.GetStreamProgressForLevel (2) == 1) {
    Application.LoadLevel (2); Application.LoadLevelAdditive (1);

```

and:

```
(Application.GetStreamProgressForLevel (2) == 1) {
Application.LoadLevelAdditive (2);
Application.LoadLevelAdditive (1);
Application.LoadLevel (1)

```

# Answer
> 1 votes
First of all loading all scenes into memory may not be a good idea. Depending on your scene size, you can quickly exhaust all the available memory. In addition why do you want to load additive all your scenes? Eventually use a single scene if you know that you are loading all the scenes anyway.

In any case, just a little clarification. When you load a scene into memory, all the objects in the scene will be added to the hierarchy (scene graph). At that point you cannot distinguish no more which object belong to which scene.

When I want to keep track of which `GameObjects` belong to which scene (usually when I use load level additive and lightmaps), I organize my scene using a root node for each scene, in such a way that all objects belonging to the scene `N`, have a common root node `Root_N` . This way if you want to unload the scene `N -1` you can just call Destroy on the relative root `GameObject` (`Root_N -1`).

I guess that in a simliar way if you attach a script to the root GameObject of each scene (starting from the second ), that is responsible for disabling the relative node in Start method, you will obtain a similar result.

```
public class RootSceneHandler : MonoBehavior // attached to the root gameobject. Disabling the root node will provoke each children to become invisible too.
{
  void Start()
  {
    SetActive(false);
  }
}

```

---
Tags: c#, unity, loading
---


title: UI in Canvas-Games

text:
# Question
Title: UI in Canvas-Games
I am quite new to programming with `<canvas/>` and WebGL, but very familiar in HTML5. So far, I have made to render some entities on the `<canvas/>`. Next would be to add a simple HUD to it.

I wonder, though, would it be a good idea to use HTML-tags for the HUD and UI elements? That would make them a lot easier to create, but perhaps that would have a big impact on performance. Is it worth to make a `<canvas/>`-Only HUD engine?

I'm even tempted to replace the sprites with `<div/>`-Elements, since they're only rotated and moved, so perhaps a css-rotation is better suited?

# Answer
> 1 votes
I'd done some preliminary testing using Dojo UI floating over a canvas, and I found performance to be horrendous. This sparked some research into the availability of canvas-rendered UI toolkits. I was happy to come across Zebra UI, and have had great success with integrating it into my game's engine.

The author is quite in-touch with Zebra's user-base, and is very welcoming when it comes to working out issues and discussing new features. I'd strongly recommend using Zebra UI.

http://www.zebkit.com/

---
Tags: sprites, html5, html-canvas, hud
---


# Question
Title: How should I prepare for migration from D3D9 to D3D10 or D3D11?
I'm considering a Direct3D9 texture streaming solution, but my company will eventually be going to D3D11 in the future.

I wanted to make my solution as forward compatible as possible, so I was hoping that someone could give me some feedback on exactly what D3D11's capabilities were and what I should be looking for when preparing such a migration?

For reference, here's what I'm considering on D3D9:

* Load low res mip maps for all meshes at load time
* Create bounding boxes around each of my objects and detect when I'm inside any given bounding box
* For any bounding box that I'm inside of I will load the high res portion of the mip map
* Any bounding box that I've left I'll unload the texture from
* I've also got to cook up some scheme to manage fragmentation of the GPU memory, initially I'll probably just cycle the GPU memory whenever the camera and my objects are still

# Answer
> 4 votes
Direct3D10 and Direct3D11 are very similar in terms of their API design, but 10 is a significant break from D3D9. No matter what you do you're going to have quite a bit of work ahead of you, because not only does the API surface change drastically, so to do many of the fundamental basics become more involved.

The best way to protect yourself against such a migration is to try to isolate your D3D9 code as much as possible: minimize the number of places you touch the actual D3D9 API itself, and expose higher-level concepts than D3D does from your own rendering API. By this I mean, if your rendering API is basically a 1:1 mapping to the underlying D3D types... so you expose vertex buffers, index buffers, shaders, textures, et cetera... then you will have a harder time dealing with D3D10's notion of a shader input layout, which you now have to expose and weave through all your code. If you exposed a higher level "drawable" object that encapsulated most of those concepts within it, you may not need to touch as much code.

Fortunately for you, Microsoft has documented several of the high-profile concerns that will occur when migrating between D3D9 and D3D10. I suggest you peruse that document, and the follow-up for D3D11 which is less intense but still useful.

---
Tags: textures, directx11, directx9, streaming
---


# Question
Title: Box2D + Citrus Engine - Proper Pong Paddles
I am creating a pong clone for my first Citrus Engine project using Box2D. I've tried two types of paddles, both do not fully work.

1) Paddle is a dynamic body with a restitution of 1.0 and friction of 0.0.

**Problem:** The bouncing ball will move the paddle when it collides.

2) Paddle is a kinematic body type.

**Problem:** The paddle will not detect collision with the walls of the game screen.

**Question:** How can I create a paddle object that will not be affected by the collision of the ball while colliding normally with the game walls?

# Answer
> 0 votes
Try applying a Prismatic Joint to a Dynamic Body. That should stop the ball from moving your paddle.

---
Tags: physics, box2d, flash, starling
---


title: Can I use memcpy() with XMMATRIX?

text:
# Question
Title: Can I use memcpy() with XMMATRIX?
I.e. can I do this:

```
XMMATRIX dxMat;
Matrix myMat;
std::memcpy(&myMat, &dxMat, sizeof(XMMATRIX));
std::memcpy(&dxMat, &myMat, sizeof(XMMATRIX));

```

`Matrix` is my own class which contains 16 contiguous float variables (only). Also can I do the same with my vector class (4 floats) and XMVECTOR?

In other words, is XMMATRIX a POD?

# Answer
XMMATRIX is a Plain Old data structure, it is defined like this:

```
struct XMMATRIX {
  XMVECTOR r[4];
};

```

You can use memcopy with POD. XMMATRIX is not different, it is only designed so it is always 16byte aligned so it can be used with SSE registers.

But keep in mind that using memcpy is error prone and could introduce hard to find bugs. I suggest you use a constructor in your Matrix class that takes XMMATRIX, and copy it internally. This way you take advantage of: 1. Type safety, instead of the `void*` that is passed to `memcpy`. 2. Your code won't have memcpy all over the place. So less bugs, and even if you used `memcpy` inside the constructor and have a bug you will only solve it once. According to the DRY principle.
> 2 votes

---
Tags: c++, memory, directxmath
---


# Question
Title: How do I detect multiple sprite collisions when there are >10 sprites?
I making a small program to animate the astar algorithm. If you look at the image, there are lots of yellow cars moving around. Those can collide at any moment, could be just one or all of them could just stupidly crash into each other.

How do I detect all of those collisions? How do I find out which specific car has crash into which other car?

I understand that pygame has collision function, but it only detects one collision at a time and I'd have to specify which sprites.

Right now I am just trying to iterate through each sprite to see if there is collision:

```
for car1 in carlist:
    for car2 in carlist:
        collide(car1, car2);

```

This can't be the proper way to do it, if the car list goes to a huge number, a double loop will be too slow.

# Answer
There is no 'proper' way, just different approaches that vary from simple-but-slow to complex-but-fast.

You can stick with that method, if your car list is small enough. However, there is a bug in your basic algorithm, as it will compare each pair of cars twice. To fix that, your second loop should start the value of `car2` from the position in the list after `car1`.

Most faster methods of detecting collisions like this use spatial properties of the objects so that the objects can be ordered in such a way that 1 comparison might reject multiple pairings.

Probably the simplest approach using this is to sort the objects along one axis (x or y) and use that knowledge to exit the loop early. eg. Sort cars by x ascending, and when you find a `car2` with an x value greater than the right-hand side of the current `car1`, you know you no longer need to compare it against any more possible `car2` objects as they must be even further away.

A more complex approach is to divide the world in 2 dimensions using a grid of squares that are bigger than the objects inside them. You track which grid square each object is in, and conversely which objects are in that grid square. So each object only needs to check for collision against other objects in that square (and maybe the 8 adjacent squares). Technically it's a 'bin' data structure.

Beyond that, there are other ways to partition the world that change as the objects move. A common example is a quadtree which subdivides the space to keep a similar number of objects in each square. Others can be found under the general term of spatial partitioning but as with any data structure, some are optimised for quick lookup while being expensive to add or change data within them.

In your particular case... I would probably just stick with the 2 loops, and upgrade to the coordinate-sorted approach later if necessary.
> 4 votes

# Answer
I see that this is an older question, but I'd like to share my own solution to this problem, as it's part of a recent project of mine and I just cleared out some collision detection that was exactly like yours, more or less. I had two queues of 'good-guys' and 'bad-guys' and every frame I would do this:

```
#old code!! not great!! :(
for goodguy in goodqueue:
    for badguy in badqueue:
        if goodguy.rect.colliderect(badguy.rect):
            goodguy.got_hit()
            badguy.got_hit()
#i don't recommend this approach!! :(

```

Even with my simple game, which might have one Player object, 3 - 4 'good guy' Bullets it fired, comparing it against the 3/5/7 bad guys in the badqueue and their Bullets they fire at random intervals… that is a *lot* of iterations that we don't need!

This is the current state of my project's hit detection: it's a little more code, but it will scale so much better and flat out ignores collisions that aren't happening.

```
for obj in GAME.allqueue:
    obj.update()
    hit_list = pygame.sprite.spritecollide(obj, GAME.allqueue, False)
    if not hit_list:
        pass
    elif obj in GAME.goodqueue:
        for otherobj in hit_list:
            if otherobj in GAME.badqueue:
                obj.got_hit()
                otherobj.got_hit()

```

I'll explain what's going on here.

First, the loop calls `obj.update()`, which does normal game logic-type stuff; moves sprites, determines if they're fired, etc etc.

The next line, `hit_list = pygame.sprite.spritecollide(obj, GAME.allqueue, False)`, tells PyGame to generate a list of all the things that `obj` is colliding with in `GAME.allqueue`, which is an instance of `pygame.sprite.Group` (as I would imagine your `carlist` is). This is fantastic, because now we just have a list of what's actually colliding with that object.

The next two lines: `if not hit_list: pass` basically tell the game *if the `hit_list` is empty, don't do anything collision-related and continue on with the game loop.* The line `if not a_list` is a Pythonic idiom which is basically the same as `if len(a_list) == 0`, or "if this list is empty", or whatever you want to call it. Basically - this is where the game decides if it should even bother with collision detection, or move on to the next important step.

The rest of the code may be a bit situational and not apply to your game/simulation, as my game basically works to avoid 'friendly fire' between both good guys AND bad guys. *(It basically makes sure two colliding objects are in separate queues, so only 'good guy meets bad guy' collisions are processed)* **However** -- In your situation, I believe you'd be able to make use of `pygame.sprite.spritecollide` in a similar fashion.

```
for car in carlist:  #let's get a list of everything THIS car is colliding with!
    cars_hit_list = pygame.sprite.spritecollide(car, carlist, False) #False tells PyGame NOT to auto-kill the whole list of results!
    if not cars_hit_list:
        pass    #if the cars_hit_list has no length, do nothing!
    else:    #this is assuming you just want all cars to crash…
        for crashedcar in cars_hit_list:
            handle_the_crashes() #whatever you actually do to crash the cars

```

In my humble opinion -- as long as you're using the `pygame.Sprite` objects to handle your sprites and the various `Group`s they belong to, using the list you get back from `pygame.sprite.spritecollide` will be more satisfying than just iterating over every possible combination of potential collisions to see if they are occurring.
> 1 votes

---
Tags: collision-detection, python, pygame
---


# Question
Title: How can I model a "weapon overheating" mechanic?
I want to create a weapon overheating system very similar to the plasma rifle in Halo. You can watch a video of the plasma rifle firing.

What I want to do is to create a flexible logic that can be used for multiple weapons for different in-game feelings. Here is my proposed system

1. Create a bar that is split from 0 - 100.
2. Each bullet has a heat value as an integer.
3. Every bullet adds this value to the bar.
4. The bar has a cooldown set as some value per second.
5. If the bar goes over 100 with any bullet fire the bullet still shoots but then the weapon is deactivated for a period defined as it's "cooldown."

Now this system is very simple but visually it will be very linear, with a simple growth and decay. I wanted to try to create a more exponential system that would mean the bar would jump quickly to the middle then remain and hover near the top / hot bit of the bar for a long period to create a sense of anticipation just before it overheats.

What would be a good formula to achieve that result?

# Answer
To have the gun heat up quickly but reach its overheat threshold slowly, you could take the gun's current temperature into account in the heat dissipation, rather than having a constant rate of heat dispersion. That's actually how it works in the real world: the rate of heat / thermal transfer is proportional to the difference in temperature. Wikipedia has a good article on Heat Transfer that covers this.

I strongly recommend a decimal value instead of int for tracking heat on your weapons, and to not have a strict cap so much as a threshold over which the weapon goes into cooldown to prevent damage from overheating.

A heat transfer rate equation might be helpful.

```
Rate = k•(T1 - T2)/m
Where k is the heat transfer coefficient of the gun's material.
    Since you're not modelling a specific
T1 is temperature of the world around the gun
T2 is temperature of the gun
m is mass.

```

You can probably implement this for your game as

```
void cooldown(double timeElapsed) {
    gunHeat -= timeElapsed * COOLING_RATE * gunHeat;
}

```

Where gunHeat is how much hotter than the surrounding air your gun is, aka your heat variable; COOLING\_RATE is a constant value for the gun according to its materials and how good it is at keeping itself cool; and timeElapsed is the fraction of a second of the game world that has been simulated since `cooldown()` was last called. Then you just add a constant value to gunHeat whenever the gun fires.

An improved version could take into account the temperature of the environment around the player:

```
void cooldownBetter(double timeElapsed, double localTemperature) {
    gunTemperature += timeElapsed * COOLING_RATE * (localTemperature - gunTemperature);
}

```

In either case, when the gun's heat/temperature is above a certain threshold, it stops shooting until the heat drops below a threshold. This could be the same threshold, so that shooting would effectively just slow down, or a lower heat/temperature so that you have to wait but then begin shooting again as fast as before.

You'll have to test and tweak COOLING\_RATE to match what you want to go for for each gun.
> 5 votes

# Answer
Your weapon needs two values: the current `heat` value (int, probably) and a `cooldown` timer (float). Initialize both to `0`.

When a shot is fired, add the bullet's `heat` value to the gun's. Cap it at `100`. When this value reaches `100`, set the `cooldown` value to your cooldown period time in seconds. Reduce this by your time delta every frame, clamped at a minimum to `0`. Don't let the gun fire shots if `cooldown` is not `0`.

In pseudocode:

```
Gun.fire(bullet):
  this.cooldown = max(this.cooldown - game.time_delta, 0)

  if this.cooldown == 0:
    create_and_fire_bullet_instance(this.muzzle.transform, bullet)

    this.heat = min(this.heat + bullet.heat, 100)
    if this.heat == 100:
      this.cooldown = 3 seconds

```
> 3 votes

# Answer
Try this out. Track `shots` and `heat` separately, and assign:

```
heat = round((shots * 100) / (shots + 100));

```

You'll need to tweak it to get the exact behavior you want, I'm sure, possibly with methods like:

```
heat = min(round((shots * 110) / (shots + 110)), 100);

```

but the basic curve should be pretty close to what you want.

For cooldown, decrement `shots` at some rate (I suggest trying 1 per 300 ms and tweaking from there) and recalculate `heat` as above.
> 0 votes

---
Tags: gui, logic, first-person-shooter
---


# Question
Title: How would I implement procedurally generated tiles in libgdx?
I'm creating a simple top down Zelda-esque game in libgdx, and I want to implement tile-based dungeons that are procedurally generated, similar to ***this.***

Libgdx does have a class called TiledMap which would seem to fit my needs, however documentation outside of the official docs suggests that TiledMaps can only be used in conjunction with .tmx files, or in other words pre-designed maps. I've done a fair amount of Googling to no avail, so I'm asking here as a last resort hoping that someone has experience using libgdx for dynamically-generated tile maps.

edit: Could I use ***StaticTiledMapTiles*** in conjunction with the tutorial I linked to above to achieve my goal?

Thanks!

# Answer
Based on advice from /r/gamedev, I've decided to forgo the use of libgdx's TiledMap, etc. built-in classes and just build my own.

I can go into greater detail if requested, but here's what I've done, essentially.

1: Generate a dungeon using the algorithm I originally linked to, and store tile coordinates (not pixel coords) using a `Coordinate` class I made in a `HashMap<Coord, MapTile>`. `MapTile` is just a class that has data about the type of tile.

2: In the `draw()` function of my main class I added the following code

```
ConcurrentHashMap<Coord, MapTile> dungeonMap = dungeonGen.getMap();
        for(Entry<Coord, MapTile> entry : dungeonMap.entrySet()){
            Coord coord = entry.getKey();
            MapTile tile = entry.getValue();

            if((inCameraFrustum(coord.getX() * tileSize, coord.getY() * tileSize, 100))){
                game.batch.draw(dungeonGen.getTileTexture(tile),
                        coord.getX() * tileSize, coord.getY() * tileSize);
            }

        }

```

Which iterates over every `Coordinate` in the `dungeonMap` and draws the tile (if the coordinate is in the camera frustum) with a global `tileSize` offset.
> 2 votes

# Answer
You can create tiled maps on without using .tmx.

```
TiledMap map = new TileMap();
MapLayers layers = map.getLayers();

TiledMapTileLayer layer1 = new TiledMapTileLayer(width, height, tile_width, tile_height);
Cell cell = new Cell();

cell.setTile(new StaticTiledMapTile(texture_region));
layer1.setCell(x, y, cell);

layers.addLayer(layer1);

Each of these classes are in the docs for libgdx.

```
> 9 votes

---
Tags: java, libgdx, tiles, procedural-generation, tilemap
---


title: Anti-aliasing a sphere

text:
# Question
Title: Anti-aliasing a sphere
I render everything in my game in 2D with SpriteBatch with the exception of a spherical entity (orb) that I render as a spinning and dynamically lit (custom effect) sphere in 3D. I capture the sphere into a RenderTarget every frame and then use the image in the SpriteBatch to render in 2D. The composed image is aliased as any model.

I do not enable MSAA because various platforms that my game runs on (WinRT, as an example) do not support it. I tried FXAA as a custom effect, but the problem is that it does not appear to support transparency (I render the sphere on a transparent background).

My rudimentary solution is to render the sphere into a RenderTarget of size X and then render the result with SpriteBatch into a RenderTarget of size X/2. I set the SamplerState for the SpriteBatch draw call for the half size rendering to anisotropic, although I am not 100% sure this increases the quality of the final output dramatically (and at what cost?).

This solution appears to work fine but is not without its flaws. Mobile devices are slowed down by the multiple SetRenderTarget calls per frame, especially since I render more than one orb type.

Are there other approaching to this?

# Answer
> 4 votes
Well for antialiasing there are many approaches like yours, downsampling an oversampled picture, which is very costly.

Using a renderTarget seems also overkill to me.

The best option would be to make a custom shader for you SpriteBatch that does parametric sphere ray-casting (not that expensive, was working on my old Sony Ericsson Mini Pro).

You can apply your light shading, textures, etc. and use the smoothstep function on the borders, it is not even needed if you add a "glow". Plus you'll have a lot of control on effects you want to add.

Other advantage fragment shader process only once for each pixel, so its the same for 10 or 100 orbs.

Example here of what I've done with this approach: https://www.shadertoy.com/view/XdsGDX (btw shaderToy is a must when coding & debuging fragment shaders)

I'm using this approach for my 3D space game right now and I was able to display more than a hundred stars at 60fps like in the example on a integrated graphic chip.

# Answer
> 2 votes
If I would have to solve this I think I would use a simple small gaussian blur. As a shader this shouldn't be that big performance issue and simple to implement, and also be a very nice-looking approach.

---
Tags: xna, directx, monogame, sharpdx
---


# Question
Title: Is it bad-practice using left-handed coordinate system in OpenGL eye-space?
In the engine I am currently programming I want to use a left-handed coordinate system for eye-space instead of the glFrustum standard right-handed one. Is that in anyway considered bad practice?

# Answer
No, it's fine, you may use whatever coordinate system and handedness you prefer.

Just be aware of what you are doing so you can make the appropriate adjustments and assumptions.
> 3 votes

---
Tags: opengl, coordinates, projection
---


# Question
Title: Calculating wall angle and sliding in 2D
Got a new project recently where I don't use any physics engine, but it requires some basic phyiscs. Basically it's a 2d "top-down" game type. I would like to add a smooth wall collision which feels better than those "jumping" ones. So here is how bad it looks like, I easily calulated the collision point in this way:

1. Added the velocity to the player's position.
2. Checked whether the new position is in the wall or not.
3. Went backwards at that vector where it "came from" until reached the first non-colliding position.

Now that I have the blue position, I would like to modify the player's vector's angle with that purple angle (I guess). Because I want the next thing to happen when the player reaches that position:

* The player gets the wall's angle and walks next to it (of course only if the player still presses the key to move upwards) like in most AAA 3D games. For example TESV:Skyrim. If you are moving toward a wall or an object in a non 90° angle, then the player keeps moving but next to the wall/object.

I have already searched for solutions on Google and here aswell, but none of them fit my needs.
Would appreciate any help. Thanks!

EDIT:

* **Green Line**: Wall *(Top one, the bottom one just for help)*
* **Purple Point**: Player old position
* **Blue Point**: Player new position *(next to the wall)*
* **Red Line**: Vector between new and old position
EDIT 2:
Can't get it to work properly, at the edges of the walls the calculations fail. The player keeps teleporting, at the program freezes sometimes. (due the while cycles which are checking for the edges)

# Answer
> 3 votes
How many games do this is not with fancy changing of the velocity after the collision has been resolved, but instead the way they resolve the collisions or in your scenario, how you found the the player new position (blue P).

You explained that you simply retraced your steps along the vector to come up with that position. Instead of doing what you did, what is a fairly common way to resolve collisions and achieve this sliding effect is through projection. This and other collision detection / resolution approaches are discussed in great detail here.

By using projection you will end up with a sliding effect like you are looking for because you are resolving for a position that is along the wall using the shortest distance possible instead of simply backtracing your steps as shown in the following image:

To quote the above linked article on resolving collisions via projection, below is how you can find the projection vector and an interactive example can be found here.

> The formula for projecting vector a onto vector b is:
>
> proj.x = ( dp / (b.x*b.x + b.y*b.y) ) * b.x; proj.y = ( dp / (b.x*b.x + b.y*b.y) ) * b.y;
>
> where dp is the dotprod of a and b: dp = (a.x*b.x + a.y*b.y)
>
> Note that the result is a vector; also, (b.x*b.x + b.y*b.y) is simply the length of b squared.
>
> If b is a unit vector, (b.x*b.x + b.y*b.y) = 1, and thus a projected onto b reduces to:
>
> proj.x = dp\*b.x;
>
> proj.y = dp\*b.y;

To get the vector for the wall you just need to know two points on the wall. It could be two corners, the collision point and a corner, etc. Once you have two points you subtract the coordinates to find the resulting vector.

e.g. - Given P \<1,2\> and Q \<3,5\> then PQ = Q - P

= PQ \<3-1, 5-2\>

= PQ \<2,3\>;

If you have a library that can subtract the vectors this is even easier for you. I don't believe direction is important in this calculation but if I'm wrong and you find you are getting a weird behavior, try subtracting in the opposite direction and see if it helps.

# Answer
> 2 votes
This answer will focus on statement #3 in the original post, and is meant to supplement ToddersLegrande's answer

> 3 . Went backwards at that vector where it "came from" until reached the first non-colliding position.

That idea is prone to failure as you have found out, luckily there is a closed form solution available, I will do in-depth on that here.

---

Given a set of points on a line, plugging the coordinates into the line equation (y=m\*x+b) yields a system of equations which can be solved to find the slope-intercept form of the given line.

Starting with the player's position we assert that:

Then we also assert that the player's position after velocity is on the same line:

With enough information to define the line now available, we can solve for the slope and intercept of the players line of motion to find:

Applying the same technique to finding the slope and intercept of the wall yields:

By solving the system formed by these two line equations, we find a (rather large) formula which directly computes the intersection, I've formatted this as code just in case you aren't familiar with maxima

```
Vec2 FindIntersection(Vec2 player,Vec2 motion,Vec2 wall1,Vec2 wall2) {
    return Vec2(
        -(motion.x*(wall1.x*wall2.y-wall1.y*wall2.x)
        +motion.x*player.y*(wall2.x-wall1.x)+motion.y*player.x
        *(wall1.x-wall2.x))/(motion.x*(wall1.y-wall2.y)
        +motion.y*(wall2.x-wall1.x)),

        -(motion.y*(wall1.x*wall2.y-wall1.y*wall2.x)
        +motion.x*player.y*(wall2.y-wall1.y)+motion.y*player.x
        *(wall1.y-wall2.y))/(motion.x*(wall1.y-wall2.y)
        +motion.y*(wall2.x-wall1.x))
    );
}

```

---

Here's how I did it on Maxima:

```
(%i) FindIntersection(PlayerX,PlayerY, MotionX,MotionY, WallVert1X,WallVert1Y, WallVert2X,WallVert2Y) :=
    ''(solve(
        subst(solve([PlayerY=pm*PlayerX+pb,(PlayerY+MotionY)=pm*(PlayerX+MotionX)+pb],[pm,pb]),
        subst(solve([WallVert1Y=wm*WallVert1X+wb,WallVert2Y=wm*WallVert2X+wb],[wm,wb]),
            [IntersectionY=pm*IntersectionX+pb,IntersectionY=wm*IntersectionX+wb]
        )),
    [IntersectionX,IntersectionY]));

(%o) FindIntersection(PlayerX,PlayerY,MotionX,MotionY,WallVert1X,WallVert1Y,WallVert2X,WallVert2Y) :=
    [IntersectionX=-(MotionX*(WallVert1X*WallVert2Y-WallVert1Y*WallVert2X)
        +MotionX*PlayerY*(WallVert2X-WallVert1X)+MotionY*PlayerX
        *(WallVert1X-WallVert2X))/(MotionX*(WallVert1Y-WallVert2Y)
        +MotionY*(WallVert2X-WallVert1X)),
    IntersectionY=-(MotionY*(WallVert1X*WallVert2Y-WallVert1Y*WallVert2X)
        +MotionX*PlayerY*(WallVert2Y-WallVert1Y)+MotionY*PlayerX
        *(WallVert1Y-WallVert2Y))/(MotionX*(WallVert1Y-WallVert2Y)
        +MotionY*(WallVert2X-WallVert1X))]

```

---
Tags: collision-detection, actionscript-3
---