title: GLSL 2d Per Pixel Lighting

text:
# Question
Title: GLSL 2d Per Pixel Lighting
First time writing shaders, and having a bit of an issue getting per-pixel lighting to work. The problem is pretty simple, but I'm afraid am doing something wrong here.

Vertex Shader:

```
#version 150

uniform mat4 proj;      // ortho projection matrix
uniform mat4 world;     // world transformation (usually only rotation)

in vec2 pos;            // position for this vertex

out vec2 ex_pos;        // pass position to frag shader

void main()
{
    gl_Position = proj * world * vec4(pos, 0.0, 1.0);
    ex_pos = pos;
}

```

Fragment Shader:

```
#version 150

uniform vec2  light_pos;        // light position
uniform vec3  light_color;      // light color
uniform vec3  intensity;        // intensity value to apply to the light
uniform float attenuation_c;    // constant attenuation
uniform float attenuation_l;    // linear attenuation
uniform float attenuation_q;    // quadratic attenuation

in vec2 ex_pos;     // interpolated position

out vec4 frag;      // final fragment color value

void main()
{
    // compute the current distance from light
    float d = distance(light_pos, ex_pos);

    // compute attenuation for this point
    vec3 frag_intensity = intensity / (attenuation_c + attenuation_l*d + attenuation_q*pow(d,2) );

    // blend mode is additive
    frag = vec4(frag_intensity * light_color, 1.0);
}

```

So, this seems pretty straightforward, but I am getting a hopelessly dark polygon (i.e., the additive fragment color always ends up 0,0,0). I have tested that simply setting d to any positive value causes the entire light polygon area to be uniformly lit, so I'm thinking that my distance computation is just wrong, but I'm not sure how it could be. I did have this working a bit earlier by doing vertex lighting instead of fragment, so I'm pretty sure my uniforms are being set correctly.

Is it the interpolated position that is causing a problem?

Thanks for any help.

# Answer
So, I just messed around with the attenuation values I was providing and managed to get the lighting to work. It turns out the vertex lighting version was working because the light intensity at the point of the light was always near base value of the light, and the triangle fan far vertices were always zero, causing a linear light blend from the center out, which made it look mostly correct.
> 1 votes

---
Tags: shaders, glsl
---


# Question
Title: How do I rotate a camera around the Y axis of the object it's looking at?
I'm making a camera that can currently rotate freely from the back to the front of a target object by giving it an angle and a distance.

I do the above with the following code

```
directionVector = new Vector3(0, Mathf.Sin (angle*Mathf.Deg2Rad), Mathf.Cos(Mathf.Deg2Rad * angle));
normalizedDirectionVector = (directionVector).normalized;

transform.position = (normalizedDirectionVector*cameraDistance) + target.transform.position;

```

In the above I take the direction from the angle, normalize it and then add it to the target position. And the camera sets nicely to the wanted angle. But how can I add the sideways movement(x-component) so that I could move the camera freely around the target?

# Answer
> 0 votes
I solved this by using the original angle vector and then using the equation that @nykwil provided, but only using the pitch component. Then I combined the y-component of the angle vector to the pitch and I got the result I wanted.

# Answer
> 1 votes
Google Euler angle conversion for more info. To get a direction vector from a pitch and a yaw (pitch is what you have now and yaw is around the vertical axis) you want this:

```
x = cos(yaw)*cos(pitch)
y = sin(yaw)*cos(pitch)
z = sin(pitch)

```

# Answer
> 1 votes
The manpage for gluLookAt might be of use. That is deprecated now days in OpenGL itself, but glm has an implementation. Then you just use that plus basic trigonometry for working out the X/Y coordinates of the camera.

# Answer
> 1 votes
You could use engine features to avoid trigonometry entirely. Another way to achieve this is to do the following steps:

1. Set the camera's position equal to the target position.
2. Rotate the camera such that it points in the direction you want.
3. Add the desired displacement to the **local translation** of the camera. This will automatically move the camera away from the target. (Note: depending on the axes you are using, this might mean adding `<0, 0, orbitRadius>` or `<0, 0, -orbitRadius>`.)

It looks like you're using Unity, which has the tools to make this extremely simple.

---
Tags: mathematics, camera, vector
---


title: Unrealscript splitting a string

text:
# Question
Title: Unrealscript splitting a string
Note, this is repost from stackoverflow - I have only just discovered this site :)

I need to split a string in Unrealscript, in the same way that Java's split function works.

For instance - return the string "foo" as an array of char.

I have tried to use the SplitString function:

> array SplitString( string Source, optional string Delimiter=",", optional bool bCullEmpty ) Wrapper for splitting a string into an array of strings using a single expression.

as found at http://udn.epicgames.com/Three/UnrealScriptFunctions.html but it returns the entire String.

```
simulated function wordDraw() {

local String inputString;
inputString = "trolls";
local string whatwillitbe;
local int b;
local int x;
local array<String> letterArray;

letterArray = SplitString(inputString,, false);
for (x = 0; x < letterArray.Length; x++)
{
        whatwillitbe = letterArray[x];
        `log('it will be '@whatwillitbe);
        b = letterarray.Length;
        `log('letterarray length is '@b);
        `log('letter number '@x);
}

```

}

Output is:

b returns:

> 1

whatwillitbe returns:

> `trolls`

However I would like b to return 6 and whatwillitbe to return each character individually.

I have had a few answers proposed, however, I would still like to properly understand how the **SplitString** function works. For instance, if the Delimiter parameter is optional, what does the function use as a delimiter by default?

# Answer
> 1 votes
The default delimiter is ',' see http://udn.epicgames.com/Three/StringsInUnrealScript.html

For your problem you could use Mid() to generate your array by hand.

> ```
> string Mid ( coerce string S, int i, optional int j )
>
> ```
>
> The Mid() function generates a substring of S by starting at character i and copying j characters. If j is omitted, the rest of the string is copied. i is clamped between 0 and the length of the string. j is clamped between i and the length of the string. If S is not a string, its value will attempt to be converted to a string value.

You want to loop from 0 to the string length and generate substrings of length = 1 . Pseudocode:

```
for (i = 0; i < inputString.Length; i++)
{
  letterArray[i]=Mid(inputString,i,1);
}

```

---
Tags: udk
---


title: Mouse Cursor Scaleform 4 / AS3

text:
# Question
Title: Mouse Cursor Scaleform 4 / AS3
I just solved my issue

in my object (on the stage) I forgot to name the element

---

I'm trying to make workin a custom mouse cursor on my Scaleform menu. I have follow some tutorials but nothing good...

Right now I have tried the Matt Doyle's AS :

```
import scaleform.gfx.Extensions;
Extensions.enabled = true;

Mouse.hide();
var mCursor:MovieClip;
mCursor.mouseEnabled = false;
mCursor.tabEnabled = false;

function handleMouseMove( e:MouseEvent ):void
{
    mCursor.x = e.stageX;
    mCursor.y = e.stageY;
}

stage.addEventListener( MouseEvent.MOUSE_MOVE, handleMouseMove, false, 0, true );

```

but i'm little confused on how declare the cursor should I add it on the stage, or can I use some `addChild()` to have it on the screen

for information `mCursor` is also the name of the cursor movieClip in my library

# Answer
> -1 votes
I just solved my issue

in my object (on the stage) I forgot to name the element

---
Tags: actionscript-3, udk, interface
---


# Question
Title: What's the name for the random animations played when character isn't doing anything else?
In many games, the main characters or enemies usually do some random stuff when idle other than just standing there breathing. For example, they may take a nap or eat some food.

These add nothing to gameplay, but help develop some personality for the characters. I can't find a word to describe them; do these animations have a standard name in the industry?

# Answer
> 7 votes
"Idle action" or "idle animation." I don't think there's really standard, but those are very common terms.

However, it seems like some games/animation frameworks, like the one used by StarCraft 2, differentiate between commonly played animations ("idle animation") and less common animations only played from time to time ("fidget animation"). In the end it still really depends on your actual system and implementation, whether there is indeed one common animation or just lots of variations played at random (or one after the other).

---
Tags: character
---


title: Make colour change depending on time

text:
# Question
Title: Make colour change depending on time
I'm making a Flash game (ActionScript 3) and for dynamics I'd like to make the background change colour depending on the clients' time of day.

I have a rough idea on how I want to do this,

At sunrise, I want the background to be yellow-orange In the middle of the day, I want the background to be cyan/clear sky colour At sunset, a reddish-orange During the night, a navy blue.

I will be using this method to change the colour of the symbol, which is at default a dark grey colour. (unless someone points out a better way to do this). This means I have access to the red, blue and green components of the background.

On implementing the system itself; I suppose I could simply get the client time and do

```
if (hour > 9) and (hour < 18)
{
    colour = SKY_BLUE
}

```

and similar for the other times of day, but I'd like it to tween slowly between colours as time progresses. For example, if 6AM is yellow-orange and 9AM is blue, 7:30AM would be yellow moving towards blue. I have a feeling I need to come up with an algorithm to link time to the RGB components of the colour, but I've always been terrible at maths and I can't think of how to do this, so that's why I'm asking.

Please tell me how I would do this, both concept outlining and sample code, or even just tips are welcome. :)

# Answer
Reference Link for Date Time Functions http://help.adobe.com/en\_US/FlashPlatform/reference/actionscript/3/Date.html

Using the getHours() & getMinutes function you can decide the change in the color.

The Color Transform code which you have mentioned is pretty good to carry the color operation.
> 1 votes

---
Tags: flash, actionscript-3, color
---


title: rotating 3D object around the center

text:
# Question
Title: rotating 3D object around the center
I have object moving from A to B on x-axis and there is no translation of object apart from it. Now, while moving, i want to rotate it around y-axis and the motion should change accordingly, i mean if i rotate it right when moving from -x to +x axis, it should move towards near plane. I have variable in gltranslatef which is modified in the loop after that i have glscalef to scale whole object which is made of hierarchical structure. Now i tried following code to achieve the expected result but its not working properly

```
   glTranslatef(move, 0, 0);

