title: Bitmap to Texture2D problem with colors

text:
# Question
Title: Bitmap to Texture2D problem with colors
I have a small problem with converting a bitmap to a Texture2D. The resulted image of the conversion has the red channel switched with the blue channel :/ I don't know why, because the pixel formats are the same. If someone can help me I will be very happy :)

```
      System.Drawing.Image image =
            System.Drawing.Bitmap.FromFile(ImageFileLoader.filename);
        System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image);
        Texture2D mapTexture = new Texture2D(Screen.Game.GraphicsDevice, bitmap.Width, bitmap.Height,false,SurfaceFormat.Color);

        System.Drawing.Imaging.BitmapData data =
            bitmap.LockBits(new System.Drawing.Rectangle(
            0, 0, bitmap.Width, bitmap.Height),
            System.Drawing.Imaging.ImageLockMode.ReadOnly,System.Drawing.Imaging.PixelFormat.Format32bppArgb);

        byte[] bytes = new byte[data.Height * data.Width*4];

        System.Runtime.InteropServices.Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);

        mapTexture.SetData<byte>(bytes, 0, data.Height * data.Width * 4);

        bitmap.UnlockBits(data);
        bitmap.Dispose();
        image.Dispose();

```

# Answer
What you are seeing is not unusual. Image data is often stored as either BGR or RGB. (Plus there's ARGB vs RGBA and also premultiplication to take into consideration.)

XNA's `SurfaceFormat.Color` is ARGB.

For XNA 4 you generally want premultiplied alpha (this has more to do with what blend settings you use or need to use). If your image is entirely opaque it won't matter.

I'm pretty sure that the problem in your code arises from your use of `LockBits`. While `LockBits` gives you an opportunity to select a pixel format, it ***doesn't actually perform any conversion***. So you've basically told it that a ABGR image is ARGB - you've lied to it! (I believe ABGR is a common format for Windows bitmaps.)

The solution is, of course, to swap the Red and Blue bytes in your temporary buffer before you set them on the XNA texture.
> 6 votes

# Answer
Here's a method i figured out, that is fast and swaps the red and blue fast also:

```
    private Texture2D GetTexture(GraphicsDevice dev, System.Drawing.Bitmap bmp)
    {
        int[] imgData = new int[bmp.Width * bmp.Height];
        Texture2D texture = new Texture2D(dev, bmp.Width, bmp.Height);

        unsafe
        {
            // lock bitmap
            System.Drawing.Imaging.BitmapData origdata =
                bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);

            uint* byteData = (uint*)origdata.Scan0;

            // Switch bgra -> rgba
            for (int i = 0; i < imgData.Length; i++)
            {
                byteData[i] = (byteData[i] & 0x000000ff) << 16 | (byteData[i] & 0x0000FF00) | (byteData[i] & 0x00FF0000) >> 16 | (byteData[i] & 0xFF000000);
            }

            // copy data
            System.Runtime.InteropServices.Marshal.Copy(origdata.Scan0, imgData, 0, bmp.Width * bmp.Height);

            byteData = null;

            // unlock bitmap
            bmp.UnlockBits(origdata);
        }

        texture.SetData(imgData);

        return texture;
    }

```
> 1 votes

# Answer
```
    public static Texture2D ConvertToTexture(System.Drawing.Bitmap b, GraphicsDevice graphicsDevice)
    {
        Texture2D tx = null;
        using (MemoryStream s = new MemoryStream())
        {
            b.Save(s, System.Drawing.Imaging.ImageFormat.Png);
            s.Seek(0, SeekOrigin.Begin);
            tx = Texture2D.FromStream(graphicsDevice, s);
        }
        return tx;
    }

```
> 1 votes

# Answer
This works:

```
// Assuming:
uint[] m_PixelsBuffer;
System.Drawing.Bitmap m_Bitmap;

unsafe {
    System.Drawing.Imaging.BitmapData origdata =
        m_Bitmap.LockBits(new System.Drawing.Rectangle(0, 0, m_Bitmap.Width, m_Bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, m_Bitmap.PixelFormat);
    uint* byteData = (uint*)origdata.Scan0;
    for (int i = 0; i < m_PixelsBuffer.Length; i++) {
        m_PixelsBuffer[i] = (byteData[i] & 0x000000ff) << 16 | (byteData[i] & 0x0000FF00) | (byteData[i] & 0x00FF0000) >> 16 | (byteData[i] & 0xFF000000);
    }
    m_Bitmap.UnlockBits(origdata);
}
texture.SetData(m_PixelsBuffer);

```
> 0 votes

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


title: 2D object grids to a dictionary

text:
# Question
Title: 2D object grids to a dictionary
I'm pretty new to Unity and trying to figure out what a good way of transferring objects in a grid to a dictionary would be.

For example, if i have a grid of 2D objects (squares) such as below

```
-------------
| 0 | 1 | 2 |
-------------
    | 3 | 4 |
    ---------
    | 5 |
    -----

```

I would expect my dictionary to be something like

```
myDict =
{
 {"0", 1},
 {"1", 0, 2, 3},
 {"2", 1, 4},
 {"3", 1, 4, 5},
 {"4", 2, 3},
 {"5", 3}
}

```

What i want to do is generate a random grid and then make a dictionary of neighbors of each grid piece that i can later use for other purposes.

Being new to Unity, i'm not really sure what a good way of this would be.

# Answer
OK, I'm assuming that you're creating your random grid inside of a two dimensional array.

```
int[,] grid = new int[5, 5];
int lastVal = 0;

Random r = new Random();

for (int i = 0; i < 5; i++)
{
    int startCol = r.Next(0, 5);
    for (int j = 0; j < 5; j++)
        //-1 indicates that the node is empty
        grid[i, j] = j >= startCol ? lastVal++ : -1;
}

```

After creating the grid, you should discover the neighbors and fill your map accordingly.

```
Dictionary<int, List<int>> valueToNeighborListMap = new Dictionary<int, List<int>>();

for (int i = 0; i < 5; i++)
    for (int j = 0; j < 5; j++)
        if (grid[i, j] != -1)
            valueToNeighborListMap[grid[i, j]] = discoverNeighbors(grid, i, j);

```

Boundaries need to be checked in order to avoid from index out of bounds exception.

```
private List<int> discoverNeighbors(int[,] grid, int row, int col)
{
    List<int> neighbors = new List<int>();

    bool canGoLeft = col > 0;
    bool canGoRight = col + 1 < 5;
    bool canGoUp = row > 0;
    bool canGoDown = row + 1 < 5;

    if (canGoUp && grid[row - 1, col] != -1)
        neighbors.Add(grid[row - 1, col]);
    if (canGoLeft && grid[row, col - 1] != -1)
        neighbors.Add(grid[row, col - 1]);
    if (canGoDown && grid[row + 1, col] != -1)
        neighbors.Add(grid[row + 1, col]);
    if (canGoRight && grid[row, col + 1] != -1)
        neighbors.Add(grid[row, col + 1]);
    if (canGoUp && canGoLeft && grid[row - 1, col - 1] != -1)
        neighbors.Add(grid[row - 1, col - 1]);
    if (canGoUp && canGoRight && grid[row - 1, col + 1] != -1)
        neighbors.Add(grid[row - 1, col + 1]);
    if (canGoDown && canGoLeft && grid[row + 1, col - 1] != -1)
        neighbors.Add(grid[row + 1, col - 1]);
    if (canGoDown && canGoRight && grid[row + 1, col + 1] != -1)
        neighbors.Add(grid[row + 1, col + 1]);

    return neighbors;
}

```
> 0 votes

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


# Question
Title: How can I get a 4x4 matrix from a bullet quaternion?
I'm trying to make a game using JavaScript with Ammo.js ( an implementation of bullet ) and Sylvester to do my matrix maths. The problem is I don't know how to turn the WXYZ that bullet gives into the 4x4 matrix Sylvester needs.

If there is a way to just get Bullet Physics to give me the 4x4 matrix please tell me! I am completely lost here.

# Answer
> 1 votes
Three.JS has a function for this based upon this principle. BTW Matrix4x4 are represented internally as Column-Major, not sure what bullet uses.

Three.js Matrix4x4.makeRotationFromQuaternion(Quaternion)

```
makeRotationFromQuaternion: function ( q ) {

    var te = this.elements;

    var x = q.x, y = q.y, z = q.z, w = q.w;
    var x2 = x + x, y2 = y + y, z2 = z + z;
    var xx = x * x2, xy = x * y2, xz = x * z2;
    var yy = y * y2, yz = y * z2, zz = z * z2;
    var wx = w * x2, wy = w * y2, wz = w * z2;

    te[ 0 ] = 1 - ( yy + zz );
    te[ 4 ] = xy - wz;
    te[ 8 ] = xz + wy;

    te[ 1 ] = xy + wz;
    te[ 5 ] = 1 - ( xx + zz );
    te[ 9 ] = yz - wx;

    te[ 2 ] = xz - wy;
    te[ 6 ] = yz + wx;
    te[ 10 ] = 1 - ( xx + yy );

    // last column
    te[ 3 ] = 0;
    te[ 7 ] = 0;
    te[ 11 ] = 0;

    // bottom row
    te[ 12 ] = 0;
    te[ 13 ] = 0;
    te[ 14 ] = 0;
    te[ 15 ] = 1;

    return this;

},

```

---
Tags: javascript, matrix, bullet-physics
---


# Question
Title: How do I get the mouse coordinates relative to my whole scene with Monogame?
I am making a topdown isometric real time game using Monogame.

I know how to get the mouse position for my camera view. How do I get the mouse coordinates relative to the entire scene?

---

My game's rendering looks isometric, but it's actually simply 2D and the illusion of isometric projection is done with a simple script that converts the cartesian coordinates for the mouse position to isometric ones, which I pass into a simple grid pathfinding algorithm that makes paths from them. This worked well for me when I used Game Maker.

# Answer
> 4 votes
I don't have a specific example for an Isometric camera, but it sounds like you are asking about the basic camera system in general.

The camera I use in my games is somewhat simple and is illustrated in the figure below:

The Camera class contains the following member variables:

```
Vector2 position;
Vector2 viewport;
Rectangle worldRectangle;

```

Converting from world coordinates to camera coordinates is only a matter of subtracting the position of the object from the position of the camera, and going from camera coordinates to world coordinates is only addition.

Getting the position of the mouse on the screen in a 2D game is almost identical to getting the position of an object, and all we have to do is get the on-screen mouse coordinates and add them to the position of the camera.

I do this using the following functions (and various overloads for Vector2, int, etc):

**Note:** The variable position refers to Camera.position, and worldRectangle is defined when the camera is created

```
/// <summary>
/// Converts a rectangle in Pixel-based World coordinates to
/// camera view Screen coordinates
/// </summary>
/// <param name="worldRectangle">Rectangle to convert</param>
/// <returns>The new Screen-based Rectangle</returns>
public Rectangle WorldToScreen(Rectangle worldRectangle)
{
    return new Rectangle(
        worldRectangle.Left - (int)(position.X),
        worldRectangle.Top - (int)(position.Y),
        worldRectangle.Width,
        worldRectangle.Height
    );
}

/// <summary>
/// Converts a rectangle in Screen coordinates to World coordinates
/// </summary>
/// <param name="screenRectangle">Rectangle to convert</param>
/// <returns>The new World-based Rectangle</returns>
public Rectangle ScreenToWorld(Rectangle screenRectangle)
{
    return new Rectangle(
        screenRectangle.Left + (int)position.X,
        screenRectangle.Top + (int)position.Y,
        screenRectangle.Width,
        screenRectangle.Height);
}

```

So in order for you to convert mouse coordinates to world coordinates, all you have to do is have a simple function like the one below, and then pass it to your script:

```
public Vector2 ScreenToWorld(int x, int y)
{
    return new Vector2(position.X + x, position.Y + y);
}

```

This can be confirmed mathematically using the image above and Photoshop (assume pixel units). Suppose that the top left of the world is (0, 0) and the Camera's Viewport is defined by the Rectangle(623, 15, 683, 436). If we hover the mouse over the top-left corner of the player, we get the coordinates (364, 276). In order to find the world location of the point, we add the camera location:

x-coordinate = 364 + 623 y-coordinate = 276 + 15

Which gives us the final coordinates: (987, 291)

---
Tags: xna, 2d, monogame, isometric, coordinates
---


# Question
Title: Varying spritefont quality depending on string
I'm using Kleymissky font size 26 made via Nuclex font renderer (Hinting Method: AutoHinter) - download

Why the thickness of the font drawn on screen depends on the string itself? What can I do to ensure it'll always be drawn one way or another (but not both)?

I'm using MonoGame, dll v3.1.2

# Answer
> 2 votes
The XNA `SpriteFont` class uses the `SpriteBatch` and `Texture2Ds` to back it. Just as when you render any other Texture2D if you use vectors with non whole numbers XNA samples the overlapping source pixels leasing to the unexpected behavior you are experiencing.

To avoid the issue make sure the the you use whole numbers when assigning the location so that the source and destination pixels align.

---
Tags: xna, monogame, fonts
---


# Question
Title: Unity 2D detect if swipe goes through an object
I am developing a game in unity with flying arrows that the user tries to deflect by swiping through them (changing their direction). I can get the arrows to move with the swipes, but they move no matter where the swipes occur. I want them to only move (be affected) iff the swipe goes through the arrow. Here's what I have so far:

```
public class swipe : MonoBehaviour
{

private Vector2 leftFingerPos = Vector2.zero;
private Vector2 leftFingerLastPos = Vector2.zero;
private Vector2 leftFingerMovedBy = Vector2.zero;

public float slideMagnitudeX = 0.0f;
public float slideMagnitudeY = 0.0f;

bool touched = false;

void Update()
{
    if (Input.touchCount == 1)
    {
        Touch touch = Input.GetTouch(0);

        if (touch.phase == TouchPhase.Began)
        {
            leftFingerPos = Vector2.zero;
            leftFingerLastPos = Vector2.zero;
            leftFingerMovedBy = Vector2.zero;

            slideMagnitudeX = 0;
            slideMagnitudeY = 0;

            // record start position
            leftFingerPos = touch.position;

        }

        else if (touch.phase == TouchPhase.Moved)
        {
            leftFingerMovedBy = touch.position - leftFingerPos; // or Touch.deltaPosition : Vector2
            // The position delta since last change.
            leftFingerLastPos = leftFingerPos;
            leftFingerPos = touch.position;

            // slide horz
            slideMagnitudeX = leftFingerMovedBy.x / Screen.width;

            // slide vert
            slideMagnitudeY = leftFingerMovedBy.y / Screen.height;

            if(touched)
            {
                //rigidbody2D.velocity = new Vector2(slideMagnitudeX, slideMagnitudeY)*20;
                rigidbody2D.AddForce(new Vector2(slideMagnitudeX, slideMagnitudeY)*5000);
                touched = false;
            }
        }

        else if (touch.phase == TouchPhase.Stationary)
        {
            leftFingerLastPos = leftFingerPos;
            leftFingerPos = touch.position;

            slideMagnitudeX = 0.0f;
            slideMagnitudeY = 0.0f;
        }

        else if (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled)
        {
            slideMagnitudeX = 0.0f;
            slideMagnitudeY = 0.0f;
        }
    }

}

void OnMouseEnter()
{
    touched = true;
}
}

```

The only way I have been able to find so far is using "onMouseEnter" which only works for very slow swipes.

How do I detect whether a swipe goes through an object?

# Answer
You have both the current position and the last position on move. (touch.position, leftFingerPos)

You can do a ray cast using these to see if there is a collision with your arrow.

http://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html
> 0 votes

---
Tags: 2d, unity, touch
---


# Question
Title: How to calculate left/right oriented angle between two 2D vectors?
I would like to calculate angle between two 2D vectors. Here's a picture of what I'm trying to achieve:

I have an obstacle line segment AB and incoming moving PC. If I'm coming from one side C¹D¹ and angle ⍺ \< π/2 (i.e. right side) then PC will turn left. On the other hand if ⍺ \> π/2 then PC will turn right. But if PC will come from the other side C²D² it should work as well for angle β as per picture.

**So what I need is to determine whether the angle between AB and CD is larger to the left or right basically.**

I've tried these things, while having vectors defined as:

```
Vector2 ab = Vector2.Normalize(new Vector2(b.x - a.x, b.y - a.y));
Vector2 cd = Vector2.Normalize(direction);

```

1) To calculate angle using atan2, but it works only randomly (1/4 of cases).

