title: Tile map collision and object handling

text:
# Question
Title: Tile map collision and object handling
I want to program a game. In this game there is a tile map and objects that interact with it and them self.

For that I made first a TileMap class, in it is only the data of the tile map. Its a very simple tile map without layers and a tile have only and integer id.

Secondly I have a class TileMapRenderer that draws the map. It iterate threw all tiles and draw them dependent on there id.

So now I don't know how I can go further. How I handle different objects like players, animals, table, chests and let them "clean" interact with the tile map..... Has someone a idea?

And at last another problem with collision. \[URL=http://www.directupload.net\]\[IMG\]http://s1.directupload.net/images/140303/q2n5ebsm.png\[/IMG\]\[/URL\] If in this example the speed is smaller than 48, its perfect but if it bigger than 48 there is a problem. Because normally I check whether on the new Position (current position + velocity) would be a collision and if yes put it a tile before. But in a second case the player would be glitch threw on tile. How I should handle collision in relationship to a object system.

I hope there is someone how know a good solution.

# Answer
I suggest to keep a tile as simple as possible, like you do with only giving it an ID, perhaps a bool for collision or any other simple things to identify what type of tile this represents. A class like this should look like, (All pseudo code, i'm a C# guy but implementing this in java should be a breeze if you know the basics):

```
class Tile
{
    public int baseID;
    public bool Collision;
}

```

This is pretty much all you need to draw everything necessary and have collision working. You just build layers of these in this order from back to front from left to right from top to bottom. (It does not need to be in this order if every sprite fits within the tilesize.)

```
Tile[,] baseMap = new Tile[100,100]; //Put in all your backgrounds
Tile[,] objectLayer = new Tile[100,100]; //Put in all your objects
Tile[,] anotherObjectLayer = new Tile[100,100]; //Put more objects in a separate layer.

```

You would draw it like this:

```
for (int y = 0; y < mapheight; y++)
{
    for (int x = 0; x < mapwidth; x++)
    {
        draw(baseMap[x,y]); //Obviously you need your implementation of ID to texture here.
//If your tiles are 32*32 you would draw it on x*32, y*32, width 32, height 32.
        draw(objectLayer[x,y]);
        draw(anotherObjectLayer[x,y]);
//Drawing it like this will result higher/further tiles to be covered by larger objects like tree's.
//You need to find out where the moving things are, like the player, to draw them on the correct [x,y] iteration.
    }
}

```

If you need slightly different variables and parameters for a layer you are free to create another class for these. Maybe inheriting from the base tile class will do you good. Here is an example for a chest tile:

```
class Chest : Tile
{
    //The baseID would be it's texture.
    //The Collision can be used to have hidden chest or buried treasure.
    int ChestItemID; //The item ID this chest holds.
    List<int> MultipleItems; //For loot frenzy.
    bool MonsterInABox; //For oldschool feeling
    int Lock; //First get the key with this ID to unlock it.
}

```

Since this class inherits from tile it is perfectly fine to put this in one of the above layers so you do not have to create a complete layer arrays just for chests.

Next time make a new question for the collision issue since it is so different. Anyway, you glitch true since your tiles are probably 48\*48 and this your character never steps on the tile with the collision on it. Therefor you should write a method that predicts what tiles your crossing. Depending on your needs you can check every pixel or just one step in between. Another option would be to calculate the next tile the player goes to remembering the first, with a tilemap like this it is very simple to check which tiles have been crossed between those points. First ask yourself if you need to move at speeds larger then your tiles, and what would be the maximum speed? If you just use the fast moving for debugging create a debug method for it.
> 0 votes

# Answer
From what I can gather, your second problem is caused by checking the end position and assuming that there are no obstacles in between. One solution would be to define a collision detection step-size (`stepSize`) which would have to be smaller than the size of your smallest obstacle. Then instead of checking just the end position, check for obstacles at `playerPosition + stepSize`, `playerPosition + (2*stepSize)`... until you reach the end position.

This is just a quick and dirty method and will likely fail when not using rectangles. Another method would be Cohen-Sutherland, which is designed for clipping on a rectangular viewport. There are many other ways, depending on how complex the layout could get. Reading up on Clipping will be useful, particularly Sutherland-Hodgman for non-rectangular obstacles.
> 0 votes

---
Tags: java, tilemap, collision-resolution
---


title: Random movement avoiding walls

text:
# Question
Title: Random movement avoiding walls
I have a top-down game you can scroll through placeable tiles I have some NPCs that do nothing at the moment I want them to freely move around without going through wall tiles etc.

For the freely moving I have code and it works fine but they walk through walls:

```
if(new Random().nextInt(4) == 0){
   x+=1;
}
if(new Random().nextInt(4) == 1){
   x-=1;
}
if(new Random().nextInt(4) == 2){
   y+=1;
}
if(new Random().nextInt(4) == 3){
   y-=1;
}

```

How can I make it so they don't walk through walls?

All the solid tiles are stored in an arraylist

```
public static ArrayList<block> s = new ArrayList<block>();

```

and then have the `for` loops for them and each block has its own rectangle around it.

# Answer
You don't check if the NPCs are colliding with a block, there are two things you could do:

1. Check if the tile the NPC want to move on is solid.
2. Move the NPC, then check if they are standing on a solid block, if yes then move back.

I would suggest method one, so you could do something like that:

```
int r = random.nextInt(4);
if(r == 0 && validMove(x+1,y)){
   x += 1;
}
if(r == 1 && validMove(x-1,y)){
   x -= 1;
}
if(r == 2 && validMove(x,y+1)){
   y += 1;
}
if(r == 3 && validMove(x,y-1)){
   y -= 1;
}

```

So they will only move if they will be on a valid position.
`validMove(x,y)` could look like the following code:

If your `ArrayList` is sorted you could try this:

```
boolean validMove(int x, int y) {
    Block b = s.get((x-1) + (y-1)*mapWidth);
    if(b.getX() == x && b.getY() == y) {
        return false;
    } else {
        return true;
    }
}

```

How does that work? Let's do a simple example, imagine you have an `ArrayList` with following coordinates:

```
{(1,1);(2,1);(3,1);(4,1);
 (1,2);(2,2);(3,2);(4,2);
 (1,3);(2,3);(3,3);(4,3)}

```

We have `mapWidth = 4` and `mapHeight = 3`.
So now you have `x = 2` and `y = 3`, you should get `(2,3)` which is at `Index 9`.
The calculation is `i = (2-1) + (3-1) * 4 = 1 + 2 * 4 = 1 + 8 = 9`.

Else you can do it like this (almost similar to Byte56 answer), but there you wouldn't have fast access if the map is big.

```
boolean validMove(int x, int y) {
    for(Block b : s) {
        if(b.getX() == x && b.getY() == y) {
            return false;
        }
    }
    return true;
}

```

For method 2 you could use intersection checks.
> 0 votes

# Answer
You need to create some kind of `isSolid(x,y)` function. Unfortunately you're storing all your blocks in an array list, so it's going to be difficult to do this in a fast way, but that's up to you to figure out.

Once you have your `isSolid(x,y)` function, you can modify your code like:

```
if(!isSolid(x+1, y) && new Random().nextInt(4) == 0){
   x+=1;
}
//etc.

```

A naive approach to your `isSolid` function can be:

```
boolean isSolid(int x, int y) {
    for(Block b : s) {
      if(b.x == x && b.y == y)
          return true;
    }
    return false;
}

```

However, I'd suggest you place your blocks into a 2D array (or a 1D array with the index specified by the x,y). If you have your blocks in a 2D array you can easily check `blocks[x][y].solid` or something similar, instead of looping through all your blocks.

Alternatively you can use the rectangles in your scene for collision detection, where your `isSolid(x,y)` function would do a collision check at that position.
> 0 votes

---
Tags: java
---


title: Platformer raycast collision detection

text:
# Question
Title: Platformer raycast collision detection
I'm using Unity to create a 2D platformer. For collision detection, I'm using raycasting to detect any possible collisions with specific collision layers, and adjusting the desired delta x & y values as appropriate.

Here is my collision detection class.

```
public class RaycastCollisionDetection : IEntityCollisionDetection {
    private BoxCollider _collider;
    private Rect _collisionRect;
    private LayerMask _collisionMask;
    private LayerMask _playerMask;
    private GameObject _entityGo;

    public bool OnGround { get; set; }
    public bool SideCollision { get; set; }
    public bool PlayerCollision { get; set; }

    public void Init(GameObject entityGo) {
        _collisionMask = LayerMask.NameToLayer("Collisions");
        _playerMask = LayerMask.NameToLayer("Player");
        _collider = entityGo.GetComponent<BoxCollider>();
        _entityGo = entityGo;
    }

    public Vector3 Move(Vector3 moveAmount, GameObject entityGo, float skin) {
        float deltaX = moveAmount.x;
        float deltaY = moveAmount.y;
        Vector3 entityPosition = entityGo.transform.position;
        // Resolve any possible collisions below and above the entity.
        deltaY = YAxisCollisions(deltaY, Mathf.Sign(deltaX), entityPosition, skin);
        // Resolve any possible collisions left and right of the entity.
        // Check if our deltaX value is 0 to avoid unnecessary collision detection.
        if (deltaX != 0) {
            deltaX = XAxisCollisions(deltaX, entityPosition);
        }
        Vector3 finalTransform = new Vector2(deltaX, deltaY);
        return finalTransform;
    }

    private float XAxisCollisions(float deltaX, Vector3 entityPosition) {
        SideCollision = false;
        PlayerCollision = false;
        // It's VERY important that the entity's collider doesn't change
        // shape during the game. This will cause irregular raycast hits
        // and most likely cause things to go through layers.
        // Ensure sprites use a fixed collider size for all frames.
        _collisionRect = GetNewCollisionRect();
        // Increase this value if you want the rays to start and end
        // outside of the entity's collider bounds.
        float margin = 0.0f;
        int numOfRays = 4;
        Vector3 rayStartPoint = new Vector3(_collisionRect.center.x,
            _collisionRect.yMin + margin, entityPosition.z);
        Vector3 rayEndPoint = new Vector3(_collisionRect.center.x,
            _collisionRect.yMax - margin, entityPosition.z);
        float distance = (_collisionRect.width / 2) + Mathf.Abs(deltaX);

        for (int i = 0; i < numOfRays; ++i) {
            float lerpAmount = (float) i / ((float) numOfRays - 1);
            Vector3 origin = Vector3.Lerp(rayStartPoint, rayEndPoint, lerpAmount);
            Ray ray = new Ray(origin, new Vector2(Mathf.Sign(deltaX), 0));
            //Debug.DrawRay(ray.origin, ray.direction, Color.white);
            RaycastHit hit;
            // Bit shift the layers to tell Unity to NOT ignore them.
            if (Physics.Raycast(ray, out hit, distance, 1 << _collisionMask) ||
                Physics.Raycast(ray, out hit, distance, 1 << _playerMask)) {
                if (hit.transform.gameObject.layer == _playerMask) {
                    PlayerCollision = true;
                }
                //Debug.DrawRay(ray.origin, ray.direction, Color.yellow);
                deltaX = 0;
                SideCollision = true;
                break;
            }
        }

        return deltaX;
    }

    private float YAxisCollisions(float deltaY, float dirX, Vector3 entityPosition, float skin) {
        OnGround = false;
        // It's VERY important that the entity's collider doesn't change
        // shape during the game. This will cause irregular raycast hits
        // and most likely cause things to go through layers.
        // Ensure sprites use a fixed collider size for all frames.
        _collisionRect = GetNewCollisionRect();
        // Increase this value if you want the rays to start and end
        // outside of the entity's collider bounds.
        float margin = 0.0f;
        int numOfRays = 4;
        Vector3 rayStartPoint = new Vector3(_collisionRect.xMin + margin,
            _collisionRect.center.y, entityPosition.z);
        Vector3 rayEndPoint = new Vector3(_collisionRect.xMax - margin,
            _collisionRect.center.y, entityPosition.z);
        float distance = (_collisionRect.height / 2) + Mathf.Abs(deltaY);

        for (int i = 0; i < numOfRays; ++i) {
            float lerpAmount = (float) i / ((float) numOfRays - 1);
            // If we are facing left, start the rays on the left side,
            // else start the ray rays on the right side.
            // This will help ensure precise castings on the corners.
            Vector3 origin = dirX == -1
                ? Vector3.Lerp(rayStartPoint, rayEndPoint, lerpAmount)
                : Vector3.Lerp(rayEndPoint, rayStartPoint, lerpAmount);
            Ray ray = new Ray(origin, new Vector2(0, Mathf.Sign(deltaY)));
            //Debug.DrawRay(ray.origin, ray.direction, Color.white);
            RaycastHit hit;
            // Bit shift the layers to tell Unity to NOT ignore them.
            if (Physics.Raycast(ray, out hit, distance, 1 << _collisionMask) ||
                Physics.Raycast(ray, out hit, distance, 1 << _playerMask)) {
                Debug.DrawRay(ray.origin, ray.direction, Color.yellow);
                OnGround = true;
                deltaY = 0;
                break;
            }
        }

        return deltaY;
    }

    private Rect GetNewCollisionRect() {
        return new Rect(
            _collider.bounds.min.x,
            _collider.bounds.min.y,
            _collider.bounds.size.x,
            _collider.bounds.size.y);
    }
}

```

This works very well except for the y-axis collisions in `YAxisCollisions`. The origin of my ray is the center of my sprite. The direction of the ray is the direction the player is moving (up or down). The distance of the ray is half the height of the collision rectangle + the desired movement speed along the y-axis. As a result, collision is detected slightly above the actual collision layer.

Here's a video clip showing the behavior. YouTube: Overtime Y-Axis Collision Detection Bug

As you can see, collision is detected as the player is moving downward. The sprite stops its y movement a bit earlier then I would like (which makes sense since the distance of the ray is the desired movement amount of the player, not it's actual current position).

What I would like is for the collision to be detected at a much closer distance between the sprite and collision layer, but everything I've tried introduces other bugs; mainly the player can easily fall through the collision layers under the right circumstances. I'm sort of at wit's end on how to get the y-axis collision detection more precise.

Before you ask, yes, this is all being called in `FixedUpdate` :)

# Answer
It looks like this is caused by the `deltaY = 0;` inside `YAxisCollisions`. This stops the sprite from moving downward at all, rather than allowing it to move exactly to the impact point.

To stop the sprite at the collision point, you'll need to respond to the information contained in the raycast hit point `hit`. This will contain the distance from the ray's origin to the point of impact. There are a couple of ways to do the math, but basically the Y value of the hit is

```
_collisionRect.center.y + hit.distance * ray.direction.y

```

You want move the sprite to place either the bottom or top edge at that value, so `deltaY` needs to be the difference between that hit y value and the current edge y:

```
deltaY = _collisionRect.center.y + hit.distance * ray.direction.y - _collisionRect.yMin;

```

or

```
deltaY = _collisionRect.center.y + hit.distance * ray.direction.y - _collisionRect.yMax;

```

Tracing the variables back to their sources will show that you can factor out the actual position of the collision rectangle and get this:

```
deltaY = (hit.distance - collisionRect.height / 2) * ray.direction.y;

```

You may want to do the same thing for the X, depending how you want the character to behave when colliding with walls.

(Caveats: Code not tested, I don't necessarily know what I'm talking about, etc.)
> 1 votes

---
Tags: 2d, collision-detection, unity, platformer, raycasting
---


# Question
Title: I need an enemy spawning algorithm for a 2D tower defense
I need an enemies spawning algorithm for a 2D tower defense game. I have 4 maps, each has 4 stages and each stage has 40 rounds. I need to create an algorithm which will instantiate waves, increase health and change their type in new rounds, new stages and in new maps. I need your suggestions and ideas to resolve my problem.

It should be done like in geoDefense and Fieldrunners.

Lets take an example which is somewhat in my mind:

MAP1- Stage-1, on Rounds 1,2,3,4 loop around with '+5' on it so also in Rounds 6,7,8,9 ...so on... instantiate 'Type-1 swarm' after increment(+5) add 'Type-1 swarm + some value' so that if previous 'Type-1 swarm' (on rounds 1,2,3,4) has 3 enemies, after above increment(+5) 'Type-1 swarm' has 3+some value. The rounds multiple of 5 will instantiate 'Type-2 swarm + some value', and as round increases health value should also increase.

On Map-1 Stage2/ and other Maps and stages repeat the above process with some slight difficulty and change type swarm1 and swarn2 with other swarn types.

I hope you people got what I actually need. I don't want to hardcode the rounds because there is also an endless option in my game and hard level would have 100 rounds instead of 40.

Any other spawning ideas/algorithms followed by TD game programmers/designers.

# Answer
> 2 votes
If you want infinite rounds define 2 functions for each enemy type, one will determine health of the enemy spawned, given the round number, the other will determine the number of enemies spawned, given the round number.

Functions that would be interesting (given your example) are things like `Health = Math.Ceiling(round / 5) * 5` This would mean every 5 rounds the health increases by 5 more.

For simple enemies the number to spawn might just be `round * 2`, so each round would have 2 more monsters than the last.

Maybe harder enemies might have `round % 5 == 0 ? 1 : 0`, so you get a hard enemy every 5 rounds (where `%` gets the remainder).

You could add extra functions defining things like enemy speed etc.

# Answer
> 1 votes
I used to made a project like this time ago with a team at the college, but in our case we just had 1 stage, what we did was calculating how many enemies will be created plus an auto-growing factor to make it massive and by the higher number only change the type of enemy and the count of then but (we never did but it can be done) never changed theirs stats, just made sure that you should build the most. It were a end-less TD.

The enemiesPerWave formula were taken from PvZMultiplayer formula, where the pwaveDifficulty was originally the number of players on it. (usefully hint to consider how it truly affect)

```

int Wave::enemiesPerWave()
{
    int rsp = (int)((0.15 * this->pWaveNumber) * (24 + 6 * (this->pWaveDifficulty-1)));
    return rsp;
}

```

```

void Wave::raiseDifficulty()
{
    if(this->pWaveNumber/this->pDifficultyFactor == 1)
    {
        if(this->pWaveDifficulty pDifficultyFactor*=2;
        }
        this->pWaveDifficulty++;
    }
}

```

Generate a enemy, type and storage it

```

void Wave::generateEnemies(int enemiesCount)
{
    for (int i = 0; i generateEnemyType();
        Enemy* enemy = Enemy::create(type);
        this->pEnemies.push_back(enemy);
    }
}

```

This could be optimized by using a Json with load N number of option, but may replace this whole function to make less hardcoded

```

eType Wave::generateEnemyType()
{
    int actualRange = (rand() % this->pWaveDifficulty);
    eType enemyType;
    if (actualRange == 0)
        enemyType = BLUE;
    else if (actualRange == 1)
        enemyType = GREEN;
    else if (actualRange == 2)
        enemyType = YELLOW;
    else if (actualRange == 3)
        enemyType = RED;
    else if (actualRange == 4)
        enemyType = BLACK;
    return enemyType;
}

```

If you want to upgrade the enemies, in the enemy class they shall had a method upgrade or level up that change their stats instead of doing that in the spawning (or Wave for my use) class.

Hope this may be useful!

---
Tags: game-design, architecture, level-design, tower-defense, levels
---


# Question
Title: Modify random distribution functions :: Make it less likely to get multiple similar values in a sequence
I want to generate a sequence of numbers for procedurally generating planets in a galaxy sector. Each planet should be placed randomly, however it should be very unlikely that two planets are directly next to each other. How can I achieve that?

I know that you can modify the chances by applying a distribution function, but how can I control them in order to make specific values more/less likely?

# Answer
> 8 votes
If you do know the distribution you want, you can use *rejection sampling*.

Simplest way: In the graph above, pick points at random until you find one is below the curve. Then just use the `x`-coordinate.

For the actual distribution, there are various plausible approaches. For example, for planet number `i` at location `p`, and some strength parameter `k` (e.g. `0.5`), define a function `f_i(x)=abs(p-x)^k`, then use distribution function `g(x)=f_1(x)*f_2(x)*...*f_n(x)`.

In practice, compute and store results of `g(x)` to array `t` (`t[x]=g(x)`); remember the highest seen value `h` also. Pick a random position `x` in `t`, pick random value `y` between `0` and `h`, repeat `if y>t[x]`; otherwise the return value is `x`.

# Answer
> 1 votes
I am not sure the problem is fully specified by the question, but I can provide some simple ideas, the second of these will provide numbers roughly in accordance with what your picture indicates you want.

Either way as you may realize the distribution function is changing after each number generated, and has a memory (ie: it is non-Markovian) and either of these method may prove impractical when the 'memory' (number of previously drawn numbers) gets very large.

1. Simple:
Generate random number form a flat distribution, compare with previously drawn nnumbers, repeat if 'too close'
2. This answer is more like your figure (assuming we want to draw from 0..1):

* create a new ordered list, insert 0 and 1
    * generate random number from a flat distribution function: N\_0
        + add this number to the list
    * on next call, draw a another number N\_1,
    * if N\_1\> N\_0
        + draw a new Gaussian Random number with mean=1 and a standard deviation o of whatever you want, a smaller number (compared with 1-N\_1) will keep the random numbers further spaced apart. This will not guarantee a minimum distance between draws, but then again your figure doesn't seem to either.
    * opposite case of N\_1 \< N\_0 handled similarly
    * on subsequent draws keep generating a random number (N\_i) from a flat distribution
    * traverse your list to see which two previously drawn numbers the new number lies between (N\_-, N\_+)
    * create a new Gaussian random number with mean (N\_- + N\_+)/2
    * add the flat distribution number (N\_i) to your (ordered list) list

endpoint bins are a special case, but it should be simple enough for you to see how to handle them.

# Answer
> 0 votes
Think of the difference between 1 dice and 3 dice. 1 Dice gives you an even probability for all values, while 3 dice will tend to have a higher probability for the values towards the middle.

The more "dice" in your equation, the stronger your chance to get something towards the centre. So let's define a function that can handle any number evenly:

```
// Takes a random number between floor and ceil
// pow defines how strongly these results should gravitate towards the middle
// We also define a function TrueRand(floor, ceil) elsewhere where you should substitute your own random function
int CenterRandom(int floor, int ceil, int pow = 3)
{
    if(ceil == floor)
        return ceil; // don't care to compare

    int total = 0;
    for(int x = 0; x < pow; x++)
    {
       total += TrueRand(floor, ceil);
    }
    return total / pow;
}

```

Now we can define an example function to use this:

```
// Distribues a number of points between floor and ceil
// We assume a function PlotPoint(int) exists to aid in creating the planet, etc...
void DistributePoints(int floor, int ceil, int numPoints)
{
    // Could easily output this in the function parameters, but language wasn't specified
    int[numPoints] breaks;
    int numBreaks = 0;

    // Special case for first pair
    breaks[0] = CenterRandom(floor, ceil);
    numBreaks++;

    for(int x = 0; x < numPoints - 1; x++)
    {
        // Generate a random number linearly, this will be used for picking
        // This way we have a greater chance of choosing a random value between larger pairs
        int picker = TrueRandom(floor, ceil);

        // Now we first find the pair of points that our picker exists on
        // For simplicity, we handle the first and last pair separately

        if(picker >= floor && picker < breaks[0])
        {
            breaks[x] = CenterRandom(floor, breaks[0] - 1);
        }
        for(int i = 0; i < numBreaks; i++)
        {
            if(picker > breaks[i] && picker < breaks[i+1])
            {
                breaks[x] = CenterRandom(breaks[i] + 1, breaks[i+1] - 1);
            }
        }
        if(picker > breaks[numBreaks] && picker <= ceil)
        {
            breaks[x] = CenterRandom(breaks[numBreaks] + 1, ceil);
        }

        PlotPoint(breaks[x]); // Plot the point
    }
}

```

Now the first to note is that this code really doesn't check if picker matches one of the points already. If it does then it's just not going to generate a point, possibly something you'd might like.

To explain what's going on here is that CenterRandom generates a bell curve of sorts. This function breaks up the plane into multiple bell curves, one per pair of points existing. The picker tells us which bell curve to generate from. Since we pick linearly, we can ensure that pairs with larger gaps between them will be chosen more often, but we still leave it completely random.

Hope this points you in the right direction.

# Answer
> 0 votes
I know you're asking about a *sequence* of random positions, but if you aren't restricted to generating the set sequentially, there's another approach: generate a *set* of points that has the desired spacing.

What I think you want is a set of planets that are reasonably spaced with some randomness. Instead of generating planet *positions* with a random number generator, generate planet *spacing* with a random number generator. This will let you directly control the distribution of spacing, by using a random number generator that picks from that distribution. This is straightforward in 1 dimension.

In 2 dimensions, I've seen some approaches that generate “blue noise” but I don't know a way to generate spacing with an arbitrary distribution. This article covers the standard “try placing it and reject if it's too close” approach, but you can generate them all at once, with a “softer” solution by placing all your points, then using Lloyd Relaxation to move all the planets to more desirable positions. It'll move the too-close planets farther apart. Recursive Wang Tiles are another approach that could be useful. This paper extends the problem to generating planets with one density and some other object like asteroids with another density. You might also be able to generate blue noise by using Fourier series; I'm not sure. The Fourier series approach would also let you use arbitrary distributions instead of only blue noise.

---
Tags: mathematics, procedural-generation, random
---


# Question
Title: Calculating impulse with multiple collision points
In my amateur 2D rigid body physics engine for a game I react on collisions between two bodies with an impulse **j** (formula 11) as explained here.

To calculate this impulse I need one contact point **P** between the two colliding bodies and the perpendicular normal **n** of the edge the contact point of A is colliding with.

<sub>(source: myphysicslab.com)</sub>

That works wonderful. At least as far as I don't have multiple contact points. But what to do if this is not the case?

**Should I calculate an impulse for each of the contact points or is there a way to reduce multiple contact points to a single one if this is a correct solution?**

As an example I have following two situations, where two bodies collide. The x denotes the center of mass and the tips of each triangle pointing down an vertice of A that is colliding with the edge underneath:

```
    _____________________                        _____________________
   |                     |                      |                     |
A  |          x          |                   A  |                     |
   |    _____________    |                      |         x  ______   |
    \  /             \  /                       |           /      \  /
     \/               \/                        |    __    /        \/
    _____________________                        \  /  \  / ___________
   |                     |                        \/    \/ /           |
B  |          x          |                   B   _________/    x       |
   |_____________________|                      |______________________|

```

In the *left situation* its intuitively pretty clear that I can reduce the two collision points to one exactly in the middle between both since the this would be collinear to both centers of mass. Also as normal n the perpendicular vector of the edge both vertices are colliding with can be chosen.

**But what to do in the *right* situation?**

# Answer
> 7 votes
Your solver needs multiple iterations (aka sequential impulse) over its contacts.

Treat each contact point independently and calculate the impulse to resolve its contact constraint for that iteration. This may cause previously resolved contact points to be pushed back into the colliding object, but not by as much as the initial penetration.

Perform multiple iterations over the contacts. Each iteration will get you closer to the correct result. The number of iterations you use is something you need to tweak based on your needs and performance envelope and how numerically stable your solver is.

Here is an article by Allen Chou on sequential impulse solvers. You should read his whole series on game physics.

---
Tags: collision-detection, physics, collision-resolution, physics-engine, rigid-body-dynamics
---


# Question
Title: Calculating How To Intercept a Moving Object
So I have two objects, Target and Interceptor. Target's position, direction of movement and movement speed are known, and Interceptor's position and movement speed are also known. Both movement speeds are fixed, and Target will never change course. Both are moving in three dimensions; Interceptor can move in any direction.

I want to figure out which direction Interceptor needs to move in, at its fixed movement speed, to be able to collide with Target as Target moves, as quickly as possible - or, as the case may be, I want to know if it is impossible for Interceptor to collide with Target.

I don't know how to do this, and my Google searches clearly haven't been using the right search terms, because nothing useful comes up. How do I calculate this?

# Answer
If the targets velocity is `V` and the interceptors desired speed is `S`:

1. Calculate the normalized vector `U` between the interceptors current position and the targets current position `Tp - Ip`.
2. Find `a` such that the length of `Vi + aU` equals `S`. `aU` is the desired speed.
3. It will take `distance / (Vi + aU).length` time to intercept.
4. If you get a negative value for `a` then they will never intercept.
> 3 votes

---
Tags: collision-detection, mathematics, movement
---


# Question
Title: Working with multiple language text files in multilingual games
What kind of tools and practices are used for maintaining text for multilingual games? By "text" I mean literally any piece of text you see in the game: dialog, menu options, tutorials, etc.

I want to keep it as modular as possible and make it very easy to add new language options by simply providing a new set of files.

Are there publicly available tools that I can use to maintain these text files and, preferably, pass it to others that can perform the translation process and allow them to put together all of the input data without me having to hardcode anything into the game?

# Answer
As always, there are lots of ways to achieve what you want. However, unlike other applications, games have very specific requirements, so what works best for other programs may not be best for a specific game.

Remember that localization is a very complicated matter. It's not just about translating words and meanings. There are lots of subtle meanings in whatever texts you have, cultural issues to remember, and even technical matters such as textbox size (a text may fit on the screen when written in English, but can overflow when written in Finnish).

Most European languages (English being a notable exception) use diacritics, accent marks and glyphs unique to them. Other languages use other scripts (like Greek or Russian). Others use different writing systems (Arabic and Hebrew read from right to left, and Japanese can be written from top to bottom). Do you have all the fonts required to support all those languages? Specifically logo like texts are very susceptible to text length problems, so be careful, and optimally plan for localization from the beginning.

Because of this, in my opinion, simple is best. I prefer to use the simplest solution that works for my interests. Here are some ways to localize a game.

### Hardcoding

If your game has very few (less than 100) strings, and you're not considering on updating it, or if you just have very few languages, it is very possible to just say

```
if language is french then
  display("bonjour")
else
  display("hello")
end

```

Doing stuff like this just works, and if it works for you, you probably don't need anything fancier. Also, you can do more sophisticated things, like reducing or increasing the amount of texts depending on the language. If possible, try to consider localizing like this.

### Parameter hardcoding

This is pretty much the same, but I've seen it more in the scripts a game uses, instead of the main program. The idea is that every function you make that can be localized, you take each possible language as an argument, like so:

```
function print(text_en, text_fr)
  if language is french then
    display(text_fr)
  else
    display(text_en)
  end
end

```

and then

```
print("hello", "bonjour")

```

This is very common in the scripts a game uses, and the best thing about it is that it maintains the context of each string, which allows for higher quality translations than just isolated strings, and if possible should be considered.

### Automatic replacement

Especially when making translations after an initial game has been shipped, it is possible to add a very thin translation layer in every text related function, that takes the original text, looks it up in a translation table, and replaces it if a match is found.

```
function translate(text)
  if language is french then
    if text == "hello" then
      return "bonjour" -- replace with a hashtable for faster lookups
    end
  else
    return text
  end
end

function print(text)
  text = translate(text)
  display(text)
end

```

This allows you to add translations to an already finished game with minimal impact on the original already functioning code. I rarely see it used before a game is finished, because if the original text changes, you also need to change the lookup key. But it works, and if you have good lookup tables, it can be quite fast.

### String resources

This is very common in application development. The idea is that you have a resource file which defines a bunch of constants like:

```
...
strings["en"][1044] = "hello"
strings["fr"][1044] = "bonjour"
...

```

and whenever you want to print the localized text, you go like

```
function print(id)
  if language is french then
    display(strings["fr"][id])
  else
    display(strings["en"][id])
  end
end

```

There are thousands of variations of this. You can have a file for each language, a file for each module; you can store them in source files, xml files, json files, csv files, binary files; you can import them from excel, word, a proprietary tool, etc.

The obvious advantage of this is that programmers love it. Keeping program and data separate is the dream of every programmer, and it pretty much works. However, keep in mind that as the amount of strings increases, the amount of ID vastly increases, and a string ID has no semantic information attached to it, so it is very easy to make mistakes.

Also, it is very common for developers to try to avoid string duplication by encoding common strings like "yes" and "no" only once. However, in some languages, the words used for those common words are different depending on the context. For example, if you're asked "don't you want coffee?", and you answer "no", in Japanese it means "yes, I want coffee" (a double negative), while in Spanish it means "no, I don't want coffee". Because of this, it is very common for developers to encode each string in a different ID, even if that means you end up with hundreds of "yes"es in your string file.

Since moving strings to a separate file and attaching meaningless IDs to them loses the context of the phrases, you may need to have a much more thorough language testing effort. Be careful with this technique.

### Language agnosticism

This is not location related, but many games give up on this, and make the game understandable with drawings and other gimmicks that don't require written words. It definitely makes interesting games, and doesn't require any kind of translations. Remember cultural differences though (some colors have different meanings on some cultures, and some hand gestures may be okay in one culture, while offensive in another)/

Just one last thing you might find useful. This is a very comprehensive list of languages (actually "cultures"), with predefined codes for each of them that you may use in your program.
> 4 votes

# Answer
I'm not sure if there is a game-specific translation framework but I've used gettext system for handling translations in WordPress. Here's the WP page describing their translation process along with a list of tools. The gist is that you create a template file that you in turn use to create translations. The final step is producing a binary, machine optimized file that is used in the actual application.

I've used Poedit (runs on Windows, Mac and Linux) to edit translations for WP and found the experience to be fairly nice.

It looks like Python supports gettext out of the box so it should be relatively simple to get gettext up and running in your game.
> 1 votes

# Answer
This is how I usually add multi-language support to my applications.

Presume u have a list of words/expressions u are using in your game, list them in file(in english). Then add the translation of the required language and make such a file for every language.

Default/English language file the only weird file because the key(left word )and translation value(right word) are an exact match.

* new game = new game
* settings = settings
* won = won
* lost = lost ...

Dutch language file

* new game = nieuw spel
* settings = instellingen
* won = gewonnen
* lost = verloren ...

When your game is starting, you just read all the language files and store them into a global defined string matrix. In this matrix the first dimension of the matrix is the language the second dimension is the string u need.

English is first dimension 0

* String\[0\]\[1\] = new game
* String\[0\]\[2\] = settings

Dutch is first dimension 1

* matrix\[1\]\[1\] = nieuw spel
* matrix\[1\]\[2\] = instellingen

Now u need to declare a global variable that keeps an integer named LANGUAGE. In your code u can now refer to this variable to get the language u need.

* matrix\[LANGUAGE\]\[1\] will give 'new game' if LANGUAGE = 0(english)
* matrix\[LANGUAGE\]\[1\] will give 'nieuw spel' if LANGUAGE = 1(dutch)

If you use this language matrix all over your code, u can simply change the language of your game by changing the LANGUAGE global variable.

If u want to add a language u simply add another file that contains all the translations for that language. Because your game will load all these language files into the language matrix, the new language will become available when u restart the game.

p.s. sorry if the layout is not that good =P
> 1 votes

# Answer
What are you coding in?

.NET has satellite assemblies which can be loaded automatically by setting the `UiCulture` on the current thread. An easy cross-language way of doing it would be XML files with a key-value pair for each element of text you need.
> 0 votes

# Answer
Could store your strings in an excel spreadsheet like so and export as .csv for easy reading\parsing. Easy to edit and update and where you currently hard code your string you look up the string using the string id instead to find the corresponding string for that language. Could load them all in memory if its a small amount of text or feasible for your app/platform. You will need to write some code to manage this but should be straight forward, if you need some more help feel free to post. Ill happily post more specifics.

StringID English French

Title\_screen English\_Foo1 French\_foo1

Java also has a nice infrastructure for handling this with property files : http://docs.oracle.com/javase/tutorial/i18n/intro/steps.html
> 0 votes

---
Tags: text, localization
---


title: read in an xml server from Unity3D 4.xx

text:
# Question
Title: read in an xml server from Unity3D 4.xx
I need examples of how to read an xml from a server, using Unity3D..

I think it's something like this.. but I can not retrieve the information from the nodes..

An example would be of great help.. thank you..

var url = "http://server.com/test2.xml";

var www : WWW = new WWW (url); yield www;

var xml : XmlDocument = new XmlDocument();

# Answer
In case you are using C#, you can use the XML classes from .NET. I tend to use the XPathNavigator, since most of the time you need only to read out data, and don't have to write data back.

Snippet from my actual code:

```
XPathDocument xmlFile;

try {
  xmlFile = new XPathDocument (filePath);
} catch (FileNotFoundException ex) {
  UnityEngine.Debug.LogException (ex);
}

// Create the navigator to navigate the file
XPathNavigator xnav = xmlFile.CreateNavigator ();

// Get the values of single nodes directly by using their XPath
string viewmode = xnav.SelectSingleNode ("/trainingSettings/viewmode").Value;
int NoItems = xnav.SelectSingleNode ("/trainingSettings/difficulty/noitems").ValueAsInt;
int NoOverallItems = xnav.SelectSingleNode ("/trainingSettings/difficulty/nooverallitems").ValueAsInt;

// Convert values using XmlConvert …
TimeSpan RemainingDurationOfTraining = XmlConvert.ToTimeSpan (xnav.SelectSingleNode ("/trainingSettings/trainingDuration").Value);

```

By using `XPathNavigator.Select()`, you can get a list of nodes back and then iterate over them, if necessary.
> 1 votes

---
Tags: unity, server, xml
---


# Question
Title: Given face normal and vertices of a triangle, how to find the acyclic order of vertices?
I'm in the process of constructing a custom 3D triangle mesh. I found the vertices of the triangle in the 3D space and it's face normal. How do I find the acyclic order of vertices?

If I draw the vertices in the wrong order, I can't see some of the faces which should be visible when back face culling is enabled.

# Answer
For a triangle with points `p0`, `p1`, and `p2`, and normal `n`, you’ll need to compare the vectors `cross(p1 - p0, p2 - p0)` and `n`. They should either point in the same direction, or in the opposite direction, for all triangles in your mesh.

Suppose your convention is that the vectors must point in the same direction.

The algorithm is simple. For each triangle, compute the following value:

```
dot(n, cross(p1 - p0, p2 - p0))

```

If the value is negative, swap `p1` and `p2`.
> 6 votes

---
Tags: opengl, 3d-meshes, normals, culling, draw-order
---


# Question
Title: 2D open world MMORPG; big map memory problem
I am developing an 2d open world mmorpg game for learning purposes, and have a issue with big maps.
A year ago i developed 2d open world single player / co-op game. It saved map in chunks, and AI for NPCs starts 'ticking' when specified map chunk is loaded.
In my mmorpg game, NPCs AI is handled by server, and its always 'ticking' in some specified interval. That is where my troubles begin. I want NPC to walk in random directions. For this to work, I have to check map collision for every step, so my NPC wouldn't end up in wall. Problem is when I have big map, for example 10000x10000, and every tile is represented with 6 bytes, that is about 572MB of map data my server must hold in memory all the time, and i cant load just few map chunks, like in my single player RPG because of lot NPCs AI needs to be updated all the time, even if player is not located near by.
My goal is to archive map size of 50000x50000 tiles. I know its possible because i seen 2d mmorpgs with huge open worlds, a lot bigger then 50000x50000, and I doubt that their server have 20GB of ram to waste just on maps.
If anyone have any ideas how I can lower memory usage, I woud like to hear you.

Thanks in advance, and sorry for my bad english

# Answer
First, while MMOs usually have a lot of players online at any one time, these players usually concentrate on key-areas. There are usually large parts of the world where no players are present most of the time. That means you can still use chunks and not keep those in memory which have no players near them.

When you have some NPCs which need to perform some activity even when there is no player nearby, you could simulate these with a simplified model. For example: a blacksmith NPC who makes swords by automatically collecting resources and bringing them to his forge, the simplified model would not do the routefinding but just use an estimation how many swords he would have made during the time no player was nearby, remove the required resources from the surrounding and give him that number of swords.

Should this still require too many resources, you need to design your server infrastructure in a way which allows it to scale over multiple servers. Make it possible to have multiple servers where each server is responsible for only a part of the game world.
> 5 votes

# Answer
I suspect these other games aren't updating all npcs at all times. I know the alure of the idea that npcs go about their lives whether there is someone there to see it or not is strong, but then you run in to exactly this problem with large worlds.
The 2 options I can think of are to either only update chunks where a player is close and will see the updates, or to 'fake' the NPC activity at a sort of 'higher level' i.e. you don't need to know that an NPC walked the route Tile 1-2-3-4-5, you just need to know that he was in Tile 1 and in 4 updates he will be in Tile 5.
> 2 votes

---
Tags: 2d, maps, mmo, scalability
---


# Question
Title: How can I prevent rigid bodies from moving through each other using Unity's built-in physics?
I'm trying to create a game where objects can be dragged, but I'm having trouble with the physics. With rigid bodies that have similar masses, they sometimes push through each other when dragged and cause unwanted movements. Here is a demo.

I'd like to do this using *only Unity 3D's built-in physics*.

In the demo, you can use the mouse to click and drag objects. The cylinders all have box colliders and masses of 10000. They also have various constraints depending on their orientation (none can rotate, and all are constrained in x or y). The sphere has a mass of 1, a sphere collider and a z constraint.

The sphere and cylinders interact well. However dragging the cylinders across one another causes intersection. I do not want this!

The cylinders have interpolate set to 'Interpolate' and collision detection set to 'Continuous'. I have thrown the 'DontGoThroughThings' script onto all the cylinders, but it doesn't seem to do anything. As for setting the velocity of the rigidbodies, I have used both of these following lines with basically the same result:

```
rb.AddForce(speed * diff * Time.deltaTime - rb.velocity, ForceMode.VelocityChange);
//rb.velocity = speed * diff * Time.deltaTime;

```

Without writing my own collision detection code, I'm out of ideas. Is there a simple setting or something I've missed?

With the context explained, here's a more precise question: "How can I get the cylinders in my demo to not move through each other?"

# Answer
> 2 votes
Without looking at your project/code I would like to suggest this:

```
private bool _mouseOverObject = false;

void Update(){
    if(_mouseOverObject && Input.GetMouseDown(0){
        rigidbody.isKinematic = false; //Let Unity Physics affect the item.
    } else {
        rigidbody.isKinematic = true; //Let it affect other physics but not be affected itself
    }
}

void OnMouseOver(){
    _mouseOverObject = true;
}

void OnMouseExit(){
    _mouseOverObject = false;
}

```

It will allow you to restrict physics but within Unity's scope and physics engine. You can jiggle around with the script to make it lock only one object to be moved etc but this should get you started.

# Answer
> 0 votes
You want the collision-detection set to `Continuous Dynamic` for fast moving objects. `Continuous` is used for static- or slow-moving objects that `Continuous Dynamic` objects collide with. See here.

*(Keep in mind that continuous collision detection is expensive, so use it sparingly)*

---
Tags: collision-detection, unity
---


title: Android : glowing/pulsing line/triangle

text:
# Question
Title: Android : glowing/pulsing line/triangle
I would like to create a simple Android app using Opengl ES 2.0 that is showing a simple shape (like line or triangle) that is glowing and pulsing like Nexus X logo in this video : http://youtu.be/jBKVAfZUFqI?t=59s

What should I look for?

So far I googled around for glowing effects and found techniques like "bloom" or "additive blending". Are they relevant here? how I would implement pulsing glow with them?

Any links to relevant works very appreciated Thanks!

P.S - I am very familiar with Android SDK; just started with OpenGL ES

# Answer
Another cheaper solution would be to fake glowing by using static semi-transparent glow textures instead of creating the glowing effect through post process shaders.

You would then need to animate their transparency (and/or size) in order to achieve a pulsing effect similar to the Nexus logo.

An advantage to this approach is that you can use your favorite image editor to control the appearance of the glow and achieve a unique artistic look.
> 2 votes

# Answer
This is how people usually do it:

Create a framebuffer 1

Render your triangle, and all glowy things to this framebuffer 1, but also things that should occlude the glowers. Make sure depth testing is on.

Create another framebuffer 2 and bind this framebuffer 2. Now take framebuffers 1 texture and do a post processing effect on it, what you probably want to do is a gaussian blur.

Bind framebuffer 0 (the one that actually draws to the screen) Draw framebuffer 1s texture as a full screen quad Turn on blending, make the blending equation additive Draw framebuffer 2s texture as a full screen quad

You can achieve the pulsing in two way, either you can make the triangle less opaque when rendering to framebuffer 1, or you can modulate the resulting fragments from the gaussian blur step with some coefficient. Of course, the level of opaqueness and the color modulation would have to depend on some period of time, eg.

```
final static long pulseTimePeriod = 3000;
private long pulseTime = 0;

public void update(long delta) {
    pulseTime += delta;
    while (pulseTime > pulseTimePeriod )
        pulseTime -= pulseTimePeriod;

    float ratio = pulseTime / Float.valueOf(pulseTimePeriod);
    float val   = Math.cos(ratio * 3.14 * 2)*0.5+0.5;
    float coefficient = Math.pow(val, 2.0); //power makes it more pulsey
}

```

These two methods would look different from each other.
> 1 votes

# Answer
I have started with OpenGL ES 2.0. a few weeks ago. It really was hard!

If you just want to finish the work I would suggest to visit Android dev's web page on OpenGL and use the sample to draw the triangle.

Then for the effects I would look for a shader which implements them(Google it). I've done a search and looks like a pretty complicated thing, but maybe there's a easy way to work it out. Anyhow, when you get the shader just change it for the one the sample is using(You'll have to understand the basics of shaders).

That would be the quick way out. If you really want to understand what's going on use "Opengl Es 2 for Android: A Quick-Start Guide". It really explains everything clearly and step by step, it is the best I've found so far.
> -3 votes

---
Tags: opengl, android, opengl-es2, glow
---


# Question
Title: GLSL associating multiple uniform samplerBuffers
At the moment I'm not sure how my VBO and TBO associate with a specific uniform samplerBuffer in my shader, I have not linked them using the location or the vbo/tbo together. It seems to still work though, but now that I am using multiple samplerBuffers, how do I establish to link between a specific TBO and the uniform. Do I need to use glUniformX?

# Answer
For VBOs you don't use uniforms, but to deference them you use shader attributes instead.

Regarding Texture buffer objects (TBO) you can bind their uniform location in the shader,

```
layout (binding = 0) uniform sampler2D tex_object;

```

You can also get its location using glGetUniformLocation and then set the TBO uniform value using `glUniformi( location, tbo)`.

Inorder to tie VBO and TBO together use `glTexBuffer`

```
// Attach the VBO to TBO.
glGenTextures(1, &tbo);
glBindTexture(GL_TEXTURE_BUFFER, tbo);
glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, vbo);

```
> 1 votes

---
Tags: opengl, glsl
---


title: Ads in mobile game

text:
# Question
Title: Ads in mobile game
I have a game with a menu screen, game screen, game over screen. Do you recommend to use ads in all of them? Is it good for user experience?

# Answer
> 1 votes
**The short answer:** All ads shown are bad for the user experience. Why would they be good? In a shopping app, they might be useful, but not in a game.

**The long answer:** It really depends on what kind of ads you're showing and how reasonable they are.

For example, I'd never ever show any ad banner during a normal game screen, if your game involves fast reactions or constantly looking at the screen (like a jump and run or timed puzzle game). If you're doing some kind of simulation that is turn based, this is far less of an issue.

Ads in the menu screen are something different. If they don't distract from the actual game, then I'd consider them okay. The same goes for the game over screen. Just avoid the user doing any accidental tap on an ad banner, as this not only creates a bad user experience ("that $§/%)! got me into clicking a banner I didn't want to click!") as well as possible license/coc violations.

So for a game, use as many ads as possible, but at the same time keep them at a reasonable amount. For example, when I tried "Draw something!", I really enjoyed the game, but finally stopped playing after it started an ad screen in each and every screen transition.

Also try to avoid animated (or even video) ads. Those might get you more money, but at the same time they might keep people from playing your game while outside WiFi range (or simply force them to remove the game).

---
Tags: game-design, marketing
---


# Question
Title: How to model interentity membership in entity-component architecture?
I'm falling in love with simple grace of entity-component design, although I still have issues breaking from MVC and OOP practices. Some of my game entities have membership relationships with each other (ex: a player is a member of a city, a city is a member of a nation), and I am unsure on the best way to implement it.

My initial reaction is to have a a MemberOfCity component that points to the appropriate city component, but components are suppose to have no references to each other. My other option is to have a System do it, but that would require the system to persist data outside of a component.

Is there a clean way to do this in an entity-component design, or am I trying to use a hammer on a screw and should use a hybrid/another approach?

# Answer
> 3 votes
My interpretation of this comment by Adam Martin, discussing how to model an airplane in an entity system --

> Since an entity is formally just “a name”, a component can refer to other entities easily.
>
> Personally, I’d be tempted to have a separate “plane” entity that had a “PlaneParts” component that was just a list of the names of the other entities on the plane.

-- is that components should never reference other components, but components can reference entities.

So I see two ways to do this:

1. The player entity (**not** the player *component*) has a 'citizenOf' component, which has a reference to the city entity (not the city component).
2. The city entity (not the city component) has a 'citizens' component, which (cf. the first part of Boreal's answer) contains a list of player entities (not player components)

Which way you want to model it probably depends on which way is going to make it more efficient to access the data.

Note that in neither case (contra the second part of Boreal's answer) does any component know about any other component, nor does any component care what other components the related entities have.

This, IMO, is the major advantage of an entity system for designers -- if you decide on the fly that potatoes can be citizens, or potatoes can *have* citizens, there's nothing in the entity-component system to stop you from doing that.

(And yes, you're probably not going to do make potatoes citizens, but you might make NPCs citizens; and yes, you're probably not going to make a player a citizen of a potato, but you might make a player a citizen of a village, or a guild, or a city-less nomadic tribe.)

# Answer
> 1 votes
I'd do it the other way around: the city has a Population component that is a list of Person entities. Components should generally be linked if they are linked in definition.

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


title: Problem with .hdr/.pic format

text:
# Question
Title: Problem with .hdr/.pic format
So, everything was clear from the specification point of view, but when I moved to reading through some of the original implementations and reimplementations, I ran into this:

```
f = ldexp(1.0,rgbe[3]-(int)(128+8));

```

This piece calculates the signed exponent (\<128 are, by specification, defined to be negative) and applies it to 2.0f. Why does he add 8 after the fact? And why doesn't he just write 136? That's biasing the encoded exponent information in favor of the smaller values, right? But why? All the values I load with this seem to be in a really cramped floating point space \[I'm not even sure anything uses the space above 1.0f\]. I understand the ratios remain consistent, but I kind of prefer to rely on original measured radiances.

http://www.graphics.cornell.edu/~bjw/rgbe.html — The code here states that is the standard way to decode "real pixels", which has no basis in the specification and no rationale offered.

# Answer
`ldexp` is a function which takes two arguments, the significand and the exponent. And it multiplies the significand by 2 taken to the power of exp. If we take the significand to be 1.0 (as in your case), it reduces down to 2^x, essentially.

RGBE format encodes the exponent in such a way that values less than 128 are considered negative, easily expressed as `e-128`. When you decode the exponent, you need to restore the significand to its \[0,1) range (the largest primary will be normalized to \[0.5, 1.0) while others... Well.). To do that, you'd have to divide each of the channels by 256 (the number of values represented by a byte). And then multiply by 2^exp to get the final value.

Notice that 256 is 2^8. Also notice that in your example that the author seemingly doesn't do the 256 divide at all. Why is that? He shoved the divide into the ldexp. How?

```
f = ldexp(1.0,rgbe[3]-(int)(128+8));

```

`rgbe[3]` is the **encoded exp**.

So, let's express the exponent in a different way:

encodedExp - 128 - 8 *(remember that exp = encodedExp - 128)*

exp - 8

Now, apply the exponent to the base 2:

2^(exp - 8) = 2^exp * 2^-8 = 2^exp / 2^8 = **2^exp / 256**

There it is! **So, the author premultiplied the 2^exp calculation with 1/256.**
> 3 votes

---
Tags: c++, c, hdr
---


# Question
Title: Getting the position of a directional light w.r.t. a moving object.
I have a forward vector of my object, which is a bike, and its position, and I have a directional light direction.

I would like to know where the light is with regards to the bike position/orientation, whether is it in front, on the right-hand side or on the left-hand side. The light will not move but the bike will.

Here is the code I have so far but it's not working as I expect:

```
Vector3 lightDirection = mDirectionaLightTransform.transform.position - Source.transform.position;
Vector3 normalizedLightDir = lightDirection.normalized;
Vector3 reflectedForward = Vector3.Reflect(normalizedLightDir, Vector3.forward);

float blobShadowAngle = Vector3.Dot(normalizedLightDir, reflectedForward);

```

# Answer
> 0 votes
Please note that I don't have unity, but my example is in c# so you'll be able to follow along.

First, since your question concerns a bike (assuming it'll always be on the ground), I've taken the liberty to 'flatten' the question and use only the x and y attributes of the used directions as in this context the z is irrelevant.

The way I'd do it:

1. Compute the angle between the bike and a reference vector, in this case (1.0, 0.0) because we'll use atan2 and things get computed w.r.t that vector in atan2.
2. Rotate the light source vector (invert the light direction to get the source) by the angle computed in 1.
3. Compute the angle of the rotated source vector. This way you get the angle of the source w.r.t. the front of the bike.
4. With the last angle computed, determine where the light is w.r.t. the bike.

Now what is considered "in front" or "on the right side" is quite vague, so you'll have to set angle ranges.

Here is a code sample that illustrate the process.

```
struct Vec2
{
  public Vec2(double aX = 0.0, double aY = 0.0) { x = aX; y = aY; }
  public double x;
  public double y;
}
static double radToDeg(double aRad) { return aRad / System.Math.PI * 180.0; }
static void Main(string[] args)
{
  double angle;

  angle = getAngle(new Vec2(1.0, 0.0), new Vec2(-1.0, 0.0));
  System.Console.WriteLine(String.Format("Front? {0} {1}", angle, getDirection(angle)));
  angle = getAngle(new Vec2(1.0, 0.0), new Vec2(1.0, 0.0));
  System.Console.WriteLine(String.Format("rear? {0} {1}", angle, getDirection(angle)));
  angle = getAngle(new Vec2(1.0, 0.0), new Vec2( 0.0,  1.0));
  System.Console.WriteLine(String.Format("right? {0} {1}", angle, getDirection(angle)));
  angle = getAngle(new Vec2(1.0, 0.0), new Vec2( 0.0, -1.0));
  System.Console.WriteLine(String.Format("left? {0} {1}", angle, getDirection(angle)));

  angle = getAngle(new Vec2(0.0, 1.0), new Vec2(0.0, -1.0));
  System.Console.WriteLine(String.Format("Front? {0} {1}", angle, getDirection(angle)));
  angle = getAngle(new Vec2(0.0, 1.0), new Vec2(0.0, 1.0));
  System.Console.WriteLine(String.Format("rear? {0} {1}", angle, getDirection(angle)));
  angle = getAngle(new Vec2(0.0, 1.0), new Vec2(-1.0, 0.0));
  System.Console.WriteLine(String.Format("right? {0} {1}", angle, getDirection(angle)));
  angle = getAngle(new Vec2(0.0, 1.0), new Vec2(1.0, 0.0));
  System.Console.WriteLine(String.Format("left? {0} {1}", angle, getDirection(angle)));

}

static double getAngle(Vec2 aBikeForward, Vec2 aLight)
{
  // invert the light because we want to have a source vector
  Vec2 invertedLightVec = new Vec2(-aLight.x, -aLight.y);

  // have both vector in the frame of the bike where it's front is pointing at (1, 0)

  // get the angle of the bike with our reference (1,0); invert the angle
  // because we'll use it to transform the inverted light vector.
  double angleBike = -System.Math.Atan2(aBikeForward.y, aBikeForward.x);

  // rotate the light by this angle
  Vec2 rotatedLight = new Vec2(
    invertedLightVec.x * System.Math.Cos(angleBike) - invertedLightVec.y * System.Math.Sin(angleBike)
  , invertedLightVec.x * System.Math.Sin(angleBike) + invertedLightVec.y * System.Math.Cos(angleBike) );

  // compute the angle of the rotated vector
  return System.Math.Atan2(rotatedLight.y, rotatedLight.x);
}

static String getDirection(double aAngle)
{
  if (radToDeg(aAngle) > -45.0 && radToDeg(aAngle) < 45.0)
  {
    return "front";
  }
  if (radToDeg(aAngle) > -135.0 && radToDeg(aAngle) < -45.0)
  {
    return "right";
  }
  if (radToDeg(aAngle) > 45.0 && radToDeg(aAngle) < 135.0)
  {
    return "left";
  }
  return "other";
}

```

I think there are other ways to achieve this, but I can't think of one right now, but this method will get you started.

---
Tags: 3d, unity, mathematics, vector
---


# Question
Title: Does GLSL copy function arguments by value?
My question is about passing variables to GLSL shader. I'm not sure how that works and what are the performance implications.

Say I got a function that accepts a "vec4" variable. The question is - is that variable copied at the entrance? I guess it makes impact on performance if so. And if it happens to be that way is there a way to pass only references like in C/C++?

# Answer
GLSL always uses copying, but this doesn't have the same performance implications as C++. In particular, because there is no recursion, there isn't a stack, and typically either functions are inlined and optimized there by the GLSL compiler, or parameters are in fixed register locations and copying is unnecessary.

Note that passing by const& in C++ is completely different from "passing by reference." In passing by reference, the function is allowed to change the argument, and these changes are visible to the calling function. "`inout`" achieves a similar result, but is not quite the same as vec4& in C++ if you pass the same variable to different parameters of a function.

`vec4` is a primitive type in GLSL, you can expect it to behave like a `int` or `float` for performance. Finally, vec4 is only 128 bits, which is one or two cycles to copy.
> 11 votes

# Answer
You can mark the variable in the signature as "input". This will work as a reference pass (at least I'm the way you have asked).
> 0 votes

---
Tags: shaders, glsl
---


# Question
Title: Rotating a camera 90 degrees around an object in Unity3D
I've attached this script to the camera and am using it to rotate the camera around an object. It's currently rotating freely but I'd like it rotate 90 degrees smoothly, over 60 frames, when the button is pressed. So that four presses of the left arrow key would have the have the camera rotate the full 360 degrees over 240 frames and back to it's starting position. I can't seem to figure out how to do this. Any help would be appreciated.

```
public GameObject targetObject;
public float rDistance = 1.0f;
public float rSpeed = 1.0f;;

// Update is called once per frame
void Update()
{

    // Trigger functions if Rotate is requested
    if (Input.GetKey(KeyCode.LeftArrow)) {
        RotateLeft(true);
    } else if (Input.GetKey(KeyCode.RightArrow)) {
        RotateLeft(false);
    }

}

protected void RotateLeft(bool goLeft)
{

    float step = rSpeed * Time.deltaTime;
    float orbitCircumfrance = 2F * rDistance * Mathf.PI;
    float distanceDegrees = (rSpeed / orbitCircumfrance) * 360;
    float distanceRadians = (rSpeed / orbitCircumfrance) * 2 * Mathf.PI;

    if (goLeft) {
        transform.RotateAround(targetObject.transform.position, Vector3.up, -distanceRadians);
    } else {
        transform.RotateAround(targetObject.transform.position, Vector3.up, distanceRadians);
    }

}

```

# Answer
> 0 votes
You'll want to use ***Lerp***. `Lerp` interpolates between 0 and 100%, so you can use it inside the `Update` loop to interpolate from the angle that you are to the angle that you want to be, according with a speed and the time elapsed.

You can see the documentation of `Mathf.Lerp()` here, but I also recommend that you take a look in the documentation of `Quaternion.Lerp()` here and `Quaternion.Slerp()` here.

If you just google *unity rotation lerp* you'll find plenty of examples.

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


# Question
Title: How can I load a picture with alpha channel in JME?
This code loads a picture into the game:

```
Picture mypic= new Picture("mypic");
        Texture2D tex = (Texture2D) assetManager.loadTexture("Textures/mypic.png");
        mypic.setTexture(assetManager, tex, false);
        mypic.setHeight(settings.getHeight());
        mypic.setWidth(settings.getWidth());

```

What have to be modified or add to show properly a picture with an alpha channel?

# Answer
You should change this:

```
mypic.setTexture(assetManager, tex, false);

```

to this:

```
mypic.setTexture(assetManager, tex, true);

```

to show a picture with an alpha channel.

The third parameter is `useAlpha`, which, if set to false will just render your transparent/translucent pixels as black.
> 1 votes

---
Tags: 2d, graphics, jmonkeyengine, alpha
---


# Question
Title: Box2d world width and height ratio with screen width and height
I have view, for example **GameView** which extends **SurfaceView** . I have integrated Box2D physics in GameView. I have two widths ,

GameView width, height and Box2D physics world width ,height. I need to get the position of box2d world with the GameView co-ordinates.

For example,

Total width of screen = 240 Total height of screen = 320

Screen points needed to be mapped onto box2d co-ordinates (x,y) = 127, 139

For this i need to get the max width and height of the Box2d physics world. Is there is any way to get the max width and height of Box2d world.

or

Can i limit the width and height of box2d world within the screen resolution.

# Answer
You're attempting to mix your data object with your visual objects. For the purpose of this issue, this is a big no-no.

Your screen is a visual object, and your sprites/models/etc are visual objects. Those will matter. Box2D on the other hand is not a visual object, so there is no magical direct mapping.

You could decide that arbitrarily the top-left corner of the screen maps to 0,0 in Box2d, and that every 10 pixels is equivelant to 1 unit in Box2D. For your data model that would work just fine.

The real question here is how does your Box2D units match your visual units. If you have a 64x64 2d sprite that happens to be a box. How big is your box2d square? Is it 1 unit, 10 units, or 64 units?
> 2 votes

# Answer
You need a transform from your screen to world coordinates. This is usually accomplished with a 'scale' factor and a positional offset. For the testbed I use a Mat22 (which means I can do rotation), a center position, and the screen size measurements:

https://github.com/dmurph/jbox2d/blob/master/jbox2d-library/src/main/java/org/jbox2d/common/OBBViewportTransform.java
> 0 votes

---
Tags: android, jbox2d
---


# Question
Title: How to store XMLs in Unity for web player deployment?
I've created with Unity a short demo that works as a standalone .exe on Windows, and I was interested in deploying it as a web player game too.

When I run the game on the web player, though, I get this error in the Unity console:

> **StreamingAssets is not available on this platform.**

I have some XMLs I parse at runtime in the *StreamingAssets* folder. Where can I put them in a web player build so to be able at runtime to load them?

Thanks for your answers.

# Answer
> 1 votes
Found a solution so to use the same code for both Windows and Web Player deployment (disclamer: I'm just reading these XML files): you can put the XMLs in the *Resources* located into the Project *Assets* folder. This basically tells to Unity to keep these files into the final build and you can load them at runtime using (in case of xmls for example):

```
XmlDocument doc = new XmlDocument();
TextAsset myXmlAsset = Resources.Load<TextAsset>("myXml");
doc.LoadXml(myXmlAsset.text);

```

I hope this helps someone :)

---
Tags: unity, web, xml
---


title: Rendering to specific face of a cubemap

text:
# Question
Title: Rendering to specific face of a cubemap
I have working omnidirectional shadow maps for point lights. Rendering a shadow map for one point light consists of rendering the scene to 6 separate rendertargets, then send those render target textures (shaderresourceviews) to a pixel shader which will shadow the scene by projective texturing. Switching rendertargets 6 times for each point light however is quite costly, and so does sampling from those in the pixel shader later.
My question is how would I access a face of the cubemap to render to? Now I am doing Id3d11devicecontext::omsetrendertargets(1,NULL,&depthtarget) . My depthtarget is a texture2d which is bound to a depthstencil view and a shaderresource which is set up to be a cubemap. Can I even set an individual face to render to or is the process completely different?

# Answer
> 1 votes
Use a geometry shader for this, writing to SV\_RenderTargetArrayIndex to determine which cubemap face to write to. See the CubeMapGS sample for D3D10 in the old DirectX SDK - the process is the very same with 11.

---
Tags: directx11, shadow-mapping
---


title: Flick Gesture in Unity3D Android

text:
# Question
Title: Flick Gesture in Unity3D Android
I'm trying to create a football game where the user will make a flick gesture in order to kick the ball. I'm quite new to developing games in unity3d, I have successfully made a moving ball, added some rotation, gravity and some basic input (the ball follows the touch coordinates). How can I achieve the flick gesture?

# Answer
> 1 votes
If you want to stay in the "Unity state of mind" and keep your code platform independent (even if just so you can easily test on your desktop), I found the easiest way to handle gestures is using one of the gesture plugins.

I can recommend two:

1. TouchKit by Prime31 \- free and open source
2. Input.Touches \- available in the asset store, not free.

Also worth mentioning is TouchScript a very professional free library, but may be an overkill for your needs.

# Answer
> 1 votes
At my company we use FingerGestures

Using that add-on, you'd be listening for and responding to events like: FingerGestures.OnFingerDragBegin += FingerGestures\_OnFingerDragBegin; FingerGestures.OnFingerDragMove += FingerGestures\_OnFingerDragMove; FingerGestures.OnFingerDragEnd += FingerGestures\_OnFingerDragEnd;

Use the position returned from drag begin and drag end to determine the magnitude and direction of the drag, and record the start and end times in the event handlers to see how fast the gesture was. A drag done quickly is a flick.

# Answer
> 0 votes
A nice resource regarding basics of flick gesturing at MSDN http://msdn.microsoft.com/en-us/library/windows/desktop/ms694980%28v=vs.85%29.aspx

Regarding Unity3D, you can take help from the following resource http://forum.unity3d.com/threads/53587-Flick-and-Slide

The following code may help you

```
    // one finger gestures
    if (iPhoneInput.touchCount == 1) {

        // finger data
        iPhoneTouch f0 = iPhoneInput.GetTouch(0);

        // finger delta
        Vector3 f0Delta = new Vector3(f0.deltaPosition.x, -f0.deltaPosition.y, 0);

        // if finger moving
        if (f0.phase == iPhoneTouchPhase.Moved) {

            // compute orbit speed
            orbitSpeed += (f0Delta + f0Delta * distWeight) * orbitScreenToWorldRatio * Time.deltaTime;
        }
    }

    // two fingers gestures
    else if (iPhoneInput.touchCount == 2) {

        // fingers data
        iPhoneTouch f0 = iPhoneInput.GetTouch(0);
        iPhoneTouch f1 = iPhoneInput.GetTouch(1);

        // fingers positions
        Vector3 f0Pos = new Vector3(f0.position.x, f0.position.y, 0);
        Vector3 f1Pos = new Vector3(f1.position.x, f1.position.y, 0);

        // fingers movements
        Vector3 f0Delta = new Vector3(f0.deltaPosition.x, f0.deltaPosition.y, 0);
        Vector3 f1Delta = new Vector3(f1.deltaPosition.x, f1.deltaPosition.y, 0);

        // fingers distance
        float f0f1Dist = Vector3.Distance(f0.position, f1.position);

        // if both fingers moving
        if (f0.phase == iPhoneTouchPhase.Moved && f1.phase == iPhoneTouchPhase.Moved) {

            // fingers moving direction
            Vector3 f0Dir = f0Delta.normalized;
            Vector3 f1Dir = f1Delta.normalized;

            // dot product of directions
            float dot = Vector3.Dot(f0Dir, f1Dir);

            // if fingers moving in opposite directions
            if (dot < -0.7f) {

                float pinchDelta = f0f1Dist - lastf0f1Dist;

                // if fingers move more than a threshold
                if (Mathf.Abs(pinchDelta) > 2) {

                    // if pinch out, zoom in
                    if (f0f1Dist > lastf0f1Dist && zoomDistance > zoomNearLimit) {
                        zoomSpeed += (pinchDelta + pinchDelta * distWeight) * Time.deltaTime * zoomScreenToWorldRatio;
                    }

                    // if pinch in, zoom out
                    else if (f0f1Dist < lastf0f1Dist && zoomDistance < zoomFarLimit) {
                        zoomSpeed += (pinchDelta + pinchDelta * distWeight) * Time.deltaTime * zoomScreenToWorldRatio;
                    }
                }

                // detect twist
                if (f0Delta.magnitude > 2 && f1Delta.magnitude > 2) {

                    // homemade algorithm works, but needs code review
                    Vector3 fingersDir = (f1Pos - f0Pos).normalized;
                    Vector3 twistNormal = Vector3.Cross(fingersDir, Vector3.forward);
                    Vector3 twistAxis = Vector3.Cross(fingersDir, twistNormal);
                    float averageDelta = (f0Delta.magnitude + f1Delta.magnitude) / 2;
                    if (Vector3.Dot(f0Dir, twistNormal) > 0.7f) {
                        twistSpeed =  twistAxis.z * averageDelta * Time.deltaTime * twistScreenToWorldRatio;
                    }
                    else if (Vector3.Dot(f0Dir, twistNormal) < -0.7f) {
                        twistSpeed = -twistAxis.z * averageDelta * Time.deltaTime * twistScreenToWorldRatio;
                    }
                }
            }
        }

        // record last distance, for delta distances
        lastf0f1Dist = f0f1Dist;

        // decelerate zoom speed
        zoomSpeed = zoomSpeed * (1 - Time.deltaTime * 10);
    }

```

---
Tags: android, unity
---


# Question
Title: Pygame window becomes unresponsive when I click it
I'm new to programming, python and pygame. This is some code I wrote to draw random colored rectangles on an 800 x 600 canvas. It does what I expected it to do but becomes unresponsive if I click anywhere on the window. I am on a 64 bit windows 7 system running 32 bit python 2.7 with the appropriate pygame 1.9.1.

```
    import pygame as pg
    from random import randint as rand

    pg.init()
    screen_size = (800,600)
    canvas = pg.display.set_mode(screen_size)
    pg.display.set_caption('Random Rects')
    curEvent = pg.event.poll()
    running = True
    todraw = []

    class rect:
        def __init__(self, x, y, (width, height)):
            self.x = x
            self.y = y
            self.width = width
            self.height = height
            self.color = (rand(0,255),rand(0,255),rand(0,255))
        def topygame(self):
            return self.color,(self.x,self.y,self.x+self.width,self.y+self.height)

    for x in range(100):
        todraw.append(rect(rand(0,800), rand(0,600), (rand(0,100), rand(0,100))))

    for x in todraw:
        pg.draw.rect(canvas, *(x.topygame()))

    while running:
        pg.display.flip()
        for event in pg.event.get():
            if event.type==pg.event.QUIT:
                running = False

```

# Answer
> 4 votes
```
Traceback (most recent call last):
  File "C:\Users\Kylotan\Desktop\test_pg.py", line 31, in <module>
    if event.type==pg.event.QUIT:
AttributeError: 'module' object has no attribute 'QUIT'

```

I added `from pygame.locals import *` to the top and changed it to just 'QUIT', and it works for me.

It's not the clicking that makes the window unresponsive, it's that the clicking makes the operating system try to send it an event, which it realises never gets handled, so the OS realises something is wrong. The reason it never gets handled is probably because the Pygame app had already crashed (with the error above) but for some reason hadn't closed the rendering window yet.

# Answer
> 0 votes
Add

```
pygame.event.wait()

```

to your main loop - without this your application will render data too fast and it will cause application "hang"

# Answer
> 0 votes
When you click inside the window and you are not defining any state condition when the event happens it may hang.

So add this condition anywhere:

```
for event in pygame.event.get():
    if event.type == MOUSEBUTTONUP:
        None

```

This would tell it when you click the mouse *do nothing* so it will not hang.

That worked for me.

---
Tags: python, pygame
---


# Question
Title: How can I have human-readable key names in a configuration file?
Given a file mapping keys to controls, such as this:

```
up         w
down       s
left       a
right      d
jump   space
run    shift
crouch  ctrl

```

The values need to be converted into game commands, and constants. The commands aren't so much a problem as the keyboard keys are; a keyboard can contain over 100 keys, so the last thing desired is this:

```
unsigned int pressedKey;
if (value == "a") {
    pressedKey = KEY_A;
} else if (value == "b") {
    pressedKey = KEY_B;
} else if (value == "c") {
    pressedKey = KEY_C;
} else if...

```

What comes to mind would be to build a map of key value pairs, something like this:

```
std::unordered_map<std::string, unsigned int> keyFinder;
keyFinder.emplace("a", KEY_A);
keyFinder.emplace("b", KEY_B);
keyFinder.emplace("c", KEY_C);
// and so on

```

This would allow for fast lookups, but on the downside it still has to be hardcoded, and it's not going to be a pretty segment of code.

I'd love to hear some good solutions for reading a file and using it to map controls! If it involves using some other file format, that's fine too, as long as it's human readable.

# Answer
> 1 votes
Keep it simple. I think you should use a map (like your `unordered_map` example). And you should just hard code the entire map like you suggested:

```
std::unordered_map<std::string, unsigned int> keyFinder;
keyFinder.emplace("a", KEY_A);
keyFinder.emplace("b", KEY_B);
keyFinder.emplace("c", KEY_C);
keyFinder.emplace("ctrl", KEY_CONTROL);
keyFinder.emplace("shift", KEY_SHIFT);
// ...

```

It's *much* easier and cleaner than correctly identifying the textual equivalents of all possible keys on all possible keyboards in a standard way. Keyboards are very *complicated*.

You *can* programmatically produce the mapping from key code to key text. On Windows, for example, iterate over every virtual key code, call `MapVirtualKey` to translate to scan codes, then call `GetKeyNameText`. There are similar processes for other operating systems. However, the key text you get back is set by the keyboard driver *and* translated based on the locale settings in almost all cases. This makes the data unreliable for use in configuration files.

A technique like the above *can* be useful for displaying the actual keys that a user should press (for example as part of an on-screen prompt), but not for producing a reliable textual mapping. Consequently, I think you are better off just hard-coding your desired mapping. Once you have this mapping to key names, put your key-name-to-action mappings in a JSON/XML/YAML/whatever-text-based-format-your-prefer file.

(Note that on some OSs, like Windows, the virtual key codes for A - Z map to the ASCII values for uppercase A - Z, so you can save yourself *some* typing there; you can find similarly exploitable patterns with numbers and F-keys, usually).

---

All of that said, I do agree with Sean's comment that you can avoid the need for this mapping entirely by providing good GUI support for adjusting keyboard bindings; then you can store out the locale-agnostic key values (virtual key codes on Windows) into your configuration file.

---
Tags: c++, input, file-format, control, settings
---


title: 2D XNA C#: Texture2D Wrapping Issue

text:
# Question
Title: 2D XNA C#: Texture2D Wrapping Issue
Working in C#/XNA for a Windows game: I'm using Texture2D to draw sprites. All of my sprites are 16 x 32. The sprites move around the screen as you would expect, by changing the top X/Y position of them when they're being drawn by the spritebatch.

Most of the time when I run the game, the sprites appear like this:

and when moved, they move as I expect, as one element.

Infrequently they appear like this:

and when moved it's like there are two sprites with a gap in between them - it's hard to describe.

It only seems to happen sometimes - is there something I'm missing? I'd really like to know why this is happening.

**\[Edit:\]** Adding Draw code as requested:

This is the main draw routine - it first draws the sprite to a RenderTarget then blows it up by a scale of 4:

```
protected override void Draw(GameTime gameTime)
{
    // Draw to render target
    GraphicsDevice.SetRenderTarget(renderTarget);
    GraphicsDevice.Clear(Color.CornflowerBlue);
    Texture2D imSprite = null;

    spriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.PointWrap, null, null);
    ManSprite.Draw(spriteBatch);
    base.Draw(gameTime);
    spriteBatch.End();

    // Draw render target to screen
    GraphicsDevice.SetRenderTarget(null);

    imageFrame = (Texture2D)renderTarget;

    GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0);
    spriteBatch.Begin(SpriteSortMode.FrontToBack, null, SamplerState.PointClamp, null, null);
    spriteBatch.Draw(imageFrame, new Vector2(0, 0), null, Color.White, 0, new Vector2(0, 0), IM_SCALE, SpriteEffects.None, 0);
    spriteBatch.End();

}

```

This is the draw routine for the Sprite class:

```
public virtual void Draw(SpriteBatch spriteBatch)
{
    spriteBatch.Draw(Texture, new Vector2(PositionX, PositionY), null, Color.White, 0.0f, Vector2.Zero, Scale, SpriteEffects.None, 0.3f);
}

```

# Answer
> 0 votes
I eventually resolved this issue; it was to do with a faulty graphics chipset in the computer I was developing on. A new graphics card was required.

# Answer
> 1 votes
(If you haven't solved it already)

Two things you can do to debug this further (if my solutions are not your problem) and give us more information:

1. Use a normal SpriteBatch.Begin. (i.e. Just have a SpriteSortMode and a BlendState. No PointWrap (which I think may be your problem since you're scaling it.) If that doesn't work then:
2. Comment out the Rendertarget code and render normally. I've seen some of my Rendertargets do wonky stuff like this, so I wouldn't rule it out.

Also, @Blecki, base.Draw simply draws something tagged as a DrawableGameComponent. All the code is doing there is drawing the rendertarget on top of any other automatic draw calls. That shouldn't be a problem.

I would bet my money on the PointWrap, as it will "wrap" the sprite when it is scaled if it cannot scale it uniformly.

---
Tags: xna
---


title: Orthographic Camera Zooming

text:
# Question
Title: Orthographic Camera Zooming
In XNA I am using a spritebatch to render a board. I have created a camera class which can provide me a view and projection matrix. Currently I am supplying the view matrix to my sprite batch when I call begin.

I can get the view matrix to correctly move everything around and do some zooming in and out. My problem is that I want to zoom in on a specific point (for now the center of the screen) but currently zooming just zooms in on the coordinate 0,0.

Here is how I am constructing the view matrix;

```
        _ViewMatrix =
            Matrix.CreateTranslation(
                new Vector3(
                    (-_Position.X + _Width * _Zoom / 2),
                    (-_Position.Y + _Height * _Zoom / 2),
                    0) ) *
            Matrix.CreateScale(new Vector3(_Zoom, _Zoom, 1));

```

How could this be altered to make it scale correctly relative to the given point. Later I will probably want to zoom to the mouse position, but if someone has a simple example I'm sure I can work out how to adapt it.

# Answer
The following code creates the desired result.

```
        _ViewMatrix =
            Matrix.CreateTranslation(-Position.X, -Position.Y, 0) *
            Matrix.CreateScale(_Zoom, _Zoom, 1.0f) *
            Matrix.CreateTranslation(_Width / 2, _Height / 2, 0.0f);

```

This will cause the camera to zoom into the center of the screen instead of the top left corner.

My understanding is that this code moves the camera such that the object I want to focus on, which is at (Position.X, Position.Y), is in the top left corner (0,0), then I'm scaling by the zoom factor and then finally moving the camera by half width/height so the top left corner is now in the center.

The code in the question would move the object to the center of the camera, but scaling is always in relation to the origin which would therefore move the point further away from 0,0 and thus it isn't at the center any more.
> 1 votes

---
Tags: xna, mathematics, sprites, camera
---


# Question
Title: Bounding Box in Monogame for mouse picking
Hello guys so I'm implementing this mouse manager to be able to pick up objects.

My application uses mainly textured quads in 3d space. I'm using bounding boxes in monogame to do so, however my solution lacks accuracy.

Right now what I have is this: https://i.stack.imgur.com/xXIYo.jpg

you can clearly see what the problem is, so this solution is probably not the best.

this is my method to calculate the bounding box:

```
        public BoundingBox GetBoundingBox()
    {
        Matrix transform = Node.GetTransformForBoundingBox();

        vertices[0] = Vector3.Transform(new Vector3(0, 0, 0), transform);
        vertices[1] = Vector3.Transform(new Vector3(Texture.Width * m_fTexturescale, 0, 0), transform);
        vertices[2] = Vector3.Transform(new Vector3(0, (Texture.Height * m_fTexturescale) * -1, 0), transform);
        vertices[3] = Vector3.Transform(new Vector3(Texture.Width * m_fTexturescale, (Texture.Height * m_fTexturescale) * -1, 0), transform);

        return BoundingBox.CreateFromPoints(vertices);
    }

```

And the mouse picking part is the standard ray tracing into near/far clipping planes with unproject.

So I was thinking, maybe if I do the other way around, and instead of un-projecting the mouse, i could project all the vertices and do some kind of polygon math to check if the mouse position is inside the polygon formed from the projected vertices, (occluded vertices are worrying me though).

Do you think is feasible, or is there any other option, should i just go for OBB?

Thanks alot,

Roger Martins

EDIT:

So after searching a bit for OBB's i found that CartBlanche had one implementation on his samples repo

this: https://github.com/CartBlanche/MonoGame-Samples/blob/master/CollisionSample/BoundingOrientedBox.cs

so I just used it and it works pretty well, now i just have one bug that i cant figure out, one transformation must be wrong.¨

result : https://i.stack.imgur.com/rzg4u.jpg

what i'm doing: so now I have a box parameter in this class, nullable one.

how I build the bounding box :

```
  public SOrientedBoundingBox GetBoundingBox()
    {
        //create the initial bounding box
        if (obb == null)
        {
            //calculate the vertices for the textured quad in model space at the origin (inferior left corner is origin because we invert the y to conpensate for the perspective projection)
            vertices[0] = new Vector3(0, 0, 0);
            vertices[1] = new Vector3(Texture.Width * m_fTexturescale, 0, 0);
            vertices[2] = new Vector3(0, (Texture.Height * m_fTexturescale) * -1, 0);
            vertices[3] = new Vector3(Texture.Width * m_fTexturescale, (Texture.Height * m_fTexturescale) * -1, 0);
            //get bounding box and trasnform it to orientedboundingbox
            //TODO : remove the middle step
            BoundingBox box = BoundingBox.CreateFromPoints(vertices);
            obb = SOrientedBoundingBox.CreateFromBoundingBox(box);
            return obb.Value;
        }
        else
        {
            return obb.Value.Transform(Node.GetQuaternion(), new Vector3(Node.AbsolutePosition.X, Node.AbsolutePosition.Y * -1, Node.AbsolutePosition.Z)*Node.Scale);
        }

    }

```

I'm going to fiddle a bit more with it, but the problem is something minor, i think. But maybe one of you can detect something silly i did.

Thanks, Roger.

# Answer
> 1 votes
in https://github.com/CartBlanche/MonoGame-Samples/blob/master/CollisionSample/BoundingOrientedBox.cs

the box is calculated based in a center vector and a distance to the edge. after transformations in the textured quad, that distance changes, so i had to basicaly update that to correct the bug. result: https://www.dropbox.com/s/5e02onl4ftsaett/BoundingBox.gif

method:

```
       public SOrientedBoundingBox GetBoundingBox()
{
    //create the initial bounding box
    if (obb == null)
    {
        //2-------3
        //|       |
        //|       |
        //0-------1
        //calculate the vertices for the textured quad in model space at the origin (inferior left corner is origin because we invert the y to compensate for the perspective projection)
        m_objVertices[0] = new Vector3(0, 0, 0);
        m_objVertices[1] = new Vector3(Texture.Width * m_fTexturescale, 0, 0);
        m_objVertices[2] = new Vector3(0, -(Texture.Height * m_fTexturescale), 0);
        m_objVertices[3] = new Vector3(Texture.Width * m_fTexturescale, -(Texture.Height * m_fTexturescale), 0);

        //get bounding box and trasnform it to orientedboundingbox
        //TODO : remove the middle step

        BoundingBox box = BoundingBox.CreateFromPoints(m_objVertices);
        obb = SOrientedBoundingBox.CreateFromBoundingBox(box);
        return obb.Value;
    }
    else
    {
        //calculate the transformed vertices without rotations
        // this means they are in the model space, in the origin (0,0,0)
        m_objDummyVertices[0] = Vector3.Transform(new Vector3(0, 0, 0), Node.GetScaledTranslationInvY());
        m_objDummyVertices[1] = Vector3.Transform(new Vector3(Texture.Width * m_fTexturescale, 0, 0), Node.GetScaledTranslationInvY());
        m_objDummyVertices[2] = Vector3.Transform(new Vector3(0, -(Texture.Height * m_fTexturescale), 0), Node.GetScaledTranslationInvY());
        m_objDummyVertices[3] = Vector3.Transform(new Vector3(Texture.Width * m_fTexturescale, -(Texture.Height * m_fTexturescale), 0), Node.GetScaledTranslationInvY());

        //calculate the new length of the sides, this is needed beacause the bounding box uses the side size to calculate intersections, and not the vertices
        Vector3 half = new Vector3(Vector3.Distance(m_objDummyVertices[0], m_objDummyVertices[1]) * 0.5f, Vector3.Distance(m_objDummyVertices[0], m_objDummyVertices[2]) * 0.5f, 0);
        //get the original, its saved in the member box
        Vector3 halforig = obb.Value.HalfExtent;
        //find the diference to ajust the new translation
        Vector3 diference = (half - halforig);
        //ajust translation and add the diference, the Y flipping is needed to compensate for the perspective
        // TODO : figure something out for all the new vector3 used here
        Vector3 translation = (new Vector3(Node.AbsolutePosition.X, Node.AbsolutePosition.Y, Node.AbsolutePosition.Z) + diference) * new Vector3(1, -1, 1);
        //transform the original box
        return obb.Value.Transform(Node.GetQuaternion(), translation, half);
    }
}

```

---
Tags: rotation, monogame, mouse, bounding-boxes
---