// If I comment these 3 lines, it does not affect the output
     glTranslatef(-move, 0, 0);
glRotatef(rotate,0,1,0);
glTranslatef(move, 0, 0);

glScalef(0.2, 0.2, 1.0);

```

# Answer
Transformations (scale,rotation, translation) are applied in the reverse order of their invocation and transformations do not change the object's position or orientation but the coordinates system that will be used to render it. Imagine the 3D coordinates system as 3 axis ( X,Y,Z ) perpendicular to each other. In case your object lies along the X axis, if you rotate the coordinates around the Y axis, your object will come towards the near or far plane because it lies in a position on the X axis. If you want to rotate the object around itself, you should place it in the center of the coordinates system.
In your code:
You scale the coordinates meaning that when you draw an object it would appear scaled, then you move the object on the X axis and then rotate its coordinate system ( this is why the object is moving towards the near plane).
The correct order of your transformations should be:

```
glTranslatef(move, 0, 0);
glRotatef(rotate,0,1,0);
glScalef(0.2, 0.2, 1.0);
draw;

```
> 1 votes

---
Tags: opengl, graphics, transformation, glut
---


title: Loaded Images are upside down

text:
# Question
Title: Loaded Images are upside down
I'm using SharpDX Toolkit and load a png file with `SharpDX.Toolkit.Graphics.Texture.Load(GraphicsDevice, Stream)`
If I apply the texture to another texture it's drawn upside down. The texture is:
and is drawn as this:
Loading is:

```
Texture image;
FileInfo file = new FileInfo(layer.Id.ToString() + ".png");
if (!file.Exists)
    return;
image = Texture.Load(GraphicsDevice, file.OpenRead());
layer.SetData(image.GetData<byte>());

```

the SetData Method:

```
private Texture2D map;
public void SetData(byte[] data) {
    map.SetData(data);
}

```

VertexBuffer declaration:

```
vertexBuffer = SharpDX.Toolkit.Graphics.Buffer.Vertex.New<VertexPositionTexture>(GraphicsDevice, new[] {
    new VertexPositionTexture(new Vector3(0, 0, 0), new Vector2(0, 0)),
    new VertexPositionTexture(new Vector3(0, Size.Height, 0), new Vector2(0, 1)),
    new VertexPositionTexture(new Vector3(Size.Width, Size.Height, 0), new Vector2(1, 1)),
    new VertexPositionTexture(new Vector3(Size.Width, 0, 0), new Vector2(1, 0))
});

```

and the WVP:

```
wvp = Matrix.Scaling(zoom) *
    Matrix.LookAtLH(new Vector3(camPosition, 0), new Vector3(camPosition, 1), Vector3.Up) *
    Matrix.OrthoLH(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, 0, 1);

```

Any idea why SharpDX draws the image upside down and how I can fix it?

# Answer
> 3 votes
I think you are probably misunderstanding the coordinate system in which you are working. Higher numbers for X and Y are not necessarily up and right on the screen. So you're most likely seeing an upside down quad, or your camera is behind the thing you're looking at and you're seeing its back (a double-sided quad will show the mirror image of your texture if you look at it from the back).

Turn your quad upside down (by changing the order of vertices in the vertex buffer declaration), or change your camera position.

# Answer
> 1 votes
Perhaps your texture mapping is upside down? Try modifying your texture coordinates in vertex buffer.

```
vertexBuffer = SharpDX.Toolkit.Graphics.Buffer.Vertex.New<VertexPositionTexture>(GraphicsDevice, new[] {
    new VertexPositionTexture(new Vector3(0, 0, 0), new Vector2(0, 1)),
    new VertexPositionTexture(new Vector3(0, Size.Height, 0), new Vector2(0, 0)),
    new VertexPositionTexture(new Vector3(Size.Width, Size.Height, 0), new Vector2(1, 0)),
    new VertexPositionTexture(new Vector3(Size.Width, 0, 0), new Vector2(1, 1))
});

```

# Answer
> 1 votes
It's important to understand the difference between the spacial coordinates being passed in for the vertex, and the texture coordinates being passed in as the second argument.

The spacial coordiantes work as expected, like any plot you've ever seen. However, for textures, the most common scheme is to put (0,0) in the upper left corner, and (1,1) or (Xres,Yres) in the lower right corner.

Try drawing a plot of where you have applied which coordinate, and you'll see that you put (0,1) and (1,1) at the top of the quad, and not the bottom.

---
Tags: directx, image, sharpdx
---


# Question
Title: Should I do intersection testing in world or object space?
I'm adding basic ray casting and collision detection for my game, and also adding bounding volumes and collision meshes.

The ray is cast in world space and each mesh's node can track its world transformation. Considering I want to test for intersection between a ray and bounding volume and also bounding volume with other bounding volume, in what space should I perform the intersection test?

Scenarios that I have in mind:

* Transform ray into object's local space, perform test, then inverse transform the resulted point.
* Transform bounding volume into world space and perform it there, or should I always keep bounding volumes in world space?
* Perform bounding/bounding test in world space or one of the objects?

Do things change much between static and dynamic collision regarding used spaces?

# Answer
> 4 votes
It's generally both easier and faster to convert rays into the object's local space and do the test. It's either 1 tranformation on the ray or N transformations of N vertices into world space, and for even a single triangle 1 will be less than N. For objects like OBBs it's also much easier to just treat it like an AABB in object space when doing ray collisions.

For object-object intersections it's still easier and faster generally to convert into one of the object's spaces. For OBB-OBB tests, it turns into an AABB-OBB test. For arbitrary meshes, it means you only need to transform one set of vertices instead of both.

For physics resolution after collisions, it doesn't matter much which space you're in since you should be computing relative values. e.g. if A collides into B, the collision will determine the resulting impulse (or penetration fixup or bounce velocity or whatever you're computing) in some vector relative to B. Just reverse the transformation on the impulse vector after calculating it if you need it in world space.

---
Tags: collision-detection, physics, mathematics, intersection
---


# Question
Title: Changing enum in a different class for screen
I'm trying to make a start menu for my game and my code uses Enum's to moniter the screen state.

Now i want to change the screenstate declared in the main class, in my Background class

```
Screen screen = new Screen();

```

is declared in the Game1 class

```
Background(ref screen);

```

This is in the update method for the Background Class

```
KeyboardState keystate = Keyboard.GetState();
switch (screen)
{
    case Screen.Start:
        if (isPressed && keystate.IsKeyUp(Keys.Up) && keystate.IsKeyUp(Keys.Down) && keystate.IsKeyUp(Keys.Enter))
        {
            isPressed = false;
        }
        if (keystate.IsKeyDown(Keys.Down) && isPressed != true)
        {
            if (menuState == MenuState.Options)
                menuState = MenuState.Credits;
            if (menuState == MenuState.Play)
                menuState = MenuState.Options;
            isPressed = true;
        }

        if (keystate.IsKeyDown(Keys.Up) && isPressed != true)
        {
            if (menuState == MenuState.Options)
                menuState = MenuState.Play;
            if (menuState == MenuState.Credits)
                menuState = MenuState.Options;
            isPressed = true;
        }

        switch (menuState)
        {
            case MenuState.Play:
                arrowRect.X = 450;
                arrowRect.Y = 220;
            if (keystate.IsKeyDown(Keys.Enter) && isPressed != true)
                screen = Screen.Play;
                break;
            case MenuState.Options:
                arrowRect.X = 419;
                arrowRect.Y = 340;
                if (keystate.IsKeyDown(Keys.Enter) && isPressed != true)
                    screen = Screen.Options;
                    break;
            case MenuState.Credits:
                arrowRect.X = 425;
                arrowRect.Y = 460;
                if (keystate.IsKeyDown(Keys.Enter) && isPressed != true)
                    screen = Screen.Credits;
                break;
            }
            break;
       }
 }

```

For some reason when I play this and I hit the enter button the Background class's screen is changed but the main class's screen isn't how can i change this?

EDIT 1\*

```
class Background
{
    private Texture2D background;
    private Rectangle backgroundRect;
    private Texture2D arrow;
    private Rectangle arrowRect;
    private Screen screen;
    private MenuState menuState;
    private bool isPressed = false;

    public Screen getScreenState(ref Screen screen)
    {
        this.screen = screen;
        return this.screen;
    }

    public Background(ref Screen screen)
    {
        this.screen = screen;
    }

    public void Update()
    {
        KeyboardState keystate = Keyboard.GetState();
        switch (screen)
        {
            case Screen.Start:
                if (isPressed && keystate.IsKeyUp(Keys.Up) && keystate.IsKeyUp(Keys.Down) && keystate.IsKeyUp(Keys.Enter))
                {
                    isPressed = false;
                }
                if (keystate.IsKeyDown(Keys.Down) && isPressed != true)
                {
                    if (menuState == MenuState.Options)
                        menuState = MenuState.Credits;
                    if (menuState == MenuState.Play)
                        menuState = MenuState.Options;
                    isPressed = true;
                }

                if (keystate.IsKeyDown(Keys.Up) && isPressed != true)
                {
                    if (menuState == MenuState.Options)
                        menuState = MenuState.Play;
                    if (menuState == MenuState.Credits)
                        menuState = MenuState.Options;
                    isPressed = true;
                }

                switch (menuState)
                {
                    case MenuState.Play:
                        arrowRect.X = 450;
                        arrowRect.Y = 220;
                        if (keystate.IsKeyDown(Keys.Enter) && isPressed != true)
                            screen = Screen.Play;
                        break;
                    case MenuState.Options:
                        arrowRect.X = 419;
                        arrowRect.Y = 340;
                        if (keystate.IsKeyDown(Keys.Enter) && isPressed != true)
                            screen = Screen.Options;
                        break;
                    case MenuState.Credits:
                        arrowRect.X = 425;
                        arrowRect.Y = 460;
                        if (keystate.IsKeyDown(Keys.Enter) && isPressed != true)
                            screen = Screen.Credits;
                        break;
                }
                break;
            case Screen.Pause:
                break;
            case Screen.Over:
                break;

        }
    }