```
Single angle = Math.Atan2(cd.Y, cd.X) - Math.Atan2(ab.Y, ab.X);

if (angle > MathUtil.PiOverTwo)
{
    RotateRight();
}
else if (angle < MathUtil.PiOverTwo)
{
    RotateLeft();
}

```

2) To use normals somehow. This works a bit better but only from one side I think. (1/2 of cases, better but not there)

```
Vector2 normal1 = Vector2.Normalize(new Vector2(-ab.Y, ab.X));
Vector2 normal2 = Vector2.Normalize(new Vector2(ab.Y, -ab.X));
Double angle1 = Math.Atan2(normal1.Y, normal1.X) - Math.Atan2(cd.Y, cd.X);
Double angle2 = Math.Atan2(normal2.Y, normal2.X) - Math.Atan2(cd.Y, cd.X);

if (angle1 > angle2)
{
    RotateRight();
}
else if (angle1 < angle2)
{
    RotateLeft();
}

```

# Answer
The sign of the dot-product of C with AB will be positive when the vector component of CD parallel to vector AB is in the direction AB, and negative when it is in the direction BA.

The sign of the (z-component of the) cross-product of vector CD with vector AB will indicate which side of AB the agent is approaching from.

Depending on your sign conventions, multiplying these two sign results will either give you -1 =\> turn left, +1 =\> turn right; or the opposite.

**Update:**

Formula for z-component of the cross product of two vectors U and V lying in the XY plane:

> ```
> z(U * V) = Ux . Vy - Uy . Vx
>
> ```

Formula for dot-product of two vectors U and V lying in the XY plane:

> ```
> U . V = Ux . Vx + Uy . Vy
>
> ```
> 5 votes

# Answer
If I understand what you're asking, the vector CD is just a vector, not a ray, so only the direction matters, not location. However, AB is a line segment, not just a vector, so its location matters.

Your tests have one 'if' test to make two cases, but I think you actually have four cases. Let's look at the diagram in AB's reference frame:

If you can calculate the angle between normal1 and vector CD, then from 0-π/2 it's “turn right”, π/2-π it's “turn left”, π-3π/2 it's “turn right”, and 3π/2-2π it's “turn left”.
> 2 votes

---
Tags: c#, 2d, vector, angles, orientation
---


# Question
Title: How to find the 3D object the camera is pointed at
I'm currently developing a 3-dimensional game (the first I've ever done and it's not as hard as I thought it would be!), but I've run into a little bit of a snag. I want to find the current block the crosshairs of the camera are pointed to, and I'm not sure how exactly to do it. The only thing I can think of is starting at the view position and moving like 0.1 units until I hit a space that is occupied by a block, but I feel like that would be a little... brute-force style? Is there an easier/better way to find it?

Here's what I have:

* The `vector3` of the camera position.
* An array of block positions which may or may not be filled with blocks. The block centres are at whole-numbered intervals.

I promise this isn't a minecraft clone. ;)

# Answer
You want to get real familiar with a handy-dandy 3D math operation called Dot Product. Pretty much all 3D graphics libraries include this 3D math function; for example http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.vector3.dot.aspx

The dot product can be used for a number of things, but every use boils down to: when you take the dot product of two vectors, the resulting number tells you how close they are to pointing in the same direction. Exactly the same direction results in 1, perpendicular gives 0, and exactly opposite directions gives -1.

For this specific problem, one vector is the direction the camera is facing, and one vector is the direction from camera to a block (subtract the position of the block from the position of the camera). Get the dot product of these two vectors, and if the result is close to 1 then the camera is pointed at that block. Do this in a loop for all the blocks.

---

I should mention, the more general method for detecting geometry at a specific camera position is to use raycasting, shooting a ray out from the camera. For example, this link explains how to cast a ray from the camera in XNA http://www.enchantedage.com/xna-picking

Such an approach is unnecessarily expensive for a 2D grid of blocks, but would be necessary for a 3D grid of blocks. You didn't specify this in your question, so I assumed "an array of block positions" meant a 2D grid but just realized you may have meant a 3D grid.

The issue is that you don't only need to determine what blocks are being faced; you also need to determine which faced block is nearest. In a 2D grid this is a non-issue since all of the blocks lie on the same plane. However in a 3D grid many blocks overlap each other, which means there could be multiple overlapping blocks all in the direction the camera points toward. Raycasting will detect the first block hit.
> 1 votes

---
Tags: xna, c#, 3d, block-world
---


# Question
Title: Move the Object in y-axis when the timer increases
I have a model(.Fbx object),I have placed a timer.When the timer starts increasing the model/object should move down(along y axis).

# Answer
http://docs.unity3d.com/ScriptReference/Vector3.Lerp.html

Have a look at lerp. You'll be able to move to a position over time like this:

```
transform.position = Vector3.Lerp( start, end, currentTime / totalTime );

```

Where start is the initial position of the object you are moving and end is the place you want to be once currentTime = totalTime. In your case, the end vector would be directly below the object that is being moved.

If you want constant movement while the timer is running, then make sure you know when the timer is running and just do something like this:

```
if( timerIsRunning )
{
    transform.position += Vector3.down * speed * Time.deltaTime;
}

```
> 1 votes

---
Tags: c#, unity, timer, axis
---


# Question
Title: Slow dictionary access with coordinates as keys
I am making a game server and currently I am experiencing a huge performance hit.

I have a class `Map` which holds a `Dictionary` of the class `Tile` with each tile having X, Y, and Z coords, some lists, etc. nothing fancy as it's a MMORPG.