    public void LoadStartContent(ContentManager Content, GraphicsDeviceManager graphics)
    {
        background = Content.Load<Texture2D>("startBackground");
        arrow = Content.Load<Texture2D>("arrow");
        backgroundRect = new Rectangle(0, 0, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height);
        arrowRect = new Rectangle(450, 225, arrow.Width, arrow.Height);
        screen = Screen.Start;
    }

    public void LoadPlayContent(ContentManager Content, GraphicsDeviceManager graphics)
    {
        background = Content.Load<Texture2D>("Background");
        backgroundRect = new Rectangle(0, 0, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height);
        screen = Screen.Play;
    }

    public void LoadOverContent(ContentManager Content, GraphicsDeviceManager graphics)
    {

    }

    public void Draw(SpriteBatch spritebatch)
    {
        if (screen == Screen.Start)
        {
            spritebatch.Draw(background, backgroundRect, Color.White);
            spritebatch.Draw(arrow, arrowRect, Color.White);
        }
        else
            spritebatch.Draw(background, backgroundRect, Color.White);
    }
}

```

Thats my background class!

# Answer
The final solution was this

```
    #region Properties

    private Texture2D background;
    private Rectangle backgroundRect;
    private Texture2D arrow;
    private Rectangle arrowRect;
    private Texture2D SecondScreen;
    private MenuState menuState;
    private bool isPressed = false;
    public Level level;
    public Screen screen;

    #endregion

    public void Update(ContentManager Content, GraphicsDeviceManager graphics, ref int? playerLives, ref int p1Score, Paddle paddle, Ball ball)
    {
        KeyboardState keystate = Keyboard.GetState();

        if (isPressed && keystate.IsKeyUp(Keys.Up) && keystate.IsKeyUp(Keys.Down) && keystate.IsKeyUp(Keys.Enter) && keystate.IsKeyUp(Keys.P))
        {
            isPressed = false;
        }

        switch (screen)
        {
            #region ScreenStart
            case Screen.Start:
                if (keystate.IsKeyDown(Keys.Down) && !isPressed)
                {
                    if (menuState == MenuState.Options)
                        menuState = MenuState.Credits;
                    if (menuState == MenuState.Play)
                        menuState = MenuState.Options;
                    isPressed = true;
                }

                if (keystate.IsKeyDown(Keys.Up) && !isPressed)
                {
                    if (menuState == MenuState.Options)
                        menuState = MenuState.Play;
                    if (menuState == MenuState.Credits)
                        menuState = MenuState.Options;
                    isPressed = true;
                }
                #region Menu States
                switch (menuState)
                {
                    case MenuState.Play:
                        arrowRect.X = 450;
                        arrowRect.Y = 220;
                        if (keystate.IsKeyDown(Keys.Enter) && !isPressed)
                        {
                            LoadPlayContent(Content);
                        }

                        break;
                    case MenuState.Options:
                        arrowRect.X = 419;
                        arrowRect.Y = 340;
                        if (keystate.IsKeyDown(Keys.Enter) && !isPressed)
                            screen = Screen.Options;
                        break;
                    case MenuState.Credits:
                        arrowRect.X = 425;
                        arrowRect.Y = 460;
                        if (keystate.IsKeyDown(Keys.Enter) && !isPressed)
                            screen = Screen.Credits;
                        break;
                }
                #endregion
                break;
            #endregion
            #region ScreenPause
            case Screen.Pause:
                if (keystate.IsKeyDown(Keys.P) && !isPressed)
                {
                    isPressed = true;
                    screen = Screen.Play;

                }
                if (keystate.IsKeyDown(Keys.Back))
                {
                    screen = Screen.Start;
                    LoadStartContent(Content, graphics, ref playerLives, paddle, ball);
                }
                break;
            #endregion
            #region ScreenOver
            case Screen.Over:
                LoadOverContent(Content);
                if (keystate.IsKeyDown(Keys.Enter) && !isPressed)
                {
                    LoadStartContent(Content, graphics, ref playerLives);
                    isPressed = true;
                }
                break;
            #endregion
            #region ScreenPlay
            case Screen.Play:
                if (playerLives < 1)
                {
                    screen = Screen.Over;
                    LoadOverContent(Content);
                    playerLives = 50;
                    p1Score = 0;
                }
                if (keystate.IsKeyDown(Keys.P) && !isPressed)
                {
                    isPressed = true;
                    LoadPauseContent(Content);
                }
                #region LevelLogic
                if (p1Score >= 50 && level == Level.One)
                    level = Level.Two;
                if (p1Score >= 100 && level == Level.Two)
                    level = Level.Three;
                if (p1Score >= 150 && level == Level.Three)
                    level = Level.Four;
                if (p1Score >= 200 && level == Level.Four)
                    level = Level.Five;
                if (p1Score >= 250 && level == Level.Five)
                    level = Level.Six;
                if (p1Score >= 300 && level == Level.Six)
                    level = Level.Seven;
                if (p1Score >= 350 && level == Level.Seven)
                    level = Level.Eight;
                if (p1Score >= 400 && level == Level.Eight)
                    level = Level.Nine;
                if (p1Score >= 450 && level == Level.Nine)
                    level = Level.Ten;
                if (p1Score >= 500 && level == Level.Ten)
                    level = Level.Eleven;
                if (p1Score >= 550 && level == Level.Eleven)
                    level = Level.Twelve;
                if (p1Score >= 600 && level == Level.Twelve)
                    level = Level.Thirteen;
                if (p1Score >= 650 && level == Level.Thirteen)
                    level = Level.Fourteen;
                if (p1Score >= 700 && level == Level.Fourteen)
                    level = Level.Fifteen;
                #endregion
                LoadPlayContent(Content);
                break;
            #endregion
            #region ScreenCredits
            case Screen.Credits:
                LoadCreditsContent(Content);
                if (keystate.IsKeyDown(Keys.Back))
                {
                    screen = Screen.Start;
                    p1Score = 0;
                    LoadStartContent(Content, graphics, ref playerLives, paddle, ball);
                }
                break;
            #endregion
        }
    }

    #region LoadContents

    #region LoadStartContentsx2
    public void LoadStartContent(ContentManager Content, GraphicsDeviceManager graphics, ref int? playerLives, Paddle paddle, Ball ball)
    {
        background = Content.Load<Texture2D>("startBackground");
        arrow = Content.Load<Texture2D>("arrow");
        backgroundRect = new Rectangle(0, 0, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height);
        arrowRect = new Rectangle(450, 225, arrow.Width, arrow.Height);
        screen = Screen.Start;
        playerLives = 5;
        paddle.AIpaddlePos.Y = graphics.GraphicsDevice.Viewport.Height / 2 - paddle.AIpaddle.Height / 2;
        paddle.paddlePos.Y = graphics.GraphicsDevice.Viewport.Height / 2 - paddle.AIpaddle.Height / 2;
        ball.gameStarted = false;
        ball.ballPos.X = graphics.GraphicsDevice.Viewport.Width / 2 - ball.ball.Width / 2;
        ball.ballPos.Y = graphics.GraphicsDevice.Viewport.Height / 2 - ball.ball.Height / 2;
        level = Level.One;
    }

    public void LoadStartContent(ContentManager Content, GraphicsDeviceManager graphics, ref int? playerLives)
    {
        background = Content.Load<Texture2D>("startBackground");
        arrow = Content.Load<Texture2D>("arrow");
        backgroundRect = new Rectangle(0, 0, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height);
        arrowRect = new Rectangle(450, 225, arrow.Width, arrow.Height);
        screen = Screen.Start;
        playerLives = 5;
    }
    #endregion

    private void LoadPlayContent(ContentManager Content)
    {
        screen = Screen.Play;
        switch (level)
        #region levels
        {
            case Level.One:
                background = Content.Load<Texture2D>("levelOneBackground");
                break;
            case Level.Two:
                background = Content.Load<Texture2D>("levelTwoBackground");
                break;
            case Level.Three:
                background = Content.Load<Texture2D>("levelThreeBackground");
                break;
            case Level.Four:
                background = Content.Load<Texture2D>("levelFourBackground");
                break;
            case Level.Five:
                background = Content.Load<Texture2D>("levelFiveBackground");
                break;
            case Level.Six:
                background = Content.Load<Texture2D>("levelSixBackground");
                break;
            case Level.Seven:
                background = Content.Load<Texture2D>("levelSevenBackground");
                break;
            case Level.Eight:
                background = Content.Load<Texture2D>("levelEightBackground");
                break;
            case Level.Nine:
                background = Content.Load<Texture2D>("levelNineBackground");
                break;
            case Level.Ten:
                background = Content.Load<Texture2D>("levelTenBackground");
                break;
            case Level.Eleven:
                background = Content.Load<Texture2D>("levelElevenBackground");
                break;
            case Level.Twelve:
                background = Content.Load<Texture2D>("levelTwelveBackground");
                break;
            case Level.Thirteen:
                background = Content.Load<Texture2D>("levelThirteenBackground");
                break;
            case Level.Fourteen:
                background = Content.Load<Texture2D>("levelFourteenBackground");
                break;
            case Level.Fifteen:
                background = Content.Load<Texture2D>("levelFifteenBackground");
                break;
        }
        #endregion
    }

    private void LoadOverContent(ContentManager Content)
    {
        background = Content.Load<Texture2D>("gameOverBackground");
        screen = Screen.Over;
    }

    private void LoadPauseContent(ContentManager Content)
    {
        SecondScreen = Content.Load<Texture2D>("Pause");
        screen = Screen.Pause;
    }

    private void LoadOptionsContent(ContentManager Content)
    {
        SecondScreen = Content.Load<Texture2D>("Options");
        screen = Screen.Options;
    }

    private void LoadCreditsContent(ContentManager Content)
    {
        background = Content.Load<Texture2D>("Credits");
        screen = Screen.Credits;
    }
    #endregion

    public void Draw(SpriteBatch spritebatch)
    {
        switch (screen)
        {
            case Screen.Start:
                spritebatch.Draw(background, backgroundRect, Color.White);
                spritebatch.Draw(arrow, arrowRect, Color.White);
                break;
            case Screen.Pause:
                spritebatch.Draw(background, backgroundRect, Color.White);
                spritebatch.Draw(SecondScreen, backgroundRect, Color.White);
                break;
            default:
                spritebatch.Draw(background, backgroundRect, Color.White);
                break;
        }
    }