Currently in the `Map` class I have this:

```
public Tile GetTile(Coordinate_t coordinate)
{
    if (Tiles.ContainsKey(coordinate))
    {
        return Tiles[coordinate];
    }
    return null;
}

```

`Coordinate_t` is a struct containing X, Y and Z as UInt32. the Dictionary is represented like this:

```
 Dictionary<Coordinate_t, Tile> Tiles;

```

Basically I need to hold over 7 million tiles in this list, but it's being really slow! Every time I try to get around 12 tiles in a function it increases the program CPU use to 1~3% which is a lot! Since the game server is supposed to hold over 100 players online at a time.

Any ideas why is it being so slow? Are there better ways to hold a huge amount of tiles of a game in a list to be accessed continuously without having such a huge performance hit?

# Answer
When you have a 3-dimensional world and you say you have 7 million tiles, I would assume that your game world is a cube of roughly 200x200x200 tiles.

Instead of storing this in a hash table (Dictionary) you could also store it in a three-dimensional array. Arrays have much less overhead and much more predictable performance characteristics than hash tables.

However, arrays are only a good solution when the size of your data doesn't change. When you want the world to be able to grow dynamically during the game (like in Minecraft where new world data is randomly generated while the player explores), you need to resize the array every time the world grows, which is always a very expensive operation. Also, when you have a sparse world with large empty spaces, an array can be very wasteful because you also need to allocate memory for these areas while more dynamic data structures allow to just have no entry for these tiles.

When this is the case, a Dictionary might be the better choice after all.

When you use a Dictionary, you need to be aware that it is very important that you override the `public int GetHashCode()` method of the objects you store in it in a way that most objects return an unique value. Any objects which return the same value will be stored as a linked list under that key which then needs to be iterated one by one. Considering that your `Coordinate_t` seems to be a set of 3 integers between 0 and 255 (8 bit), you could in fact fit the whole coordinate into the 32bit integer to ensure that each coordinate returns an unique hash code.

```
public override int GetHashCode() {
    return x + y << 8 + z << 16;
}

```

The binary representation of the hash-code of each coordinate-triplet will then be:

```
 00000000zzzzzzzzyyyyyyyyxxxxxxxx

```
> 7 votes

# Answer
Try changing your GetHashCode to something that better distributes the values to reduce the number of collisions in the dictionary.

If your hash code is bad you're going to get the performance of a list rather than a hash-set. To show this consider a GetHashCode method that always returns **0** for any object.