```

Thanks, this was my way of doing it and the games done :D basically i just stored

```
Screen screen

```

in the Background class and updated it in the Update method in Game1 class to sync the Screen in that class.
> -1 votes

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


# Question
Title: Cube worlds, instancing vs mesh generation
For a Minecraft type game, what are the pros and cons of hardware instancing the terrain vs generating a mesh of vertices based on what's visible?

The terrain is dynamic so cubes will be added/removed frequently. Also each side of a cube is the same texture.

# Answer
> 8 votes
"Added and removed frequently" really is not *that* frequent in most games of the genre. Bursts of mining activity are interspersed among long bouts of exploration, farming, chatting, fighting, etc.

That said, the difference mostly comes down to performance. Which is best is entirely dependent on your API of choice, target OS, target hardware, and specific game. The best answer is to just implement whichever you find simplest to develop and then - if and only if you have performance problems - implement the other approach and compare the results.

The primary advantage of instancing is that it greatly reduces the amount of data you have to send over the bus and reduces the amount of host work you have to do. Adding or removing a block can be as simple as removing an item from an array (rather than regenerating a whole mesh), and the array need only be a texture index and a position (compared to the other approach which needs 12 triangle positions, uv coords, and texture positions per free-floating cube).

The primary advantage of building a mesh is that it allows more potential optimization and reduces the complexity of shaders somewhat. Obscured cube faces can be culled from the generated mesh much more easily than with instancing (as the data is available almost for free while building the mesh), which can greatly reduce bandwidth required (*maybe* even further than using instancing), reduces the number of triangles the rasterizer must rasterize, and reduces overdraw and fillrate consumption.

Note that you can do the second approach with even more smarts. If you're worried about frequent changes, just remember the "bursty" activity (if it applies to your game). You can generate a less efficient but easier to modify mesh after an edit and then lazily generate a more compact mesh after a second or three of inactivity. You could even switch to instancing when edits are happening and revert to meshes afterward. With a chunk-based world, you can do this on a per-chunk basis; thus *if* the mesh generation approach is faster, you let distant chunks keep their efficient meshes and only the current chunk need use a slower rendering method.

Also note that instancing is not available on all modern hardware. Probably not an issue for an XNA game, but if you plan to port to mobile OSes (maybe using MonoGame), remember that most devices are still using OpenGL ES 2.0 which does not support instancing. GLES3 devices are slowly making their way to market on some newer devices, though it'll be years before you'll want to stop caring about today's devices. WebGL is also based on GLES2 and there's been little official traction on a WebGL2 that offers GLES3-level functionality. GLES2 may be a historical relic by the time your game is even released, if you're lucky, or it may still be a limiting factor for your target markets.

# Answer
> 4 votes
First, note that there are a lot of "Minecraft-like" worlds that are very different in performance. For example, if you can't edit the terrain then the normal buried-block problem goes away. If there's no underground passages, then you reduce the rendering task even further. But I'm going to assume that you still have those two problems.

The **primary benefits of instancing** are data size and complexity. **(1)** Instancing reduces the size of the data that you have to feed to the GPU. There's just a cube, and then the locations of all the instances. Without lighting or texture changes or any other attributes, that drops the amount of memory required significantly. However, this memory normally sits on the GPU anyway so you're *not* saving CPU-\>GPU bus bandwidth. Plus geometry data (assuming decent culling, see below) is rarely very large. Hence you're "saving" something that wasn't expensive. **(2)** For instancing, the amount of processing of game data needed to generate the rendering geometry for a chunk is much smaller, simpler, and faster. If you're planning a simple demo or other application that doesn't need to be competitive on a consumer level, it's the easiest to code.

The **primary benefit of visible mesh generation** is rendering performance. The GPU processes fewer verts and should have much less overdraw (ie process fewer fragments). The downsides are larger data size and code complexity.

You might be wondering: why do I say performance is a benefit to the latter approach? Some technical details:

The biggest rendering expense with a Minecraft-type world is all of the cubes that aren't in the view frustum. Next is the surfaces that aren't visible because they're completely encased within other cubes. Third is rendering obscured surfaces, eg underground passages, walls inside structures, and stuff on the other side of hills. Fourth would be maybe backfaces. Further clasess of surfaces that shouldn't be rendered probably get more trivial.

1. You should definitely mince the world into cubic chunks and discard any chunks that don't intersect the view frustum. Frustum culling at a fine scale (a triangle or a cube) should be done on the GPU; on a large scale (eg for a 'chunk' of 8x8x8 cubes) it should be done on the CPU. Also, keep your draw distance limited -- the number of chunks you need to process increases with the cube of the draw distance. (This desire to chop the world into small chunks, however, will compete with a soft upper limit on the number of primitives that you can draw every frame.)
2. Whether you use instances or composited meshes, you should consider only drawing cubes that aren't buried. Instanced cubes will draw all six sides of every cube, even if five sides of a cube are buried. Hence, instances can have a huge amount of overdraw. Naively, an 8x8x8 chunk without any culling will have over 3,000 quads. If you have 100 chunks onscreen, a renderer will have just under 2M verts to worry about. Note that modern graphics cards (as of mid-2013) can maintain 60fps with a peak theoretical workload of around 30M verts per frame. Doable, but you can't increase the number of visible chunks (ie increase the draw distance) much without running into stuttering problems. And as long as you aren't doing much other processing! That same 8x8x8 chunk will usually have between 64 and 192 *visible* quads -- that's *2-5%* of the naive approach. Culling invisible quads will save you huge.
3. Obscured surfaces can be extremely hard to find. Normally this task is just left to the Z buffer. A smart algorithm might cut the number of quads you have to draw in half and in certain cases (e.g. staring at a wall) cut it by 99%, but normally (outdoors) you don't get much. Compare 50% to the gains in #1 and #2.
4. Likewise, backface culling is typically left to hardware. I think hardware is still limited to around 1000 draw calls per frame before it starts seriously impacting performance, so trying to be tricky by (eg) dividing a chunk into six sets (one for each facing plane) can backfire. So just let magic GPU hardware do backface culling.

---
Tags: xna, c#, procedural-generation
---


title: XNA - Distribution and Patching

text:
# Question
Title: XNA - Distribution and Patching
I have a couple of questions. Some of this I've done some research on, and some of it may be lacking, but any help is appreciated.

1) When distributing an XNA game for PC that uses custom fonts that I've installed on my Dev system - will they be usable on a client machine, or will that machine have to have that font installed?

2) What's the best practice for a)creating installers for XNA games for PC, and b)patching existing XNA game installations?

Thanks a lot.

# Answer
> 1 votes
1) If you're using SpriteFont of XNA (ContentPipeline) these SpriteFonts can be loaded by XNA (in the `Content` directory) via `ContentManager.Load<SpriteFont>("AssetName")` without having it installed on the client pc.
SpriteFont at MSDN

2) Install:

* install XNA Redistributable on the PC
* copy Application files to destination

An alternative would be ClickOnce Deployment (or the online deployment Visual Studio provides).

Patch: create diffs between updates and change the files based on that diff (ensure that the patch files are signed and can't be changed by a third-party)
or let the ClickOnce-Deployer do his job in AutoUpdating (you will find the option in Visual Studio)
Patching has to be secure otherwise your application might unintendedly be used by a third-party for his usage - which will never be good.

---
Tags: xna, patching, installer
---


# Question
Title: Why is music compressed with lossy codecs down to low bitrates in modern games?
I wonder why anyone would compress the soundtrack of a game with lossy codecs (mp3 mainly) down to 128 kbps bitrate. Thing is I see it on most of the games. Rarely a game has 320 kbps soundtrack, let alone lossless audio formats. It's mostly the case when a game is delivered digitally with a soundtrack packed as DLC along with the main game, and still sometimes the game itself uses a lossy version of it, which just seems silly.

It might have been an issue of free hard drive space or insufficient CD capacity, but these days games are either shipped on huge multiple-layered high capacity optical discs, or fully delivered via content distribution networks.

Why do modern games have lossy encoded music files?

# Answer
> 10 votes
Larger sizes cost money and slow down downloads. That matters. When you have a game that has multiple music tracks compressing down lossily can save many megabytes (even gigabytes if you include audio effects, dialog, etc). Sure, your game might already be a 4GB download, but why pay for extra server bandwidth and make users wait longer for 5GB if there's no benefit to doing so? Especially as we move more into free-to-play: a game that downloads in 5 minutes has a much higher chance of converting players (and making more money) than one that takes 7 minutes to download. Every single last barrier between catching a potential player's interest and getting him in game needs to be broken down if possible. See the success of Flash games and their very fast "click link to game's site, be in game" conversion opportunities.

Then let's think about platforms that have limited storage size. A console might only have several GB available for user downloaded games on limited flash memory. An 800MB title will fit. A 2GB+ title will only be available to a subset of console owners.

Now let's look at memory. If you need to load music, sound effects, and dialog into memory to play it, what do you do on a system like the 360 that only has 512MB shared with the video card in total? Even on PC, many users are still on a 32-bit OS, which means you've got all of 2GB (maybe 3) to fit everything you need loaded on the CPU, including audio. For music only this is somewhat reduced since you're usually streaming, but the compressed audio still allows smaller buffers (assuming you're offloading to an audio unit that can decompress on its own) in main memory. The streaming is also less likely to lag or glitch with smaller, less-frequent requests for blocks achieved by packing in more audio data in less space.

And then of course there's other considerations like mobile games, where you need to keep the entire game under ~50MB in order to be able to be downloaded on cellular connections. A player who finds your game on the bus but can't download is probably not going to bother looking up your game again later when they get home: you've missed your chance to get a new customer. You need to get the entire game - executables, packaging, textures, models, game data, and audio - into that 50MB envelope.

These other platforms affect the PC indirectly, too. There needs to be a strong case to spend the time and money to write two different audio conversion pipelines for PC and consoles (and then test them), and "the PC can do it better" is not generally a strong case for most titles (since making the PC version better rarely increases sales signifiicantly). If you're already converting to MP3 or Ogg to deal with a console, you might as well just reuse all that pipeline work and verification on the PC.

# Answer
> 1 votes
Many players would care a lot if their download times suddenly doubled, making an impulse purchase less likely. Also, I don't know if this still holds true, but for digital/marketplace options some devices (xbox?) had a tight upper limit on size.

And someone, somewhere, pays for that bandwidth.

Plus runtime RAM limits are seen as better spent on graphics, which are immediately obvious to 99% of all players and reviewers, versus audio which is only noticed if it's either out of sync or has really bad voice actors.

---
Tags: audio, compression
---


# Question
Title: How do programming skills aid a game designer
So many game designers are programmers as well nowadays. Is it so *extremelly* helpful for a game designer to have programming skills and in which ways programming skills aid a game designer?

# Answer
Well, if you want to program games, it's pretty beneficial to have those skills. But at least from what I've seen of game design, a lot of it is breaking down larger problems into smaller ones and building towards the whole. Being able to break down problems like that is HUGE in programming, so my guess is a lot of game designers recognize that and want to enhance that skill, or they just want to see another aspect of the actual process of making games. Especially if they're a project lead, they need to understand the work of everyone working under them in order to be the best project lead that they can be. That being said, if you just want to do art, or animation, or sound or anything like that, you don't need programming, but if it interests you at all it's not the worst skill/hobby to have.
> 1 votes

---
Tags: game-design, software-engineering
---


# Question
Title: Have the character automatically slide around obstacle corners
Like this:

The player is only holding right, however the character still moves up a bit to go around an obstacle.

My current collision system has access to:

* The entity's previous position
* The entity's current position
* The entity's (axis-aligned) bounding box
* All the obstacles and their (also axis-aligned) bounding boxes

Also it proccesses each axis separatelly.

How can I implement this?

# Answer
Traditionally if you're travelling parallel to the axis of a box, traditional collision handling won't make you go around the corner like that. That's because there's no local information on whether you should go around by going up or by going down.

I see two obvious options:

1. Local approach - make the collision shape a box with bevelled corners, e.g. a type of octagon. Therefore it would naturally (depending upon implementation) slide along the corner because it's a 45 degree angle.
2. Global approach - when a collision occurs decide by some heuristic which way to go. For example pick the shortest path to the opposite side of the box.

To slide along an angle nicely, take the attempted movement vector and subtract the component in the direction of the normal of the box.
> 3 votes

---
Tags: collision-detection, collision-resolution, collision-avoidance
---


title: Sound Manager class in Unity

text:
# Question
Title: Sound Manager class in Unity
Starting with Unity having had experience of XNA im not sure if the way i want to solve my problem is the correct way. So id like the opinion of more experienced people.

I am doing a 2.5D game and have no need for 3D sounds that generate from a certain 3D position. I am used to creating a sound manager class that handles the loading of sound assets and has a static public method for each sound effect. This way it works like a toolbox i can call SfxManager.PlayDeathScreamSfx(); from anywhere in the solution.

How could i do the same in Unity?

I have tried making a game object called soundmanager and given it static methods that would play the sound effects but the SoundClips needs to be static for the static methods to be able to use them. And if the SoundClips are static then they dont show up in the inspector and i cant drag'n'drop a sound file on them to reference them.

What to do?

# Answer
> I am doing a 2.5D game and have no need for 3D sounds that generate from a certain 3D position

Then uncheck the 3D sound checkbox in the sound file inspector.

> I have tried making a game object called soundmanager and given it static methods that would play the sound effects but the SoundClips needs to be static for the static methods to be able to use them.

I'd stay away from static stuff. In Unity you usually don't use static managers class. Instead create a `SoundManager` component, with a AudioSource component attached and expose public methods for playing your sound fx. For example:

```
[RequireComponent(typeof(AudioSource))]
public class SoundManager : MonoBehavior
{

public AudioClip soundA; //assign clips from inspector
public AudioClip soundB;

public void PlaySoundA()
{
   audio.PlayOneShot(soundA);
}

public void PlaySoundB()
{
   audio.PlayOneShot(soundB);
}
}

```

From the other behavior, you only need a reference to `SoundManager`. Assign it to them through inspector or find the `GameObject` with `SoundManager` compoents when those behaviors start.
> 0 votes

---
Tags: unity, sound
---


# Question
Title: Using a web service for multiplayer games?
I've been looking into web services for making multiplayer games and was just wondering how feasible would it be?

What I would like to do is make a simple MMORPG that uses a turn based fighting system, are there any inherent limitations with web services which would make this difficult and not worth my time?

Also out of curiosity would a faster paced multiplayer game be workable using web services? Something like a top/down shooter similar in pace to games like asteroid?

# Answer
To be able to handle the number of simultaneous users that you intend to, for any game relying on realtime interaction, you'd typically need a dedicated server with a mighty strong/fast connection, running a direct tcp/ip connection to each client.

Even for something turn based, such as chess or magic the gathering, if you tried to implement an RPC or REST (http tunnelling) service, the resulting speed drop with 200 simultaneous connections to a single server would degrade the user experience to the point of frustration.
> 3 votes

# Answer
You should look into Electro Server, or if you can dumb down the design a bit and make everything play asynchronously like a lot of facebook games do then using a RESTful webservice setup can work very nicely... Otherwise Jordaan Mylonas said it all pretty well.
> 3 votes

# Answer
the throughput is important and by using a web service, you will increase the size of the message by unnecessary information inside your header messages. I would advise you to make your own customize web service over a tcp or udp connection.
> 0 votes

---
Tags: networking, multiplayer, mmo, web
---


# Question
Title: Ball vs 45-degree slope collision detection
I have a simple game in which the player moves a ball around. The ball bounces off of walls. Right now I have square walls(■) implemented: I use simple bounding-box collisions to check if the player will move into a wall when updating its x or y speed and if so, I multiply that speed with -1 to make them bounce.

However, I also want to implement triangular pieces(◢◣◤◥). To bounce back I believe one can simply use:

```
   newxspeed = -1*yspeed;
   newyspeed = -1*xspeed;

```

However, what I am having trouble with is the collision detection: When does the player hit the diagonal?

# Answer
> 8 votes
First of all in order to calculate the collision detection between a sphere(circle in 2D) and a line you need to calculate the perpendicular vector between the moving ball's center and the line, in order to calculate this distance you need to do the following:

So in order to calculate d in the above figure we need to do some steps.

1. Assume your line is using the parametric equation P(t) = **S** \+ t **V** note that **V** is the line direction can be obtained by subtracting (P2 - P1).
2. From Pythagoras:

> d^2 = len(**Q** \- **S**)^2 - len( proj(**Q** \- **S** ) )^2

Then you expand the equation to get the following, it seems a bit complicated but it's actually not.

> d = sqrt( len(**Q** \- **S**)^2 - len( (**Q** \- **S**) dot **V** )^2 / V^2 )

Where **Q** is the circle's center and **S** is any point on the line. Once the distance is less than the circle/sphere radius you need to trigger collision response which is explained in the next point.

It's incorrect to always flip the x or y component to bounce the ball, what you need to do is to reflect the velocity vector, in order to do so you need to calculate the Normal vector of the surface and use that normal for calculating the reflection vector using the following equation

> **R** = 2 * (**V** dot **N**)\* **N** \- **V**

where **R** is the reflection vector, **N** is the normal of the surface and **V** is the Velocity vector.

In case of 45 deg your surface normal will be N = (1,1,0) with varying sign depending on which direction the normal faces (position or negative).

# Answer
> 6 votes
You want to measure the distance between the center of your ball and the wall, so:

solving the system that you see in the picture will give you the coordinates of point d.

Then, if the distance between point d and c is smaller or equal to the radius of the ball r, there is a collision between the ball and the wall

# Answer
> 5 votes
Balls are actually rather simple objects for collision detection. They collide with terrain when the distance between the ball's center and the edge of the terrain becomes less than the ball's radius. The position of the center of the ball should be trivial to obtain. Finding the nearest point of terrain is generally more complicated and the best way to do it depends on how the terrain is represented.

Your algorithm to calculate the new velocity after bouncing off a diagonal slope is incorrect. Inverting both the x- and y-coordinates will make the ball go back in the same direction it approached the slope from. This is fine if the ball comes at the terrain from a right angle, but fails for other angles. You'll want to negate only the component normal to the surface, e.g. when bouncing off the ceiling, you negate y, not x.

---
Tags: collision-detection
---


# Question
Title: Unity Sound effect playing too many times
In the class PlayerControl I have this

```
if (Input.GetKey("space"))
    {
        soundManager.PlayBleep();
        sword.SetActive(true);
    }

```

In my soundmanager I have this

```
   public void PlayBleep()
{
    if (!audio.isPlaying) {
        audio.PlayOneShot(SwordWhip2);
    }
}

```

At the moment I am getting the sound like 10 times each time I press space creating horrible soundeffects. How could I get it not to play until the sound has finished?

# Answer
> 1 votes
`PlayOneShot` does not alter `isPlaying`. See here. So `isPlaying` will always be false.

A simple fix is to change your input to only trigger once. Instead of `Input.GetKey("space")` you can use `Input.GetKeyDown("space")`.

You can alternatively add your own flag for when the weapon is active. This additional flag would likely be useful for the animation and other time delays to keep the sword from swinging too fast.

---
Tags: unity, sound
---


title: Using versors for movement

text:
# Question
Title: Using versors for movement
**The context**

I was thinking of using a versor + velocity field to implement the "moving" part of a 2D game object. For example, if the player should move right I just set the versor to be: \[1, 0\] and the velocity to be some variable. Then when the player movement needs to be updated we just multiply the versor to the variable and we get the vector to be summed to the current vector position.

For example if the position `p` is `[12, 45]` in the 2D space, the versor `vs` is `[1, 0]` and the velocity `v` is `4` we can easily apply the algorithm above:

```
new position = p + (vs * v)