Trying to put that into a Dictionary will force the dictionary to put all the items into the same bucket (http://en.wikipedia.org/wiki/Hash\_table#Hashing), yielding linear search time rather than close to random access time for a perfect hash.

The math behind a clever hash is beyond me, for integer only structs I usually use something similar to the example below.

Consider this implementation of your Coordinate\_t struct;

```
struct Coordinate_t
{
    int x, y, z;
    public Coordinate_t(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public override int GetHashCode() {
        uint h = 0x811c9dc5;
        h = (h ^ (uint)x) * 0x01000193;
        h = (h ^ (uint)y) * 0x01000193;
        h = (h ^ (uint)z) * 0x01000193;
        return (int)h;
    }
}

```

If you comment out the GetHashCode you'll see a massive change in performance when using a dictionary.

Test application

```
struct Coordinate_t {
    int x, y, z;
    public Coordinate_t(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    // Uncomment this to make it go faster
    //public override int GetHashCode() {
    //    uint h = 0x811c9dc5;
    //    h = (h ^ (uint)x) * 0x01000193;
    //    h = (h ^ (uint)y) * 0x01000193;
    //    h = (h ^ (uint)z) * 0x01000193;

    //   return (int)h;
    //}
}

class Program {
    static void Main(string[] args) {
        var tiles = new Dictionary<Coordinate_t, string>();
        var sw = new Stopwatch();
        sw.Start();
        const int count = 100;
        for (var x = 0; x < count; ++x)
            for (var y = 0; y < count; ++y)
                for (var z = 0; z < count; ++z)
                    tiles[new Coordinate_t(x, y, z)] = String.Format("{0}.{1}.{2}", x, y, z);
        sw.Stop();
        Console.WriteLine("Add took {0}", sw.Elapsed);
        sw.Reset();
        sw.Start();
        for (var x = 0; x < count; ++x)
            for (var y = 0; y < count; ++y)
                for (var z = 0; z < count; ++z)
                {
                    var expected = String.Format("{0}.{1}.{2}", x, y, z);
                    if (tiles[new Coordinate_t(x, y, z)] != expected)
                    {
                        throw new Exception("Something is super-broken!");
                    }
                }

        sw.Stop();
        Console.WriteLine("Get took {0}", sw.Elapsed);
    }
}

```
> 3 votes

---
Tags: c#
---


title: Odd Behaviour XNA Game Component

text:
# Question
Title: Odd Behaviour XNA Game Component
Inside of my main class file I am initializing a number of game components which are used to represent game scenes i.e. main menu and game. I am initilizing each component inside of XNAs LoadContent method without issue and set the default scene as the main menu. I then switch to the game scene.

My issue then occurs when I switch back to the main menu scene and then try to start a new game by switch from the menu to the game scene. When I switch from the game to the menu I dispose of the game scene using the GameComponent.Dispose() method provided by the XNA framework.

```
private void UnloadScene(GameScene scene)
{
     scene.Dispose();
}

```

As I have disposed of the game scene I attempt to re-initialize the game scene component with the following method.

```
private void LoadScene(GameScene scene)
{
     scene = new GameScene(this, graphics.GraphicsDevice);
     Components.Add(scene);
}

```

I then switch from the menu scene to the game scene using the following method. This method is called in my Update method after the user has selected new game on the main menu.

```
public void SwitchScene(SceneManager manager)
{
     sceneManager.HideScene();
     sceneManager = manager;
     manager.ShowScene();
}

```

This time when the game scene loads I am met with a cornflower blue background and no assets on screen. I have placed a breakpoint within the above method and seen that the game scene is given all of the required data yet nothing is being drawn.

However if I explicitly place the following code above the SwitchScene() method after the player has selected new game then the scene is drawn without issue.

```
scene = new GameScene(this, graphics.GraphicsDevice);
Components.Add(scene);

```

Below is what the code looks like with the second approach mentioned.

```
if (InputHandler.IsHoldingButton(0, Buttons.A, out throwAway))
{
     switch (menuScene.Index)
     {
          case 0:
              gameScene = new GameScene(this, graphics.GraphicsDevice);
              Components.Add(gameScene);

              SwitchScene(gameScene);
              break;

          case 1:
              this.Exit();
              break;
     }
}

```

Is this behaviour intentional, if so how would I attempt to produce the first approach correctly?

Below is a screenshot of the graphics device after the second attempt to load the game scene. Note the data in this image is identical to the graphics device when loading the game scene for the first time.

Below is the code for the SceneManager class.

```
public class SceneManager : DrawableGameComponent
{
    private readonly List<GameComponent> components;

    public List<GameComponent> Components
    {
        get { return components; }
    }

    public SceneManager(Game game)
        : base(game)
    {
        components = new List<GameComponent>();

        // Indicates whether draw should be called
        Visible = false;

        // Indicates whether GameComponent.Update should be called
        // when Game.Update is called
        Enabled = false;
    }

    public virtual void ShowScene()
    {
        Visible = true;
        Enabled = true;
    }

    public virtual void HideScene()
    {
        Visible = false;
        Enabled = false;
    }

    public override void Update(GameTime gameTime)
    {
        for (int i = 0; i < components.Count; i++)
        {
            if (components[i].Enabled)
                components[i].Update(gameTime);
        }

        base.Update(gameTime);
    }

    public override void Draw(GameTime gameTime)
    {
        for (int i = 0; i < components.Count; i++)
        {
            GameComponent component = Components[i];

            if ((component is DrawableGameComponent) &&
                ((DrawableGameComponent)component).Visible)
            {
                ((DrawableGameComponent)component).Draw(gameTime);
            }
        }

        base.Draw(gameTime);
    }
}

```

# Answer
I have managed to get my application working with the first approach I was attempting to use. It appears that the way I am disposing of the GameScene is the cause of the issue. It seems as though it is also disposing of the SceneManager functionality which the GameScene is derived from as I noticed that none of my update and draw calls in both SceneManager and GameScene were being executed when the application had switched to the game scene.

However this does not explain why the second approach works and the first does not when I am disposing the scene the same way for both approaches. If anyone has any further information on this I would be greatful.

Rather than calling Dispose() on the game scene when I return to the main menu I am now declaring the game scene null.

```
private void UnloadScene(SceneManager scene)
{
     // Old approach
     // scene.Dispose();

     // New approach
     scene = null;
}

```

I am then re-initializing it inside of the LoadScene() method like I attempted originally.

```
private void LoadScene(GameScene scene)
{
     scene = new GameScene(this, graphics.GraphicsDevice);
     Components.Add(scene);
}

```
> 0 votes

---
Tags: xna, c#, xna-4.0, game-component
---


# Question
Title: XNA C# 3D game Wall collision response glitch
I have been working on a reliable physics system in my code and so far it's ALMOST working. :D

I am aiming for wall "sliding" style of collision response, like you'd expect it to work in commercial games.

I have implemented a system that gets a collision geometry from an FBX model. Geometry with specific names will not be rendered, instead they'll be used to construct Oriented Bounding Boxes, further from which a set of Triangle structures will be constructed.

So far, everything went as expected. Triangles are correctly deduced from their parent bounding boxes, each Box having 12 triangles. I have used helper classes to render out the triangles alone, along with their normals, and I know for certain they are transformed and positioned correctly inside the world.

I am using a Ray-Triangle intersection math to determine which triangle is the closest to the player, and from that, grab a normal from which the Physics Vector will later be reflected.

For some reason this all works but only on surfaces of some specific orientation. I have grabbed a screenshot with walls that are successfully collided with marked in Green color:

Against these walls the collision works perfectly, as expected.

Against all others, the collision somehow fails and player can simply walk through.

I have made 100% sure that my triangles are all correctly picked from mesh and positioned in the world and that their normals are correct (I can render all this as helper objects in 3D world).

The most important bits of my code are as follows:

Triangle construction:

```
for (int i = Part.MeshParts[0].StartIndex; i < Part.MeshParts[0].StartIndex + (Part.MeshParts[0].PrimitiveCount * 3); i += 3)
                {
                    Triangle temp = new Triangle();

                    temp.Normal = Vector3.Transform(modelVertices[modelIndices16[i]].Normal, NormalTransform);

                    temp.Normal.Normalize();

                    temp.Vertices[0] = Vector3.Transform(rawData[modelIndices16[i]], Transform);
                    temp.Vertices[1] = Vector3.Transform(rawData[modelIndices16[i + 1]], Transform);
                    temp.Vertices[2] = Vector3.Transform(rawData[modelIndices16[i + 2]], Transform);

                    Triangles.Add(temp);
                }

```

(also a copy for this for 32 bits, not important now),

This is a part of a function that returns Triangle\[\], which is a part of CollidableGeometry structure:

```
 public struct CollidableGeometry
        {
            public OrientedBoundingBox OrientedBox;
            public Triangle[] Triangles;
            public Vector3 TriangleNormal;

        }

```

Now, the most important is the collision detection part.

By this part, we know that OrientedCollisionGeometry\[i\] is colliding with Player's box:

```
for (int x = 0; x < OrientedCollisionGeometry[i].Triangles.Length; x++)
                        {
                            Ray PlayerMovement = new Ray(Player.player, -OrientedCollisionGeometry[i].Triangles[x].Normal);

                            OrientedCollisionGeometry[i].Triangles[x].Intersects(ref PlayerMovement, out tempDistance);

                            if (tempDistance != null)
                            {
                                if (Math.Abs((float)tempDistance) < Math.Abs((float)distance))
                                //if (tempDistance < distance)
                                {
                                    closestIDX = x;
                                    distance = tempDistance;
                                }
                            }
                        }

                        if (closestIDX != -1)
                        {
                            ///Final collision decision:

                            Player.CollisionReflectionVector += OrientedCollisionGeometry[i].Triangles[closestIDX].Normal;

                        }
}

```

This code roughly translates as:

We know there's an oriented bounding box that intersects player's bounding box. We go through all 12 triangles that make up a box: For each triangle, construct a Ray that starts at Player's position, and in the direction of that triangles normal (in negative). If the ray goes through the triangle, record the distance at which it does.

The triangle with lowest distance from the player is marked as most important one, and it's Normal is recorded as the one we need to reflect the player's direction of.

In short, what I know for 100% is NOT wrong:

-The triangles are correctly placed in the world.

-The triangle's normals are correct.

-The oriented box collisions are correct, and determining which OBB from the mesh is colliding with the player is also correct.

SOME surfaces works exactly as expected, and those are all of specific orientation.

The rest produce NO effect.

I can pack up the compiled game, or entire source code if somebody wants to play around and take a look.

I'm completely stumped over this for several days now. Worst part is that it DOES work normally as expected for some walls.

I have picked up the Ray-Triangle intersection from this resource link: http://www.discoverthat.co.uk/games/xna-triangle.htm

As far as I know, winding order of the triangles is also not the problem because you'd be stuck inside the wall (if you were already to go through the outside surface).

So, help?

# Answer
I have figured it out.

Turns out, my logic was correct, however the imported mesh had it's normals messed up for whatever reason. Maybe I used incorrect settings when exporting FBX file from Max.

I have calculated my own normals so now everything is correct.

```
            Triangle temp = new Triangle();

            temp.Vertices[0] = Vector3.Transform(rawData[modelIndices16[i]], Transform);
            temp.Vertices[1] = Vector3.Transform(rawData[modelIndices16[i + 1]], Transform);
            temp.Vertices[2] = Vector3.Transform(rawData[modelIndices16[i + 2]], Transform);

            Vector3 Normal = Vector3.Cross(temp.Vertices[1] - temp.Vertices[0],
                                  temp.Vertices[1] - temp.Vertices[2]);

            Normal.Normalize();

            temp.Normal = Normal;

            Triangles.Add(temp);

```

Some more tweaks and playing around will be needed but it's working fine for now, I like where this is going.
> 1 votes

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


title: How to mirror a texture in libGDX

text:
# Question
Title: How to mirror a texture in libGDX
Is it possible to rotate my sprite in LibGDX?

```
public class Flame {
    private static final int FRAME_COLS = 6;
    private static final int FRAME_ROWS = 1;

    private Animation flameAnimation;
    private Texture flameSheet;
    private TextureRegion[] flameFrames;
    private SpriteBatch spriteBatch;
    private TextureRegion currentFrame;

    private float stateTime;

    private int xFlame;
    private int yFlame;
    private float rotation;

    /*
        Some code here
    */

    public void draw(){
        stateTime += Gdx.graphics.getDeltaTime();
        currentFrame = flameAnimation.getKeyFrame(stateTime, true);
        /*
          I also try currentFrame.flip(true, false); // but this doesn't work
        */
        spriteBatch.begin();
        spriteBatch.draw(currentFrame, xFlame, yFlame);
        spriteBatch.end();
   }

```

# Answer
From LibGDX's docs:

> *spriteBatch.draw(Texture texture, float x, float y, float width, float height, int srcX, int srcY, int srcWidth, int srcHeight, boolean flipX, boolean flipY)*
>
> Draws a rectangle with the bottom left corner at x,y having the given width and height in pixels.

Set flipX as true to get your desired result
> 7 votes

---
Tags: libgdx, sprites
---


# Question
Title: How to create polygons from tilemap areas?
I'm currently working on a project which needs simple AI's to walk around using pathfinding.

I'm trying to find a way to generate a polygon based on the connected tiles (explained below), an i'm wondering how to do this.

I know about the flood fill algorithm, but have never used it before.

This is what a map (could) look like (maps are created by the players)

Basically, i wan't the yellow outline as one polygon (vector2 array) and the red outline/area as another polygon (vector2 array)

# Answer
For the exact problem (how to create a polygon from tiles forming some area) you basically:

1. Flood fill the area to limit the number of tiles you check and avoid situations alike checkerboard pattern (where edge node can have 4 neighbour edge nodes)
2. Pick up a node on the edge of the area
3. Look for the nodes that are connected to it, that lay on the edge too (there should be always 2)
4. At first you will get 2 nodes, pick one to go one of the direction
5. Repeat step2 for new node, ignoring the one you already parsed
6. Repeat 2-4 until you have closed the loop - that is your polygon.
7. Optionally remove nodes from straight sides.

P.S. This algo has a name, but I cannot recall it, sorry.
> 1 votes

---
Tags: procedural-generation, tilemap
---


# Question
Title: iOS Facebook SDK, Games Start Playing post
im trying to implement a method in my native iOS game the publish a story on face book such as this photo

most games that is integrated with facebook share stories like this in the activity section on the timeline

any good example especially for iOS 6

# Answer
> 1 votes
What you are looking for is called "actions". Here is how to post an action.

```
// create an Open Graph action
id<FBOpenGraphAction> action = (id<FBOpenGraphAction>)[FBGraphObject graphObject];
[action setObject:objectId forKey:@"dish"];

// create action referencing user owned object
[FBRequestConnection startForPostWithGraphPath:@"/me/fbogsample:eat" graphObject:action completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
  if(!error) {
    NSLog([NSString stringWithFormat:@"OG story posted, story id: %@", [result objectForKey:@"id"]]);
    [[[UIAlertView alloc] initWithTitle:@"OG story posted"
                                message:@"Check your Facebook profile or activity log to see the story."
                               delegate:self
                      cancelButtonTitle:@"OK!"
                      otherButtonTitles:nil] show];
  } else {
    // An error occurred
    NSLog(@"Encountered an error posting to Open Graph: %@", error);
  }
}];

```

However, before you post a question about Facebook open-graph in general, you should check here first.

---
Tags: ios, objective-c, facebook
---


# Question
Title: Should I bother merging faces in my 3D block-based game?
Okay, so I have a bunch of cubes in a 3d-world. I already implemented face culling, so that when a cube is next to another cube, their touching faces won't be drawn, or even sent to the buffer. However, a while back when I was still researching how to make a 3d block-based game, I came across a stack overflow question where the asker posted an image of their cubes, which had not only been culled but they had also merged the faces of adjacent cubes into larger rectangular faces. Like this:

My question is, should I do this? Will the drawing time be saved enough to justify the longer update time? And if so, I'm not even sure if it would work some of the time. The cubes aren't textured, they're coloured, so I'm not entirely sure if it would work with multiple colours of cubes.

# Answer
There are many different variables that come into play regarding this. If two faces are next to each other that use different textures, light levels, colors, etc.. you more than likely won't be able to join them together anyhow (nearly anything's possible with enough work, but it'd probably be **FAR** too much work).

If, however, you have a lot of cube faces with the same textures, light levels, and colors, it's totally possible and could make a huge difference in your performance.

My engine, which may be completely different than yours, keeps all like faces segregated into different arrays. By this, I mean for a chunk (32x128x32), all visible faces that are on the tops of all the cubes are in their own array and the same for the north faces, the west faces, the bottom faces, etc. With this, I can easily cull entire chunks from being passed to the render stage or I can simply skip sending all west faces from a chunk that the player is east of.

With that in mind and understanding that joining neighboring cube faces requires nearly identical data on each of them, if you set up a good way to keep your arrays sorted and "walk" over the array properly, it's completely possible to improve performance. Whether or not you want to go through all the work to find out is up to you though.

I don't think anyone can actually answer the question of SHOULD you do this except you. Without knowing how you store your data, how often you have situations that even let you join faces, etc.. I don't think anyone can truly answer.

If you want to look into it though, I'd suggest going the shader route described here. That's the way I'd suggest doing the actual joining. To join them, however, I suggest the way I describe in this post at the end. It's easy, while not 100% optimal, it is quite fast.
> 4 votes

---
Tags: xna, c#, 3d, block-world
---


# Question
Title: How can I analyze which level on which of three difficulty settings causes players to quit my game?
I have a puzzle game with N stages where each stage has 3 difficulty levels. Users have to finish current unlocked stage to access next stage, but they can access any difficulty level for unlocked stage.

As example, User A played stage 1 with difficulty level EASY, then he changed the difficulty level to HARD and finished stage 2.

I'm using Flurry Analytics to log as above: "stage1\_Completed\_Easy" and "stage2\_Completed\_Hard"

The problem is: there could be more users completed stage N than those who sompleted stage N-1 As example, there are:

* 100 players completed stage1 EASY
* 50 players completed stage1 HARD
* 50 players completed stage2 EASY
* 25 players completed stage2 HARD
* 70 players completed stage2 NORMAL

I'm making assumption that each player only completed each stage once. This means from stage 1 to stage 2, I'm losing 5 players

I want to know which level and what difficulty that makes users stop playing my game

# Answer
I actually do not know what level of liberty Flurry analytics give but you can, for example send and unique user\_id with each event and with that remove people who played more than one level of difficulty or even count how many people retried what level. And with enough processing power you could generate a storyboard based on the events of you player, meaning: first they go to level 1 normal then half goes level 2 normal half goes level 2 hard.

Another solution is to send a counter for each player so you can do the same thing. That counter could increment each time you send a log to flurry. But once again that depends on your back-office
> 2 votes

---
Tags: analytics
---


title: Incrase framerate in XNA

text:
# Question
Title: Incrase framerate in XNA
I'm trying to increase the frame rate of my game from 60FPS to 100 FPS because of reasons. But i can't seem to get it higher than 60 frames. This is the count I'm using. I can slow down the frame rate by setting `TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 16);`

to a higher value, but settings it lower won't increase the frame rate, according to the counter. Anyone have any idea what's going on?

# Answer
> 4 votes
I found I had to do the following to set the FPS limit free. In your `Game` class, do the following:

```
graphics = new GraphicsDeviceManager(this);  // I have this stored as a member variable
graphics.SynchronizeWithVerticalRetrace = false;
IsFixedTimeStep = false;

```

Note that an unlimited FPS can cause unpredictability in physic engines, and network games. A full discussion of fixed vs variable timesteps can be found here: When should I use a fixed or variable time step?

# Answer
> 1 votes
The FPS is capped at 60 because of the default value of `true` on `Game.IsFixedTimeStep`. If you set this value to `false` it should allow your FPS to go to whatever you need it to.

Game.IsFixedTimeStep on MSDN

---
Tags: xna, c#, frame-rate
---


# Question
Title: Collision/Intersection of (2D) Ray to Line Segment
Given a ray (r0, r1) and a line segment (a, b), I need to calculate the normal of the line segment based on the direction of the ray. For example, in the following picture:

The correct normal given the ray (from picture) and segment should be normal n1. Here is the algorithm I am using to calculate the point of intersection:

```
public static Vector2? lineSegmentIntersection(Vector2 r0, Vector2 r1, Vector2 a, Vector2 b)
{
    Vector2 s1, s2;
    s1 = r1 - r0;
    s2 = b - a;

    float s, t;
    s = (-s1.Y * (r0.X - a.X) + s1.X * (r0.Y - a.Y)) / (-s2.X * s1.Y + s1.X * s2.Y);
    t = (s2.X * (r0.Y - a.Y) - s2.Y * (r0.X - a.X)) / (-s2.X * s1.Y + s1.X * s2.Y);

    if (s >= 0 && s <= 1 && t >= 0 && t <= 1)
    {
        // Collision detected
        // Return the point of intersection
        return new Vector2(r0.X + (t * s1.X), r0.Y + (t * s1.Y));
    }

    return null; // No collision
}

```

Ideally, I would like to modify this algorithm to calculate the proper normal. Further, I know how to calculate the normals n0 and n1:

```
norm0 = new Vector2((b.Y - a.Y), -(b.X - a.X));
norm1 = new Vector2(-(b.Y - a.Y), (b.X - a.X));

```

What do I do next to determine which of those two normals to choose? I get the feeling this is fairly simple and I've been looking at it for too long...

# Answer
If assume that your code works properly, the easiest solution is to select correct normal from these two ones.

You can do this just by calculating the dot product of the ray vector and the normal. If the result is negative, than this is the normal you are looking for.

For example:

```
Vector2 ray;
ray = r1 - r0;
float result;
//if result < 0 than the norm0 is the correct normal
result  = ray.X * norm0.X + ray.Y * norm0.Y;

```

You should be aware, that your code have to handle the case of parallel ray and segment. Code, that you've listed will raise an exception of dividing by zero.
> 2 votes

---
Tags: collision-resolution, intersection
---


# Question
Title: Using IPAD's as controllers for a Unity game
We are making a Multiplayer game using Unity. The actual game would be run from a PC projected on a screen and the players would be using their respective Ipad as a controller to play the game. I am not sure how difficult this would be to achieve inside Unity but I am assuming that all the game data inside Unity would need to be fed and retrieved from some kind of a server. How would this be possible with Unity because each Ipad would have a separate Unity build and also a separate build for the PC from where the actual game would be running.

# Answer
> 3 votes
Since Unity can publish games to iOS, this would be just like making any other client server application. The easiest would be to have the iPads all connected to the same network as the host PC, but you could easily utilize the Master Server tools provided with Unity to get everyone connected.

You'd likely use RPCs for most of your communications. As long as the PC build and iOS build defined the same RPCs (which they would if you don't change your code between builds), you wouldn't have a problem with them communicating.