```

which leads to:

```
new position = [12, 45] + ([1, 0] * 4)
new position = [12, 45] + [4, 0]
new position = [16, 45]

```

The velocity/speed is a separate field because a versor (of length always = 1) better explain diagonal cases, like we see below.

When the player position is handled by the pressing of WASD keys I'd like to be able to code something like this:

```
on press W -> add versor [0, +1] to current versor and normalize
on press S -> add versor [0, -1] to current versor and normalize
on press A -> add versor [-1, 0] to current versor and normalize
on press D -> add versor [+1, 0] to current versor and normalize

on release W -> remove versor [0, +1]
on release S -> remove versor [0, -1]
on release A -> remove versor [-1, 0]
on release D -> remove versor [+1, 0]

```

**Adding versors (everything is good)**

The cool thing about this is that when both W and D are pressed the player moves diagonally to the top right because we first add the W versor and normalize:

```
vs = [0, 0]
vs += [0, +1] // W versor
// vs is now [0, +1] which is already normalized

```

and then we add the D versor:

```
// vs is now [0, +1]
vs += [+1, 0] // D versor
// vs is now [1, 1] which is not normalized
vs /= magnitude(vs)
// vs is now [0.71, 0.71]

```

**Substracting versors (the problem)**

Now the problem is when the user later release the W key for example. We currently have the W and D key pressed (which means the player is moving of \[0.71, 0.71\] (towards the top right corner) at every update. But if we remove the W versor, the calculus goes as:

```
// vs is now [0.71, 0.71]
vs -= [0, +1]
// vs is now [0.71, -0.29]
vs /= magnitude(vs)
// vs is now [0.9258, -0.3781]

```

The versor should be the remaining D versor, instead, (\[1, 0\]). I understand that this problem is related to the fact that we are normalizing at every operation, otherwise we would have:

```
vs = [0, 0]
vs += [0, +1] // W versor
vs += [+1, 0] // D versor
// vs is now [+1, +1]
vs -= [+1, 0] // D versor
// vs is now [0, +1]

```

but if we don't normalize and for some reason two D events are sent, we end up with:

```
vs = [0, 0]
vs += [0, +1] // W versor
vs += [+1, 0] // D versor
vs += [+1, 0] // D versor
// vs is now [+1, +2]
vs -= [+1, 0] // D versor
// vs is now [+1, +1]

```

which is not what we want. How can I correctly calculate the player position with versors then?

# Answer
> 3 votes
Don't try to remove force from your movement when a key is released. Apply movement acceleration/force every frame, not just on key events. Clamp velocity's magnitude and use *damping* (plus maybe surface friction) to cause the character to quickly slow to a halt when the key is released.

This applies whether you're using versors, vectors, or some other representation. You're currently combining your movement controls with current object state and losing information in the process (which is why subtracting the original inputs doesn't work). You'll also run into problems with trying to apply counter force when letting go of a key once you have more complex scene interactions: your character will maybe hit a wall and stop moving, so applying a counter force to the original input will cause the character to start moving in the opposite direction.

---
Tags: 2d, movement, linear-algebra
---


title: Displaying normals of a geometry

text:
# Question
Title: Displaying normals of a geometry
I have a rectangle which is created by 2 triangles and it is in x-z plane, and i have object on it. Now, the normals of two triangles (face normals) are y axis i.e. (0,1,0). I want to display normals of two triangles for which i need two points to draw a line to show normal. Intuitively if i take center of a triangle as one and (0,1,0) as second point of a normal then both of the normals will converge to single point. I dont think it is correct as the normal should be exactly perpendicular to the surface. We can do a trick and take one point as a center and other by increasing y coordinate keeping x and z same, but what if we have curved surface and not a plane board? What about the cylinder made of triangles? How could we display normals as a lines of cylinder? I guess i am missing very basic concept here, please help me to understand it and tell me how to calculate the two points of normal.

# Answer
> 1 votes
Usually you already have normals for all three vertecies that make a tri. In that case you average the position of the vertecies as the first point and add the average of all 3 normals to get the second point.

(v0 v1 and v2 are supposed to be the vertecies that make up the triangle) If you don't already have normals and you want to calculate them then you just calculate the cross product of `perpendicular = v0v1 x v0v2` and then normalize the result (divide by length). The order is important. v0 is the first vertex, v1 the second and v2 the third. `v0v1 = v1-v0` and v0v2 = `v2-v0`. Start point is as was before `start = (v0+v1+v2)/3.0` and the end is then `end = start+ (perpendicular/length(perpendicular))`

Also, depending on your model size the length of 1 might be too small or too huge, in that case just use a scaling factor.

This is really more of a comment but it's a little too long so I'm posting it as an answer

---
Tags: opengl, mathematics, graphics, transformation
---


# Question
Title: how to predict enemy postion to shoot bullet same kingdom rush
i'm doing a tower defense game same kingdom rush, enemy can run curve not only linearly.

i found this link : 2D tower defense - A bullet to an enemy

but this link use only for enemy run linearly.

So how to predict target's position in future with enemy can run curve .

p/s : i use this link to make enemy run http://gamedev.tutsplus.com/tutorials/implementation/understanding-steering-behaviors-path-following/

# Answer
If you're trying to intercept a known curved path it just comes down to algebra, e.g. solve for the line intercepting the parabola.

However if you're talking about adaptive things like steering behaviours, you can't guarantee interception because their trajectory can change at any moment. I think that the best you can do is to cheat a little and ask the enemies what their current path is. General flow below:

1. Estimate travel time for projectile to reach enemy
2. Estimate enemy position on spline at that time
3. Go back to step 1 as many times as desired with new enemy position

Note that you can still miss if they recalculate their path after you shoot.

Edit: pseudocode below

```
estimated_enemy_pos = current_enemy_pos
for i equals 1 to some_number
    difference = estimated_enemy_pos - gun_pos
    distance = difference.magnitude
    time_to_hit = distance / bullet_speed
    estimated_enemy_pos = spline_pos(time_to_hit)

shoot(estimated_enemy_pos)

```
> 1 votes

---
Tags: mathematics, cocos2d, bullet-physics, projectile-physics, tower-defense
---


# Question
Title: Unity Mesh and Collider not aligned on rotation
I have a GameObject with a mesh and a collider. When I rotate the object the mesh and the colider do not act the same way and when the GameObject is rotate 65 degrees on the z axis the mesh and the colider are no longer aligned. This must affect game play. I don't understand why this happens and how it is supposed to be fixed.

# Answer
> 3 votes
I got it! The problem was that the GameObject that was not aligned with its colider was a child of another GameObject and that parent was scaled. When you dont have the scales (1,1,1) weird things happens to the children.

Solution is to create a root GameObject that never is scaled and then put children in it.

# Answer
> 0 votes
Out of the box this doesn't happen in my experience. I suggest to check if rotating it in design view has the same problem to rule out scripting effects. Most likely something is referencing the mesh and/or collider individually rather than just the GameObject.

---
Tags: unity, 3d-meshes
---


# Question
Title: XNA C# Making the game scaleable for different resolutions
I am currently developing a game in C# and XNA, and I want it to look right at all resolutions. How would I get started with doing that?

# Answer
First, you have to decide how are you going to actually do the scaling? Do you need to handle aspect ratio? (It sounds like you do.)

If you are using `SpriteBatch`, you can pass a scaling matrix to `Begin`. You can also set the `Viewport` to letterbox or pillarbox off the screen you don't want to render to. Here is an example:

```
int backbufferWidth = GraphicsDevice.PresentationParameters.BackBufferWidth;
int backbufferHeight = GraphicsDevice.PresentationParameters.BackBufferHeight;

Viewport originalViewport = GraphicsDevice.Viewport;
GraphicsDevice.Viewport = new Viewport((backbufferWidth - viewWidth)/2
        (backbufferHeight - viewHeight)/2, viewWidth, viewHeight);

Matrix scaleMatrix = Matrix.CreateScale(scale, scale, 1);
spriteBatch.Begin(0, null, null, null, null, null, scaleMatrix);

// ... draw your sprites ...

spriteBatch.End();

GraphicsDevice.Viewport = originalViewport;

```

Note that the above code is untested. Also, I've left the maths for figuring out `scale` and `viewWidth` and `viewHeight` as an exercise - it will depend on how you actually want the scaling to look.

(My answer on that question I linked might give you a starting point. Don't forget to use `Math.Floor` to set `viewWidth`/`Height`, so it doesn't round up and extend outside the backbuffer!)
> 1 votes

# Answer
You can create a menu with an option to change the resolution. Include all the standard resolutions. When the user clicks on that option, change the resolution via

```
graphics.PreferredBackBufferWidth = 1920; //Your width
graphics.PreferredBackBufferWidth = 1080; //Your height
graphics.ApplyChanges(); //When calling this from outside the constructor, apply all the changes.

```

And if you want to scale up everything, render it into a RenderTarget with fixed size and then render the RenderTarget to the screen (and scale it up).
> 0 votes

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


title: C# Collision Math Help

text:
# Question
Title: C# Collision Math Help
I am making my own collision detection in MonoGame. I have a PolyLine class That has a property to return the normal of that PolyLine instance. I have a ConvexPolySprite class that has a List LineSegments. I hav a CircleSprite class that has a Center Property and a Radius Property. I am using a static class for the collision detection method. I am testing it on a single line segment. Vector2(200,0) =\> Vector2(300, 200)

The problem is it detects the collision anywhere along the path of line out into space. I cannot figure out why. Thanks in advance;

```
public class PolyLine
{
    //---------------------------------------------------------------------------------------------------------------------------
    // Class Properties

    /// <summary>
    /// Property for the upper left-hand corner of the owner of this instance
    /// </summary>
    public Vector2 ParentPosition { get; set; }

    /// <summary>
    /// Relative start point of the line segment
    /// </summary>
    public Vector2 RelativeStartPoint { get; set; }

    /// <summary>
    /// Relative end point of the line segment
    /// </summary>
    public Vector2 RelativeEndPoint { get; set; }

    /// <summary>
    /// Property that gets the absolute position of the starting point of the line segment
    /// </summary>
    public Vector2 AbsoluteStartPoint
    {
        get
        {
            return ParentPosition + RelativeStartPoint;
        }

    }//end of AbsoluteStartPoint

    /// <summary>
    /// Gets the absolute position of the end point of the line segment
    /// </summary>
    public Vector2 AbsoluteEndPoint
    {
        get
        {
            return ParentPosition + RelativeEndPoint;
        }

    }//end of AbsoluteEndPoint

    public Vector2 NormalizedLeftNormal
    {
        get
        {
            Vector2 P = AbsoluteEndPoint - AbsoluteStartPoint;
            P.Normalize();
            float x = P.X;
            float y = P.Y;
            return new Vector2(-y, x);
        }

    }//end of NormalizedLeftNormal

    //---------------------------------------------------------------------------------------------------------------------------
    // Class Constructors

    /// <summary>
    /// Sole ctor
    /// </summary>
    /// <param name="parentPosition"></param>
    /// <param name="relStart"></param>
    /// <param name="relEnd"></param>
    public PolyLine(Vector2 parentPosition, Vector2 relStart, Vector2 relEnd)
    {
        ParentPosition = parentPosition;
        RelativeEndPoint = relEnd;
        RelativeStartPoint = relStart;

    }//end of ctor

}//end of PolyLine class

public static bool Collided(CircleSprite circle, ConvexPolygonSprite poly)
{
            var distance = Vector2.Dot(circle.Position -
                poly.LineSegments[0].AbsoluteEndPoint, poly.LineSegments[0].NormalizedLeftNormal) + circle.Radius;

            if (distance <= 0)
            {
                return false;
            }
            else
            {
                return true;
            }

}//end of collided

```

# Answer
To me that looks like code for intersecting a circle with an infinite line, not a line segment. It's determining the distance from the circle centre to the closest point on the line, and if it's less than the circle radius it's a collision. There are various ways to limit it to a line segment, e.g. check if the closest point is within the line segment, or use a parametric equation for the line segment and check whether t is in the range 0 to 1.

Formulae for intersections can be found on the net, e.g.: http://mathworld.wolfram.com/Circle-LineIntersection.html
> 1 votes

---
Tags: monogame
---


title: HTML5 2D Game Renderer

text:
# Question
Title: HTML5 2D Game Renderer
i have a question on designing a HTML5 2D game renderer.

I've read that it's better to not let entities draw themselves but instead put all the drawing functions in the renderer. After coding for a bit, I realise that this does have its advantages. For instance, I can have a list of helper functions in my renderer system, like `drawRotatedImage()`, `getSprite()`, `setFontSize()`, plus the context variable etc.

However, wouldn't this lead to a very bloated renderer class, with functions like `drawTree()`, `drawMonster()`, `drawPlayer()`, `drawBall()` or whatever entity?

Also, how would i easily map the entity objects to their corresponding draw functions? Would i have to do an `if (entity.type == 'monster') this.drawMonster(); else if (entity.type == 'tree') this.drawTree();` kind of thing?

# Answer
It would appear that you're implementing this design pattern in a way that causes new issues. The good news is, you've observed the problems with your implementation!

> Wouldn't this lead to a very bloated renderer class?
> How would I easily map the entity objects to their corresponding draw functions?

Consider refactoring your code so you have a more "templated" design. Rather than having all these different functions `drawPlayer()`, `drawMonster`, `drawTree()`, etc., consider analyzing the similarities between these functions and turning them into a single function. One way to do this is to store all the information that would be different per entity (position, sprite reference, rotation) in the entity itself. Then, you can have one function in your renderer that looks like this:

```
drawSprite(Sprite &sprite, float x, float y, float rotation);

```

Now, in each of your entities, there is no need to make a call to its own special draw function because you have one generalized function. Simply call `drawSprite` and pass the proper arguments.

With some clever inheritance or composition, you should find yourself writing very little rendering code after you take care of this.

Edit: I'd also like to point out that this has the advantage of decoupling rendering code from entities. You may find this useful for drawing things out of the game's context, like rendering your main character's sprite next to the title at the main menu, or showing item graphics in an inventory.
> 1 votes

# Answer
I recommend that you *do* have functions in your renderer called "drawTree", "drawHouse" etc.

To call these, you can pass your renderer object into your objects (polymorphic) "draw" function. Instead of the objects drawing themselves, they just pass off the relevant information into the renderer. What information that is, depends on the kind of object.

So the Ball's "draw" function looks a bit like

```
function draw(renderer) {
   renderer.drawBall(this.location); // other params as necessary
}

```

Also if you have some object which doesn't need rendering (say it is a game-logic object), then you can just have it have a "noop" rendering method.
> 0 votes

# Answer
I tried to model a render system for an html5 game and learned the following:

We use render code separated from other game code with the intention of change graphic api at any time without having to touch anything except the renderer implementation. But, for html5, do we need this? Canvas is already all the multi platform it can be. The browsers are already responsible of implement the platform specific part.

A render system, if used, must be very generic. I don't think a method called renderATree() should be in the renderer. The sprite representing a tree must contain the data that you need to pass to a render generic function to produce a result that looks like a tree.

```
sprite.img = "media/img/trees.png"; // many types of trees in a single png file
sprite.left = 0; // we configure the sprite to represent one of those trees
sprite.top = 0;
sprite.width = 32;
sprite.height = 32;
sprite.offsetx = -16; // the sprite will be renderer centered in the x axis
sprite.offsety = -32;

```

renderer.renderSprite(sprite, posx, posy, rotation, scale);

If this where C++ renderSprite would probably contain api specific calls (DirectX, OpenGL), but being a html5 game, it probably contains only canvas calls. Having a render system then is only a choice of code organization.

If you still need a method like renderTree or renderMonster then I would make them part of the sprite or entity.

The Tree "class" then share the same prototype of the sprite "class" but define its own render method. In javascript this does not look so unnatural, I remember doing something like this:

```
function Sprite ()
{
  // The sprite interface (some vars and some functions)
}

function newSoldier ()
{
  var spr = new Sprite();
  var spr.render = renderSoldier; // written somewhere, contains the canvas calls to render a soldier.
  return spr;
}

```

And It was used like this:

```
scene.add(newSoldier());

```

When using the "Each sprite know how to render itself" approach a render system became unnecessary. Then I ended with a main loop that used functionality of the scene "class" to efficiently cull the scene and then loop through a sprite array representing the visible part of the scene calling each sprite render function. As sprites are allowed to contain render code, anything can be an sprite including a health bar that needs no image data and is renderer only with lines of different colors (easy done with canvas calls).

Also note that with the second approach sprites and entities are the same thing. I called them sprites because it was 2D game. In the first approach sprite was a "structure" that contains data for the renderer renderSprite function and a separate entity "class" that refers to a sprite was needed.

In resume, my position is:

* If implementing a render system include only generic functionality on it (probably unnecessary on most htm5 games)
* If you choose "Each sprite know how to render itself" having canvas calls inside the render functions does not harm in this case.
> 0 votes

---
Tags: architecture
---


# Question
Title: Drawing Sprites at Correct Z-Index without A Sprite Map?
My game is in HTML5 canvas, but I assume this concept applies to any language.

In the past I've used a multi-dimensional array to keep track of sprite positions. Here is a simplified example:

```
[
[ [],[[plant12]],[],[],[] ],
[ [],[[apple]],[],[],[] ],
[ [],[],[],[],[] ],
[ [[apple]],[],[[apple]],[],[] ],
[ [],[],[],[],[] ],
]