As for how much game data you transfer between the clients and server, it will depend almost entirely on your game and how you've designed it.

---
Tags: unity, multiplayer
---


# Question
Title: Calculate needed speed and object's position in Unity3d
So I'm trying to calculate an object's future position so my enemy can land to it safely. Idea is that using the future position I can calculate the angle and convert it to a direction vector and also using distance I can calculate the speed necessary to reach its target. I'm still kind of stuck with this idea.

Here is code which I'm using at the moment.

```
// Find the close platform to land
Transform _tmp = GetClosestPlatform(SpawnerNew.Platforms);
// Hard coded time, should be time which enemy should take to reach position
float _constNeededTime = 3f;
// As my game's speed always increasing every frame so I need to calculate it also how it's in future (GameManager.Instance.OverAllSpeedModifier is called 10x times / sec)
float _anticipatedLevelSpeed = GameManager.Instance.CurrentLevelSpeed + (GameManager.Instance.OverAllSpeedModifier * _constNeededTime * 10);
// trying to calculate the future postion of the platform
Vector3 _anticipatedLoc = _tmp.transform.position - new Vector3((_platformSpeed * _anticipatedLevelSpeed) + _constNeededTime, 0f, 0f);
// Calculate angle
float _angle = Mathf.Atan2(transform.position.y - _anticipatedLoc.y, transform.position.x - _anticipatedLoc.x) * 180 / Mathf.PI;
// Convert angle to vector direction
_nearestPlatformDir = new Vector3(Mathf.Cos(_angle * Mathf.PI / 180f), Mathf.Sin(_angle * Mathf.PI / 180f), 0);
// Trying to calculate speed needed to reach platform
_neededSpeed = Vector3.Distance(_anticipatedLoc, transform.position) / _constNeededTime;

```

# Answer
> 1 votes
Forget trigonometry. Use vector math. Think of it as solving an equation: you want the position of the platform and the position of the enemy to be the same at some point in the future. So you write the equations of motion for both, and solve for the velocity of the enemy:

```
platform_x = platform_x0 + vel_platform0 * t + accel_platform * t^2 / 2
enemy_x = enemy_x0 + vel_enemyx * t
enemy_y = enemy_y0 + vel_enemyy * t

```

Note that I've written those assuming that the platforms accelerate over time, as you describe in your post. The enemy, by contrast, will move at constant velocity towards the platform.

Now in order to hit the platform, we need the values to be the same for some time T:

```
platform_x(T) = enemy_x(T) =>
platform_x0 + vel_platform0 * T + accel_platform * T^2 / 2 = enemy_x0 + vel_enemyx * T

platform_y(T) = 0 = enemy_y(T) =>
0 = enemy_y0 + vel_enemyy * T

```

Notice that we have three variables to solve for (T, vel\_enemyx, vel\_enemyy) and only two equations. This makes sense, as we can have the enemy move really quickly towards the platform, and hit it earlier, or move more slowly and hit it a bit later.

In your example, you fixed the time T to 3 seconds, so substituting that you can then easily solve vel\_enemyx and vel\_enemyy.

EDIT: Using your variables, code would be something like:

```
float vel_enemyx = 1/_constNeededTime * (_tmp.transform.position.x + GameManager.Instance.CurrentLevelSpeed * _constNeededTime + GameManager.Instance.OverAllSpeedModifier * 10 * _constNeededTime * _constNeededTime / 2 - transform.position.x);
float vel_enemyy = -transform.position.y / _constNeededTime;

```

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


# Question
Title: How do I set a touch listener in a child scene in AndEngine?
In my game, I want to implement touch listener for my child scene objects. Basically I tried all the possible way to implement this that I have usually done for my normal scenes, but those methods do not work here. Could somebody provide some guidance for setting touch area listener in child scene?

Here is my code:

```
    menuScene.setTouchAreaBindingEnabled(true);

    menuScene.registerTouchArea(resumeButtonSprite);
    menuScene.registerTouchArea(retryButtonSprite);
    menuScene.registerTouchArea(exitButtonSprite);

    menuScene.setOnAreaTouchListener(new IOnAreaTouchListener() {

        @Override
        public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
                ITouchArea pTouchArea, float pTouchAreaLocalX,
                float pTouchAreaLocalY) {
            System.out.println("Touch");
            return true;
        }
    });

```

In this code, menuScene was a child scene activity.

Also after research I found that my engine was stopped while the child scene was activated so the touch event is not detected. I want to implement a pause menu in my game so any desirable solution for a pause menu implementation would help.

# Answer
> 2 votes
Are you still having the problem? Try checking out the AndEngine example for the pause menu

```
if(this.mEngine.isRunning()) {
        this.mMainScene.setChildScene(this.mPauseScene, false, true, true);
        this.mEngine.stop();
}
else {
        this.mMainScene.clearChildScene();
        this.mEngine.start();
}

```

The above code should work for a pause menu.

# Answer
> 0 votes
I used

```
engine.getSoundManager().onPause();
parentScene.setIgnoreUpdate(true);

```

and

```
engine.getSoundManager().onResume();
parentScene.setIgnoreUpdate(false);

```

---
Tags: andengine
---


title: Fighting Game Camera Positioning in SDL

text:
# Question
Title: Fighting Game Camera Positioning in SDL
I'm working on a 2D fighting game (using SDL) much like the original Killer Instinct on SNES. I want the camera to keep both players an equal distance from the left and right sides of the viewport. When either player moves, the camera adjusts to keep this equal distance and both players in view, except for when both players are at either end of the stage, during which the camera remains still. Here is an example of how the original KI camera works: http://youtu.be/eFgfaP7f7Rs?t=8m22s

I will provide a diagram of what I am trying to achieve.

The red box is the viewport (camera) which slides over the background image file to display the portion of the stage the players are currently in.

Goal: Each frame the player positions are checked and an algorithm is used to calculate the src.x clipping position for the camera. The midpoint, I believe, in addition with the distance between the players can be used to calculate this value. The viewport width and image width are stored in memory and can also be used. If one player moves, the camera moves at the same velocity, and if both are moving in the same direction, the camera should double its velocity to keep up, all whilst keeping both player's distances from the left and right sides in sync.

Currently, I am using integer math for all positions. I specify the clipping width on the image file using configuration files, so for example, my current background is 768 pixels wide and I clip it to 425 pixels wide, which is displayed in the viewport. The fighters have basic acceleration and max velocity. I use a Camera class to logically represent its x value from 0 to the right edge. The camera's x position is subtracted from the player's x position before rendering. Before rendering the background, I add the camera's x value to the clipping x value (src.x).

I have tried many silly things such as using the ratios of the image and clipping widths to get weird x values. I've tried simply using the midpoint and modifying it with whatever I could think of using the distance, but no luck. I do have semi correct movement by setting the camera x position to the midpoint - (image width - clipping width). However this of course does not keep the players at equal distances.

I've been trying to figure this out for a while and it seems so simple, yet the solution continues to elude me (I'm probably exhausted at the moment). It is possible there are some strange architectural decisions in my code that are making this needlessly difficult. If someone could help me figure out an algorithm, that would be all I need. I can provide more information as needed.

# Answer
This indeed should be very simple, so I suspect you may have gotten some details wrong.