```

And this would always draw sprites with the correct z-index, as the map was always read left-to-right, top-to-bottom:

But with a more experienced game developer's advice, I started using quad trees for collision.

Since I will have a tree of objects with x/y coordinates, I thought I might as well abandon using a sprite map, and just draw the sprites based upon the quad tree data.

But the problem is that if the objects are not collected in a precise order, the sprites will be drawn in incorrect order, resulting in such:

If I am not using a sprite map, what is the best way for me to ensure I am drawing sprites in the correct order/z-index?

I am thinking that maybe I will make a collection method for the quad tree that will collect objects from a left-\>right, top-\>bottom order, and then draw each object's corresponding sprite in a loop. But honestly, that sounds a lot less inefficient that a having a predefined map, especially considering that all that traversing is a lot of recursive calls.

Another approach is to create some sort of z-index system, but I think that may be over-complicating things as well.

Any advice on how to approach this?

# Answer
> 1 votes
Implement a QuadTree was indeed a good idea. Scene culling and collision detection will be more efficient with a QuadTree.

Your only option is to learn a sorting algorithm or get a library that implement one. I don't know a javascript library that meets this condition.

First you select the visible sprites. This will be fast thanks to the quad tree. This is the scene culling.

Second, you will have an array of sprites in any z-order. Then you apply a sorting algorithm to efficiently sort the array from the lower z value to the higher one.

Third, now you have the same array but with all sprites ordered by their z position. Render all sprite in the array.

Sorting algorithms reference: http://www.sorting-algorithms.com/

Play all animations and choose which one to implement. I remember have used Quick3 in the past for a QuadTree.

It may be the case that you don't want to pay the time cost of learn an algorithm at this stage of your project. In my opinion it won't take so much time and will be good later. But if you still want to avoid the sorting algorithms for now, do brute force as a temporary solution:

When you are inserting the sprites into the array, for each new sprite, increase the array size by 1, iterate through the entire array, compare the arriving sprite z with each of the other sprites. Remember that the array is sorted from the beginning because all sprites where inserted using this method. When you find the first sprite with a higher z-order, move that sprite and all sprites next to that one by 1 to the end of the array. Then insert the arriving sprite where the first sprite with higher z-order was.

Note: that is very inefficient. It only will work to make possible to see the game graphics correctly drawn for now, but you probably cannot publish your game until you implement a more efficient method. If all scenes of the game are so simple that this method is enough maybe the quad tree was not needed in the first place. As you are using a quad tree, then you expect your scenes to reach considerable complexity, and sorting algorithms will be needed too.

---
Tags: 2d, sprites, html5
---


title: Compute Shader Memory Sharing

text:
# Question
Title: Compute Shader Memory Sharing
Ok guys I have had some pretty good success on this site but I feel that this is a pretty complex question.

I am trying to do tile based deferred lighting using DirectX 11 and the compute shader. Basically I am splitting up the screen into tiles and figuring out which lights hit the pixels in that tile. Then once I get to the pixel shader I only calculate the lighting for the current pixel based on what lights hit that pixel. (I'm pretty sure that I can find the lights that hit the pixel and the lighting calculations for that pixel solely in the compute shader but for now I am not doing that). So currently I think there is two ways that I can get the information to the compute shader. The tile data needs to come in a RWStructuredBuffer so that I can write to it and then use it during other parts of the GPU pipeline in a ShaderResourceView. The thing that I am not sure how to do is what is the best way to get all of the light data to the compute shader? I think I could do it in a constant buffer or a groupshared buffer. I believe the latter of the two is faster but I am not sure how it works and I cannot find much information on it. And if I was to use a constant buffer I would need to house an array of lights in that buffer and I am not sure how I would do that either because I do not want to hard code an array size in the shader.

Here is some code samples to show you what I am doing.

```
struct ComputeIn
{
    uint3 DTid  : SV_DispatchThreadID;
    int index   : SV_GroupIndex;
};

struct TileData
{
    float4 position;
    float3 normal;
    float2 texCoord;
    vector<float, 8> something;
};

struct PointLightData
{
    float4 color;
    float3 pos;
    float radius;
};

//If I use a cbuffer for the light data
cbuffer LightData
{
    //How do I make an array of lights in a cbuffer
    Array of lights here!
};

RWStructuredBuffer<TileData> tileData : register(u0);

//If I use a groupshared
groupshared PointLightData pointLights : register(u1);

[numthreads(1, 1, 1)]
void CS( ComputeIn input )
{
    //How do I iterate through the groupshared buffer?
    //groupshared[?];
    //

}

```

One more thing. I may be incorrect in assuming this but I assume that memory on the GPU is similar to memory outside of the GPU. If I have a buffer that is passes to the GPU and I know how my data is lined up inside of this buffer, I should be able to traverse through this memory to get to what data I need. My question is how do you traverse memory on the GPU. If I have a this.

```
struct PointLightData
{
    float4 color;
    float3 pos;
    float radius;
};

StructuredBuffer<PointLightData> pointLights : register(u0);

[numthreads(1, 1, 1)]
void CS( ComputeIn input )
{
    //FIGURE OUT WHAT LIGHTS HIT THIS TILE!

}

```

I assume that pointLights is a "pointer" to the beginning of this memory. How would I go about traversing all of the memory inside of this buffer? Suppose I know the total size of the memory and will not go out of bounds?

If anyone can shed some light on any of these topics I would greatly appreciate it!

Thanks!

# Answer
A structured buffer is probably the best way to get the light data into the compute shader. As you pointed out, there are some disadvantages to using a constant buffer: you would have to specify a fixed array size, and constant buffers also have worse packing (things tend to have to be 16-byte-aligned with them), while structured buffers don't have these drawbacks.

Groupshared memory would not be appropriate for getting data into the shader. It is for threads within the threadgroup to share data amongst each other. Groupshared memory cannot be initialized or set from outside the shader. It does not have a register (`u0` etc.) since it is not used to communicate outside the shader.

You can define a structured buffer pretty much like you showed:

```
struct PointLightData
{
    float4 color;
    float3 pos;
    float radius;
};

StructuredBuffer<PointLightData> pointLights : register(t0);

```

However, note that for a *read-only* buffer or texture, it goes in a texture register (`t0`), not a UAV one. This holds true on the CPU side as well; you'll create an SRV for the buffer and set it to an SRV slot, rather than a UAV slot. You can make this a dynamic buffer (`USAGE_DYNAMIC`) and use `Map` to update it each frame with the current set of lights, much like you would do a dynamic vertex buffer.

In the shader, the structured buffer just behaves like an array. You can access elements of it by subscripting:

```
for (int i = 0; i < numLights; ++i)
{
    PointLightData curLight = pointLights[i];
    // do stuff with this light...
}

```

Finally, you probably actually *don't* want the tile data to be in an `RWStructuredBuffer` UAV. A UAV would be useful if you wanted to store some data generated by this compute shader and then use it later, in a different dispatch or draw call. However, tile-based deferred lighting is typically all done in one dispatch. This would be the place to use groupshared memory. Each threadgroup corresponds to one tile, so you would use `numthreads(16, 16, 1)` for 16x16 tiles (or whatever size you choose). Each threadgroup generates a list of lights into its own groupshared memory, then applies those lights to each pixel in the tile. This way the per-tile light lists never need to go off the chip to global memory; they just stay in the fast local memory until they're used.
> 4 votes

---
Tags: c++, shaders, graphics, directx11, lighting
---


# Question
Title: Armature rest matrix - why does this exist?
I'm not sure I have a clear idea on what purpose the rest matrix/bindpose is supposed to serve in skeleton animation. If it is supposed to transform a bone into the rest pose and the mesh itself is always exported in the rest pose then shouldn't the rest matrix always be the identity matrix? But then why is it not the identity matrix in Blender?

I also find that if I transform my mesh (exported in the rest pose) by the rest matrix for each bone then it is very incorrectly deformed (it was after all already in the rest pose).

# Answer
> 2 votes
It's the transformation between the bone's local space and the whole mesh's object space. In other words, it goes from a coordinate system that has its origin at the joint location and its axes aligned with the bone, to the coordinate system for the whole mesh. (Or maybe it goes the other direction, depending on how it's defined exactly.)

This is necessary because in order to deform a bone to a new pose, you would multiply the inverse bind pose transformation (that goes from bind pose to the bone's local space) with the matrix defining the desired pose (that goes from the bone's local space to the desired pose). The resulting matrix takes vertices directly from the bind pose to the new pose.

---
Tags: graphics-programming, 3d-meshes, skeletal-animation
---


# Question
Title: Stacking items, c# XNA: When item reaches maximum stack, new items added are also maximum stack
haven't used this site before so I'm sorry if I format my post badly.

I am trying to build a stackable inventory for my game in c# XNA and the problem I've encountered is when an item in my inventory reaches the maximum stackable count (10) and creates a second instance of the item in the second slot of my inventory the second instance retains the count value of the first item.

So 10 items in my inventory have a value of 10 in the first slot, but 11 items will have a value of 10 in slot 1 and 10 in slot 2

4 pictures illustrating my problem: https://i.stack.imgur.com/FPxU9.jpg

```
class Backpack
{
         // 25 Inventory Slots
    public int itemMax = 25;
    public List<Items> ItemList = new List<Items>();
    int end = 1;

         //Funtction to add new items
    public void Add(Items newItem)
    {

        if (ItemList.Count <= itemMax)
        {

               //this if statement makes a list item add if the list.count is zero
            if (ItemList.Count < end)
            {
                ItemList.Add(newItem);
            }

            for (int x = 0; x < ItemList.Count; x++)
            {

                if (ItemList[x].nameID == newItem.nameID)
                {
                        //Checks for stackable item and less than 10 counts of item
                    if (ItemList[x].isStackable && ItemList[x].Count < 10)
                    {

                        ItemList[x].Count += 1;
                        break;
                    }
                    else
                    {
                        ItemList.Add(newItem);

                        end += 1;
                        break;
                    }
                }
                else
                {
                    ItemList.Add(newItem);
                    end += 1;
                }
            }

```

EDIT for floAr - I access the function like this:

```
        Items i;
        i = new Items();

        i.nameID = 1;
        i.Name = "Hog Meat";
        i.Item = ItemClass.Useable;
        i.Description = "Regenerates 30% hunger.";
        i.isStackable = true;
        i.Image = Content.Load<Texture2D>("hogmeat");
        i.sRect = new Rectangle(0, 0, 16, 16);

       backpack.Add(i);

```

# Answer
> 0 votes
I created a minimal test project to test your solution. The problem with the 2nd stack having a count of 10 is related to some reference and value passing mistakes. There are plenty of resources about this topic online (search for 'pass by value vs pass by reference c#')

However I discovered a new bug :) When the first stack is full, the backpack always created new stacks with count 1, as you don´t check if the second stack still has room:

```
else
{
    ItemList.Add(newItem);
    end += 1;
    break;
}

```

But here is my testing configuration (Console Application): Program.cs (Main class):

```
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Backpack b = new Backpack();
            for (int i = 0; i < 15; i++)
            {
                b.Add(new Items() { nameID = "myItem", isStackable = true, Count = 1 });
            }
            Console.Read();
        }
    }
}

```

Just creating a backpack an passing 15 NEW items to it. Backpack.cs is the one taken from here.

And a simple Items.cs stub, just with the necessary Properties:

```
namespace ConsoleApplication1
{
    class Items
    {
        public object nameID { get; set; }

        public bool isStackable { get; set; }

        public int Count { get; set; }
    }
}

```

If I run this and inspect the backpack after the for loop, it contains 1 stack with count 10 and 5 stacks with count 1.

Try to check if you are actually generating Items with the new keyword, this should fix your first error

Feel free to comment as soon as new questions arise!

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