The overall goal is to **match up the center of the camera with the midpoint of the players**. As you've found though, those values aren't immediately available to you, so you need to work them out. What you might have are (leaving out the Y axis stuff since we don't need them):

* The top-left of the camera (let's call it `src.x`)
* The size of the camera view port (call it `src.w`)
    + So the center of the camera is actually `src.x + src.w / 2`
* The player positions (call them `player1.x`, `player2.x`)
    + I'm assuming your player positions are anchored at their midpoint, as this means you don't need to make any adjustments when they turn around (just do a flip). This does mean that when you render them, you need to draw their sprites from `player.x - player.w / 2`.

So altogether, you want this to be true:

```
src.x + src.w / 2 == (player1.x + player2.x) / 2

```

Rearranging for `src.x`, you want to perform the following:

```
src.x = (player1.x + player2.x) / 2 - src.w / 2

```

There are a few more details for a nice fighting game camera:

* Don't let the camera go outside the stage or "world": clamp `src.x` between 0 and `world.w - src.w`.
* You actually want to pan the camera towards the midpoint, rather than setting it to the midpoint immediately, as the code above does. This is so that when your players do teleporting special moves, you don't want the camera to jump around. You can play around with a few methods of movement to see what feels better without being nauseating or obtrusive - constant speed, tweening, panning with acceleration. From the video, it looks like KI is using constant speed, which is perfectly fine.
* What happens if the players want to move further apart than the camera can see? In old-school fighting games they can't move further as scaling didn't work well, but modern 3D fighting games do often support this. Think about whether you want to also have zooming, or even panning vertically as players perform aerial moves.
> 2 votes

---
Tags: camera, algorithm, geometry, sdl, fighting-game
---


# Question
Title: How do I check whether a camera has unobstructed view of a GameObject?
I want to check if a `GameObject` is visible to the camera. The `renderer.isVisible`-method only checks if the camera is turned towards the object, not if there is anything between them (like a wall).

How can I check whether the object is *actually visible*?

# Answer
> 8 votes
As requested, one possible solution (with some flaws) is to use raycasting:

Attaching a (C#) Script similar to this to the `GameObject` from which you want to check visibility would work:

```
if(renderer.isVisible) //Check if Camera is turned towards the GameObject first
{
   RaycastHit hit;
   // Calculate Ray direction
   Vector3 direction = Camera.main.transform.position - transform.position;
   if(Physics.Raycast(transform.position, direction, out hit))
   {
      if(hit.collider.tag != "MainCamera") //hit something else before the camera
      {
         //do something here
      }
   }
}

```

The flaws of this approach:

* Every object that could be in between the GameObject and the Camera has to have a collider attached to it.
* This approach may produce false negatives in the case of partially obstructed objects, as the ray is cast from the center point of your object. If this is a problem in your case, then you may have to work around it (for example, by casting multiple rays from different positions).

# Answer
> 5 votes
Depending on your exact needs, another possible solution would be to do a test render where you set different objects to different colors and then check for that color in the test render.

However this would only be useful in pretty obscure situations; in the majority of situations I would use raycasting. I'm just dropping in this different answer for completeness in considering all your options.

# Answer
> 3 votes
You won't get away on this one with an easy answer. The raycast method is completely flawed. Its the same as calling the object "one pixel" wide and checking if this pixel is visible or not.
Unity uses a precalculated visibility matrix, composed with regular sectors of your world, and a quadratic ray cast test. Which has the same flaws but you don't need to implement anything, Unity has it built in. It takes a while to preprocess, you can even visualize the boxes getting computed and turning from red to white as it goes.

Visibility has been addresses throughout the years using:
\- painting algorithm (draw from back to front)
\- z buffer
\- portals
\- raycast (imperfect)
\- occlusion queries
\- crazy geometry based complex methods
like this one: http://research-srv.microsoft.com/en-us/um/people/johnsny/papers/vissort.pdf

Of course many of the aforemetnioned techniques does not let you know the visibility of one chosen object on the CPU side, but it depends of what you want to do with that information. Mostly its used as a render/not render flag so fed back to rendering. This is why the hardware occlusion queries can be kept on GPU side only and could perform OK in some situations.

The correct geometry based techniques usually resort to some conservative convex hull shape creation, then determine visibility against potential occluders anti-conservative hulls. This is not easy to do, takes a lot of CPU time and usually brings no benefit.

http://www.gamasutra.com/view/feature/131388/rendering\_the\_great\_outdoors\_fast\_.php?print=1

http://bagira.iit.bme.hu/~szecsi/papers/occ.pdf

...

---
Tags: unity, camera, gameobject, line-of-sight, visibility-determination
---


title: How can I inspect 3D model exactness?

text:
# Question
Title: How can I inspect 3D model exactness?
I am neither a game designer nor a graphic designer. I am a .Net and C# software developer. I have a game project and I've still been studying to learn game concepts and technolgies for a year.

I've decided to create a 3D based and networked MMO game with Unity3D. I've planned to hire graphic artists to do my game assets. However, I only know what I want? In other words, I only know concept of 3D models.

What I have to request from graphic artists and how can inspect their work? Do I have to determine some quality criterias or something like this? Same questions are also valid for humanoid and NPC animations.

Thanks

# Answer
There are many points you can check:

* does it load (import) correctly in your Unity
* how many polygons
* how many textures
* how many bones
* how many draw calls does it incur in the engine. in forward mode / and deferred mode.
* is it manifold
* does it create seams while lightmapped
* previous point is linked to secondary UV set unwrapping quality.
* does it have a normal map / specular map / roughness map
* a wrinkle map...
* hit boxes... etc.

A specialized game asset artists will be very good on all these points.

If your question is about how can I interview artists to determine how good they are at each of these points, maybe you should require for a demo asset, from one of your descriptions (concept) that the person could provide as an application entry.

When you make a concept, usually people do a concept art. Which is a bunch of drawings/paintings that takes a day or two to compose, to a profesionnal. If you are a programmer, it will be what one calls "programmer's art" but if you have any expressivity at all it should be enough to convey your intent.
The concept art represents facial view / side views, some material description, accessories list, details emphasis (like "I need scars here").
> 0 votes

---
Tags: unity, 3d, graphics, models, assets
---


title: Using IBO's with color

text:
# Question
Title: Using IBO's with color
I am trying to familiarize myself with IBO's by drawing triangles etc but I'm finding no way to get the color to apply properly. Can I not use an IBO to index the color values as well? I am having another problem with the shapes themselves as I am trying to render two triangles to create a square but the triangles are not aligning properly.

Code:

```
//colors red, blue and green
float[] colors = {    1.0f, 0.0f, 0.0f, 1.0f, //Top color (red)
      0.0f, 1.0f, 0.0f, 1.0f, //Bottom Left color (black)
      0.0f, 0.0f, 1.0f, 0.9f
};

//the vertices I need to render a cube.
float[] dataBuffer = {-1,1,-1, //1
      -1,-1,-1,//2
      1,-1,-1,//3
      1, 1,-1,//4
      -1, 1,1,//5
      -1,-1, 1,//6
      1,-1,1,//7
      1,1,1//8
};

//int[] idxBuffer = {1,2,3,3,4,1,5,6,7,5,8,7,5,1,8,4,1,8,6,2,7,3,2,7,5,6,2,1,5,2,8,7,3,4,8,3};

//indexes for two triangles to create a square (result looks like roof of a house...)
int[] idxBuffer = {3,1,2,3,1,4};
//idx's for colors that I want to apply to each vertex in idxBuffer.
int[] idxColorBuffer = {1,2,3,1,2,3};

//*****************THE INITIALIZE ROUTINE ****************
 vboHandles = new int[4];
  gl.glGenBuffers(4, vboHandles, 0);

  //populate the position buffer
  FloatBuffer fbData = Buffers.newDirectFloatBuffer(dataBuffer);
  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[VERTICES_IDX]); //the vertex data
  gl.glBufferData(GL4.GL_ARRAY_BUFFER, fbData.capacity() * 4,
          fbData, GL4.GL_STATIC_DRAW);

   //populate the color buffer
  FloatBuffer fbColors = Buffers.newDirectFloatBuffer(colors);
  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[COLOR_IDX]);
  gl.glBufferData(GL4.GL_ARRAY_BUFFER, fbColors.capacity() * 4,
          fbColors, GL4.GL_STATIC_DRAW);

  //index buffer IBO Vertex
  IntBuffer dtaIndc = Buffers.newDirectIntBuffer(idxBuffer);
  gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, vboHandles[2]); //bind the indices
  gl.glBufferData(GL4.GL_ELEMENT_ARRAY_BUFFER, dtaIndc.capacity() * (Integer.SIZE / Byte.SIZE), dtaIndc, GL4.GL_STATIC_DRAW);

  //index buffer IBO Colours (not sure if this is how it's done??)
  IntBuffer colorIndc = Buffers.newDirectIntBuffer(idxColorBuffer);
  gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, vboHandles[3]);
  gl.glBufferData(GL4.GL_ELEMENT_ARRAY_BUFFER, colorIndc.capacity() * (Integer.SIZE / Byte.SIZE), colorIndc, GL4.GL_STATIC_DRAW);

  //set vertex array index
  IntBuffer intBuffer = BufferUtil.newIntBuffer(1);
  gl.glGenVertexArrays(1, intBuffer);
  iVao = intBuffer.get(0);
  gl.glBindVertexArray(iVao);

  gl.glEnableVertexAttribArray(0);
  gl.glEnableVertexAttribArray(1);

  // Select the VBO, GPU memory data, to use for colors
  gl.glBindBuffer(GL2ES2.GL_ARRAY_BUFFER, vboHandles[COLOR_IDX]);
  gl.glVertexAttribPointer(COLOR_IDX, 3, GL4.GL_FLOAT, false, 0, 0);

  gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboHandles[VERTICES_IDX]); //the vertex data
  // Associate Vertex attribute 1 with the last bound VBO
  gl.glVertexAttribPointer(VERTICES_IDX,4, GL2ES2.GL_FLOAT, false, 0,0);

  //use VERTICES_IDX to bind the element array to the vertex buffer.
  //this seems to sort of work...
  gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, vboHandles[2]);
  gl.glVertexAttribPointer(VERTICES_IDX, 4, GL4.GL_INT, false, 0, 0);

  //this I was hoping would bind the indexed colors but I get nothing...
/*    gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, vboHandles[3]);
  //use COLOR_IDX to bind the element array to the vertex buffer.
  gl.glVertexAttribPointer(COLOR_IDX, 1, GL4.GL_INT, false, 0, 0);*/

//*********************THE DISPLAY ROUTINE*********************
//transform matrices to shaders etc...
//then...
//draw 2 triangles (6 vertices).
gl.glBindVertexArray(iVao);
//gl.glDrawArrays(GL4.GL_TRIANGLES, 0, dataBuffer.length / 3);

//draws two triangles that look like the roof of a house and colors
//them both red...should draw two triangles that look like a square
//and colors them varying shades of red, green, blue.
gl.glDrawElements(
                 GL4.GL_TRIANGLES,      // mode
                 idxBuffer.length,    // count
                 GL4.GL_UNSIGNED_INT,   // type
                 0           // element array buffer offset
);

```

Also, there is one parameter that confuses me in particular. In glVertexAttribPointer, the second param 'size' in the spec it states "Specifies the number of components per generic vertex attribute. Must be 1, 2, 3, or 4. The initial value is 4." Is this not a setting for the number of components for a vertex which would be 3 (in my case anyway - I know there is a w)? Why is it in the following line that it must be 4?

```
gl.glVertexAttribPointer(VERTICES_IDX,4, GL2ES2.GL_FLOAT, false, 0,0);

```

# Answer
> 1 votes
The positions and color (and all other vertex attributes) *all use the same index buffer*, there is **no way to change that**. So if you have an index `X` then that vertex will have the position at index `X` and the color at index `X`.

The size parameter indicates how many values to take (1 to 4). Sometimes positions are stored in the homogenic format (essentially add another dimension which is always 1 for positions and 0 for directions). This helps with matrix transforms.

For your colors attribute that should be 4 because you also pass in the alpha channel. But for your vertex that should indeed be 3.

---
Tags: opengl, java, vbo
---


# Question
Title: OBJ Model not being rendered properly in OpenGL ES 2 android app
I have an Android OpenGL ES 2 app that loads an **.OBJ** model using **Assimp** and renders the same.

The vertices data is stored in a object declared like this :

```
class CGameObject
{
public:
struct _Mesh {
    std::string Name;               // Name of Mesh

    std::vector<float> vertices;    // vertices of Mesh

    GLuint m_vbo;
    // TODO: Add TEXTURE and MATERIAL support
};
...
}

```

Set various Matrices :

```
cameraX = 3.0f; cameraY = 3.0f; cameraZ = 5.0f;

// Camera/View matrix
View = glm::lookAt(
    glm::vec3(cameraX, cameraY, cameraZ),     // Camera position
    glm::vec3(0, 0, 0),     // Pointing at
    glm::vec3(0, 1, 0)      // Angle
 );

aspect = (float) width / height;

// Projection Matrix
Projection = glm::perspective(45.0f, aspect, 0.1f, 10000.0f);

glm::mat4 Model = glm::translate(mat4(1.0), glm::vec3(0.0f, 0.0f, 0.0f));
MVP = Projection * View * Model;

```

Rendering function :

```
void GLEngine::DrawFrame() {
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

glUseProgram(programObject);
// Draw of VBO ---BEGIN
for (GameObjects::iterator i = gObjects.begin(); i != gObjects.end(); ++i)
{
    CGameObject* pObj = *i;
    /////////////////
    for (int x = 0; x < pObj->Meshes.size(); x++)
    {
        glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);
        // bind VBO you want to draw
        glBindBuffer(GL_ARRAY_BUFFER, pObj->Meshes[x]->m_vbo);

        glEnableVertexAttribArray(gvPositionHandle);
        glVertexAttribPointer(gvPositionHandle, 3, GL_FLOAT, GL_FALSE, 0, 0);

        if (x == 0){
            glVertexAttrib3f(gvColorHandle, 0.0f, 0.0f, 1.0f);
            UcheckGLError("glVertexAttrib3f");

            }
        else {
            glVertexAttrib3f(gvColorHandle, 0.0f, 1.0f, 0.0f);
            UcheckGLError("glVertexAttrib3f");

            }

        //glEnableVertexAttribArray(gvColorHandle); // My app crashes if I uncomment this line . .. any reasons why ?
        //UcheckGLError("glEnableVertexAttribArray");

        glDrawArrays(GL_TRIANGLES, 0, pObj->Meshes[x]->vertices.size());
        // unbind VBO
        glBindBuffer(GL_ARRAY_BUFFER, 0);
    }
    /////////////////
}
// Draw of VBO ---END
// unbind program
glUseProgram(0);
}

```

source for shaders -

vertex shader :

```
attribute vec3 in_Position;

uniform mat4 MVP;

attribute vec3 in_Color;
varying vec4 fColor;

void main(void) {
    vec4 v = vec4(in_Position, 1.0);
    gl_Position = MVP * v;
    fColor = vec4(in_Color, 1.0);

}

```

Fragment shader :

```
varying vec4 fColor;

void main() {
    //gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
    gl_FragColor = fColor;
}

```

But the results is not what I expect. Expected :

What I get :

Loading of the Assimp model is provided in this question : https://gamedev.stackexchange.com/questions/85808/problem-rendering-simple-obj-model-using-assimp-in-android-app

# Answer
you problem is with the following call:

```
glDrawArrays(GL_TRIANGLES, 0, pObj->Meshes[x]->vertices.size());

```

you need to pass in the amount of vertices you are drawing aka `pObj->Meshes[x]->vertices.size() / 3`
> 1 votes

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


# Question
Title: Why should I use a list of enemies instead of an array of enemies?
I have been making 2d shooter similar to galaga using xna in C#, where the enemies (2 types) are all in rows above the player's ships, and are supposed to randomly launch attacks. I had previously implemented part of this game using an array to generate the rows of enemies and testing to make sure the other game mechanics worked before implementing the enemy movement system and ai. I was told later that I should use a list instead of an array to generate the rows of enemies. What advantage is there to using a list over using an array?

# Answer
First of all please read Array versus List: When to use which? for coverage of this issue from a general perspective.

Now to focus on your case, I would recommend a list if:

1. You don't know how many enemies you will have in advance (and don't want to worry about handling resizing)
2. You would like to remove enemies from the middle (and don't want to worry about handling fragmentation)

In practice I find that `List<T>` provides an powerful and efficient implementation that takes care of house keeping and edge cases while allowing a developer to focus on game logic.

---

There are a differences in usage, mostly changes I consider improvements as they enable a more powerful API.

Here are some usage samples:

```
using System.Collections.Generic;

Item item = new Item();
int index = 0;

//initialise new list
List<Item> list = new List<Item>();

//add item to last position
list.Add(item);

//retrieve item from indexed postion
item = list[index];

//replace item at indexed postion
list[index] = item;

//remove first occurance of item
list.Remove(item);

//remove item from indexed position
list.RemoveAt(index);

//remove all occurenece of item
list.RemoveAll(o => o.Equals(item));

//get count of items in list
int count = list.Count;

//iterate through list
foreach (Item item in list) {
    // do work on item
}

```
> 5 votes

# Answer
The problem with arrays is that they can not resize dynamically. When you exceed the initial capacity, you need to allocate a new array and copy the whole array over. When you want to remove an entry in the middle, you need to move all entries after it down by one. These are both very expensive operations when your array is large.

The List class is an object-oriented wrapper around an array. The API pretends that adding and removing entries is no big deal, but that's not the case. The internal implementation does exactly that. `Add` calls `EnsureCapacity` which calls the setter for `Capacity` which then does

```
T[] newItems = new T[value];
if (_size > 0) {
      Array.Copy(_items, 0, newItems, 0, _size);
}

```

When you need

1. fast dynamic growth when adding items
2. fast dynamic shrinking when removing items
3. fast iteration from start to end but you don't need access by index

the data structure you should be using is a LinkedList. For more details about the performance characteristics of List vs. LinkedList see Drew Noakes answer to "When should I use a List vs a LinkedList" on stackoverflow.

When you need both access by index and want dynamic growth and shrinking, you could use a Dictionary with the index numbers as key.
> 1 votes

---
Tags: xna, c#, ai, spawning
---


# Question
Title: How to render the sprites for a 2D soft body physics system
This is not a question as to how to achieve soft body physics, but rather if I have a mass-spring system how to modify a sprite with that information. I am using unity so I dont have access to vector based graphics.

# Answer
> 1 votes
If you have a convex shape then what you can do is perform a convex hull operation to get a list of vertices that define the edge. Now find the average position of these points to define the center.

If you already have a list of edge vertices then you can ofcourse skip that step.

These edge points and the center can be used to define triangles as is common in a triangle fan. i.e. the triangles are defined as (center, i, (i + 1) % nEdgeVerts) where i is an index pointing to the next edge vertex. Basically, it's like slicing a pizza.

This needs to be textured, so you will have to set UV values for the vertices. The easiest way I can think to do this is to first set the center point with the uv of (0.5, 0.5). Then find the coordinate of each edge vertex relative to the center. Find the largest value of x and y and scale all coordinates by these values. This will give you X and Y coordinates in the range -1 to 1. All that's left is to do is shift this into the texture UV range, so add 1 and divide by 2.

So roughly;

do for each edge vertex;

```
  relativePos = edgePos - centerPos;
  if (relativePos.X > largestX) largestX = relativePos.X;
  if (relativePos.Y > largestY) largestY = relativePos.Y;

```

then calculate the UV for each vertex using;

```
  uvCoord.X = ((relativePos.X / largestX) + 1) / 2;
  uvCoord.Y = ((relativePos.Y / largestY) + 1) / 2;

```

Now this will work for soft bodies which start as fairly regular shapes like cicles, rectangles etc. And if the UVs remain fixed, i.e. calculate once when the shape is first created, you should actually see the texture bend and stretch with the body.

For more complex convex shapes the UV algorithm above might not be a good fit and you'll have to try some other way, even just presetting the UVs somewhere.

For concave shapes, like a half moon, you will need to do decompose it into multiple convex shapes. See here and here.

---
Tags: unity, sprites, soft-body-dynamics
---


# Question
Title: Implement an action "while" touching event
I'm making a game using Xcode for iOS. This is a segment of code I have that makes the sprite jump up when the screen is tapped:

```
//tap/touch to jump (& play sound)
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event{
       [self playSound];
       jumpUp = 16;
}

```

It's pretty simple to achieve that, but how can I implement it so that the sprite just keeps going up whist you are touching the screen instead of just a single tap?

```
//Simple pseudo code:
while touchingScreen Event {
    jumpUp +=1;
}

```

# Answer
> 1 votes
One possible solution is to use `(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;` for while the played is jumping, and `(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;` for when player stops jumping.

Another solution would be to set the player's state to "jumping" when `touchesBegan`, then during each loop of the game code preform the appropriate movement. Then when `touchesEnded` happens, switch the player's state to something else.

---
Tags: game-mechanics, touch, gestures
---


# Question
Title: How should loot be distributed across dungeon levels?
I am making a dungeon crawler; as the player character adventures down through increasingly difficult floors of a dungeon, they collect more valuable treasure.

**What is a good algorithm to determine the distribution of treasure?** Should each potential item be given a range from one to a million and then be rolled for, or should multiple dice with special value be rolled and an item constituted that way?

For this example there can be an infinitely varied assortment of randomly generated items.

# Answer
These are the three approaches that I would take:

# Loot tables:

Build a table for each zone and sub-area. Loot table should be approximately close to the theme and difficulty level of the enemies, I.e. if it is intro level and mobs can range from level 1-3, then so should the loot. You can make different loot drop tables for specific sub-areas as well. If you have a dungeon and a small area specifically where the orks hang out, then your loot table for that sub area may have items specific to orks, i.e. "ork swords, or ork shields"

If you are editing a level or automatically generating it then the loot tables should be generated the same way your terrain/mobs are. Your loot should be proportional to the difficulty of the dungeon level (or the mobs for that level).

For game balance you should take into account risk/reward. Boss gear should be given when fighting tougher enemies. Otherwise you risk getting the best gear from simple mobs and removing the fun element from your dungeon.

Here would be an example of a loot table

Zone 1 loot table:

* Item,Difficulty,Chance
* Regular Orc Shield, 1-3, 20%
* Regular Orc Sword, 1-3, 20%
* Some gold (5-10gp), 1-3, 80%
* {Awesome sword -or- Awesome Shield}, 5, 20%

Manually generated games use these, so for example if you want to scavenge a particular area for ingridients or craftings parts, the loot table for that area would contain particular parts (i.e finding food in jungle areas, finding electronics in junk yard) etc.

# Standard Deviation:

Some games use standard deviation for loot drops. For example the more common the item, the close it is to the average. The more exotic items the further it is from the average and closer to the sides of the curve. This can be used with loot tables, or it can be used for the overall game. If you are making a space shooter and the only things that can be dropped are power ups and parts, then you don't need a loot table, you can just use the standard deviation and define the probability threshold for the items.

Example:

* Health (Common), .5
* Ammo (Common), .5
* Cool gun (Uncommon), .7
* Super gun (Rare), .9

The common items, statistically, should drop more often then the rare ones.

# Pure Random

I would actually use this method when starting to make the game because it is the easiest to implement. You do not want to optimize your game when you are still making it, you can always worry about balance and mechanics a bit later in your development cycle. Also having random drops may seem amusing and might also give you ideas during play testing. For example having super loot drop when you are in the tutorial may give you some ideas to create some quest named "Holy Quest to get Super Loot". I.e. it is good for brainstorming.
> 6 votes

# Answer
I would suggest that in addition to using random numbers, it would be more interesting and logical, and good for play balance and sense of immersion, if the loot were related to the nature of the place and what else is there. Not just how deep into the dungeon it is, but what is the nature of each part of each dungeon level.

Whether pre-designed or randomly generated, each room or passage or section of a dungeon level can have a type, which can influence how it is laid out, what is there, what it looks like, and what creatures and objects (loot) will tend to be there.

As I particularly like things to make sense, I would think about what loot would make sense to go in what area and with what opponents, and if the loot is useful gear that the opponents can use, equip them with it so they can use it against the players. It always seems pretty fake to me when there is, say, a warrior standing around next to some great weapons, or a wizard hanging around some magic equipment, which are just prizes for the player and not being used by the opponents who were there first.

So, your algorithm could be like:

1. Determine what each section of each level is like, based on a semi-random selection of odds for each type of section to appear on each level depth, and also based on what sections are adjacent to it, so the layout will make more sense than being completely random.
2. For each section, now that we know the type, generate features and place pseudo-random monsters appropriate to that type of place.
3. For each monster, add pseudo-random gear that that monster can use but could also be looted, and a much smaller chance of them just having random stuff they can't use themselves. Also check the monsters against the other monster types to see if they make sense to be hanging out together, or if one would have fled or been killed by another.
4. Add other logical loot for the place type, in logical places. Maybe check against each monster in that region to see whether it is something they would have pocketed before the player shows up, or not.
> 3 votes

# Answer
> or should multiple dice with special value be rolled and then an item constituted that way

Why would this be better? The player would not see the "dice", the first example is as much a "dice" as the second.

I think you need to make all the items you want and consider their relative usefulness before starting to think about their distribution.

Also, I think it's really boring when you beat a rat and for some reason it drops something incongruous like a sword. It's a rat, why would it be carrying around a sword? Where did it keep it? I like it way better when monsters/chests drop things you'd expect them to drop. It sounds to me like you want a Diablo like loot system. In that case you'd do well to read up on these FAQs describing the drop mechanics.
> 2 votes

# Answer
This is how I ended up doing it (based on Diablo II):

## Loot Tables

Each enemy that is killed has a certain enemy class. For example, a regular melee lvl 20 character's code might be MA-20, and an elite melee of the same level would be MC-20.

Every code is paired to a "loot" table containing any number of fields. Each field has a reward and a probability.

### Loot Table for MA-20

```
item - probability
gold - 20
nothing - 80
weapons.simpleDagger - 5
MC-20 - 1

```

To determine the loot dropped, each possible reward is assigned a range based on its probability, and then a random number is rolled. In this case, the random number is 106.

```
gold - 20 - awarded on 0-20
nothing - 80 - awarded on 21-100
weapons.simpleDagger - 5 - awarded on 101-105
MC-20 - 1 - awarded on 106

```

Each slot can either be gold, nothing, an item, or point to another table. If the roll lands on an item, the enemy drops that item. If it lands on another table, then that table is then rolled for, continuing indefinitely until an item is drawn.
> 0 votes

---
Tags: rpg, balance, content-generation
---


# Question
Title: Are web browser games like Travian/Tribal Wars based on asynchronous responses?
I'm coding in Python. Currently, with some group of people, we are making a decision about server-side language choice for our web-browser-based strategy game. I have some questions:

1. Are games like Travian based on asynchronous requests or it's all normal synchronous?
2. WSGI for Python web apps is synchronous. Does it mean only one request is processed in the moment? If I have 10000 requests, I must wait for each one?
3. For this type of game, requests based on RESTful or GET/POST methods are most suitable? No need of sockets (I hope so)?

# Answer
**Pre-rant answer:**

There are only two technical reasons to require asynchronous requests, and neither of them applies to a game like Travian because real-time updates are not required.

1. You need to make instant updates to the client, so you need to initiate communication from the server. Before websockets, this could be accomplished with long-polling (keeping a request open long after it was initiated), and submitting additional response content as soon as it became available.
2. You need to answer or receive requests that take a long time because of total size and bandwidth, but still need to accept and work on new requests during that time.

These reason don't apply to Travian-likes because:

1. You don't need instant updates. Timed resources can tick continuously on the client-side, but the server always should validate them based on `previous_value + rate * elapsed_time`. That update can happen whenever a user refreshes their page or attempts an action; no real-time push is required. Even if you need regular updates, they can occur through a simple polling mechanism (without keeping connections open).
2. Your requests should not (and can not) be that large. This requirement would cripple *any* game server with a large number of users. Even Youtube delivers video via so-called "pseudo-streaming", delivering only the bit of content you need when you need it, which can be accomplished with separate requests to the server.

If you believe you can get away with RESTful or any other stateless communication (and indeed you can), then you do not require an asynchronous server architecture. You should select a server based on its ability to process the game state quickly, and possibly the ease of increasing that capacity on-demand. Concurrent connection count is mostly irrelevant.

---

It sounds like you are falling for the term "asynchronous" as a buzzword. I call it a buzzword because non-blocking requests have no benefit on a server that is *busy doing work* to answer the requests. Asynchronous requests only offer one "advantage", which is to allow the dog-piling of more incoming requests (that still take unacceptably long to receive a response). The single reason to require asychronous requests is if you expect your requests to take a long time to complete.

Asynchronous server systems increase the maximum number of concurrent connections. That is completely irrelevant if you prefer to use stateless (RESTful) requests. For example, the largest number of twitter posts per second, *EVER*, was about 6000. Will your game community need to make more requests per second than that? Some quick math will allow you to disprove that notion. *Half* that rate would be 260 million requests per day.
> 1 votes

# Answer
1. Most browser-based games are going to use asynchronous communication. You might want to read what the difference between the two actually are. The biggest thing to note here is that typically synchronous communication will block until a response is received. Meaning if I fire off a request for high-score data from the same thread that does the rendering, my game will appear to freeze until I get the response. On the other hand, if I use an asynchronous model, then I can fire off the request, and handle the response if/when I ever get it.
2. You are correct. WSGI is synchronous which means that each request must be processed in order before the next request can be processed. Typically this means that the calling thread is blocked until the request has finished processing, which for something that must stay responsive can be a huge deal.
3. You can use either one, really the biggest difference here is personal preference and availability of one or the other in a preferred framework. Personally I've used both in varying projects, and found no significant difference in either one. Typically the biggest deciding factor here is finding technologies that play well together.

Also since you mentioned it, based off this data I would have to say that browser-based games are better off shying away from web sockets for now. It says that 20% of all people don't have browsers that support it. However in 5-10 years where the majority of browsers support it, websockets might be the thing to go to.
> 0 votes

---
Tags: browser-based-games
---


# Question
Title: "_SRGB" suffix for BC texture format doesn't result in sRGB-to-linear correction at sampling
I am working on a 3D engine as a hobby (**Direct3D 11**). Currently I am trying to implement sRGB -\> linear -\> sRGB color space conversions via texture formats with "**\_SRGB**" suffix. So, my textures are supposed to be sRGB images (for example, DDS-files compressed in **BC1\_UNORM\_SRGB** format), output is also gamma-corrected (thanks to **R8G8B8A8\_UNORM\_SRGB** frame buffer) and all shader calculations are made in linear color space.

The problem is, whether I use sRGB or non-sRGB format for the DDS-file, after sampling the texture I get exactly the same color values inside the shader that are stored in original image. But if I get it correctly, sampler should apply implicit gamma correction `(pow(color, 2.2f))` for the input values. So, for example, if I want to output the same color as is in the map (lets say, **0.5f** for **R** channel), I sample it from the texture (**0.5f** becomes **0.218f** after transferring to linear color space by sampler), then I do nothing with it inside the shader and send to output. As the frame buffer has sRGB format, merger (or some other part of pipeline, that does it) will apply gamma re-correction to our value `(pow(color, 1.0f / 2.2f))`, and **0.218f** will become **0.5f** again. I will get the same image as I had on the input.

The output colors are definitely gamma corrected, as I see clear difference when I change frame buffer format from sRGB to non-sRGB. But as no input correction is applied, the final image looks brightened comparing to the input one. As I said, I checked the value in pixel shader after `texture.Sample()` call, and it is exactly the same as colorpicker shows for the source texture. When I swap the texture format to non-sRGB, nothing changes (I use **Visual Studio 2013 Update 4** for format changing).

To load DDS files I use DDSTextureLoader. I also called Direct3D methods directly to create resource and view from the file, but nothing changed. Both resource and shader resource view have "\_SRGB" format, as I can see in Graphics Debugger, so they are definitely sRGB ones.

I've read at MSDN that in **Direct3D 11** setting texture format is enough for sampler to recognize sRGB image. Is there something I am doing wrong or missing, or understand incorrectly? Maybe someone had similar issues? Any advice would be highly appreciated!

# Answer
I'm not using `DDSTextureLoader()` functions myself, but it seems that the function creates appropriate shader resource view for you to match the DDS format and the associated sRGB space, thus you get about the same linearized result in the shader regardless if you use sRGB format in your DDS file or not. You could create your own SRV instead with fixed sRGB setting and use that to see the difference.

Just to clarify, you DO get sRGB-to-linear correction at sampling. If you store texture in linear space and use linear sampler you get the same result as storing the texture in sRGB space and using sRGB sampling (barring the precision differences).
> 0 votes

---
Tags: textures, hlsl, directx11, dds
---