title: Generating a grid of cubes in 3D space

text:
# Question
Title: Generating a grid of cubes in 3D space
I am trying to generate a grid of cubes in 3D space and It aint workin...

All im doing is for looping YXZ (in that order) (nested for loops) then im doing cubes\[x\]\[y\]\[z\] = ... (new Location(x,y,z))

But when I render them they are in this weird line that curves every X cubes... What am I doing wrong?

RENDERING:

```
public void render() {
    Cube[][][] temp = testchunk.getCubes();
    for (int z = 0; z<temp[0].length;z++) {
        for (int y = 0; y<temp[0][0].length; y++) {
            for (int x = 0; x<temp.length; x++) {
                Cube b = temp[x][z][y];
                if (b != null) {
                    GL11.glTranslatef(b.getPosition().x, b.getPosition().y, b.getPosition().z);
                    GL11.glCallList(cubes.get(b.getCubeId()));
                }
            }
        }
    }

}

```

GENERATING:

```
    for (int z = 0; z<cubes[0].length;z++) {
        for (int y = 0; y<cubes[0][0].length; y++) {
            for (int x = 0; x<cubes.length; x++) {
                cubes[x][z][y] = (Cube.dirt.getInstance()).setPosition(new Vector3f(position.x+(x*Cube.CUBE_SIZE),position.z+(z*Cube.CUBE_SIZE),position.y+(y*Cube.CUBE_SIZE)));
            }
        }
    }

```

# Answer
> 5 votes
You aren't resetting the modelview matrix, so each cube's translation is added to all further cubes. Use glPushMatrix and glPopMatrix around each translate-and-call.

---
Tags: java, 3d, procedural-generation, lwjgl, voxels
---


# Question
Title: MonoGame and normal windowed desktop application
I am trying to move all my XNA projects to Monogame. But in project templates I found only XAML and horrible metro application template. Is MonoGame support creating application in good old windowed mode for Windows 8? If yes how?

# Answer
> 2 votes
I'm not sure what your issue is.

MonoGame (as of 3.0's beta) adds a bunch of template projects to VS2010, including **MonoGame Application for Windows**. It runs by default as a windowed application, albeit a console one (so it creates a console window too) -- which is eeasily remedied.

**Edit:** I didn't realize you're asking about Windows 8 specifically. When you install the MonoGame 3.0 (beta), you'll find the Windows 8 assembly you probably need in `%program files%\MonoGame\v3.0\Assemblies\Windows8`. As of today (3.0 beta), you probably only need to add a reference to `MonoGame.Framework.Windows8.dll`

# Answer
> 0 votes
MonoGame.Framework.Windows8.dll is for Windows Metro, so basically for good old desktop-mode games, you have to use MonoGame.Framework.Windows.dll.

# Answer
> 0 votes
For plain old windows desktop you can simply use XNA, as it is mostly the same as monogame. Also Monogame uses opengl, as i expirienced much troubles with it on windows 7 desktop

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


# Question
Title: Weird rendering issue when applying lightmap through HLSL
I have a weird issue when trying to render the lightmaps in my game.

Please see the following screenshots.

Note how the scene looks up close with the lightmaps enabled.

Note how that same part of the scene is now completely blacked out (as well as its surroundings) - this happens gradually as you zoom out.

When I completely disable the lightmap, nothing is blacked out, making me believe its related to the way I apply it with HLSL.

Here's how I my Pixel Shader code looks like:

```
float4 PS1(VSO input) : COLOR
{
    float4 albedo = (HasAlbedo) ? tex2D(AlbedoSampler, input.UV) * input.Color : input.Color;
    float4 lightmap = (HasLightMap) ? tex2D(LightMapSampler, input.LightMapUV) : float4(1, 1, 1, 1);

    float4 finalColor = float4(albedo.xyz * lightmap.xyz, 1.0f);

    return (HasFog) ? input.FogFactor * finalColor + (1.0 - input.FogFactor) * FogColor : finalColor;
}

```

Am I doing something wrong in my HLSL? Or is it most likely something else?

For some additional information:

* I use SharpDX in combination with C#.
* The assets in the screenshots come from the game "Medal of Honor Allied Assault", so my sincere apologies for the Swastika signs if it offends anyone. This scene just happened to show the issue perfectly.

# Answer
> 0 votes
I fixed the issue myself!

After some more testing I found out that even if the lightmap would make the full scene overbright (just like it would when it was forcefully disabled in the HLSL), it still generated black shadows.

Because of this discovery I went back to my texture declaration:

```
LightMaps[i] = new Texture(GameHelper.Device, BSPFile.LIGHTMAP_SIZE, BSPFile.LIGHTMAP_SIZE, 0, Usage.None, Format.A8R8G8B8, Pool.Managed);

```

I started fiddling what made most sense to me, which was the LevelCount. After setting it to 1, rather than 0, the issue resolved itself!

After Googling I found out what the LevelCount actually does and by setting it to 1, I disable a hardware feature where downscaled versions of same texture get generated and shown based on the distance between the surface of that texture and the camera. It now totally makes sense why this messes things up.

---
Tags: rendering, hlsl, fragment-shader, sharpdx, lightmap
---


# Question
Title: What has the most efficient intersection test against an AABB tree - OBB, Cylinder or Capsule?
I'm currently trying to find collisions in 3D between a tighter volume than an AABB and a tree of AABB volumes. I just need to know whether they are intersecting, no closest distance or collision response. An OBB, Cylinder or Capsule would all roughly fit these purposes but Cylinder and Capsule were the first thing I thought of, which I have found little information about detecting intersections online. Am I right in thinking that they would always be more complex to perform Separating Axis Tests on even though they might seem like simpler shapes? I figure by the time I get my head around SAT for curved shapes I could have done the thing with OBBs but I wanted to find out for sure.

# Answer
> 2 votes
Little bit of necromancy here, but somehow it came back to the top of the list already today, and while a comment covers the idea, there aren't any actual answers yet. For the benefit of future readers:

The idea behind using an Axis Aligned Bounding Box, or in the 3D case a bounding cube, is that you can quickly disqualify some number of your potential collisions through a series of relatively cheap comparisons to the effect of `if(A.top < B.bottom) continue;`

The (hopefully) much smaller set of objects that pass the AABB collision test may then go on to more accurate, but computationally expensive checks. In my experience, the time you save by quickly disqualifying the obvious non-collisions will "almost always"(tm) be greater than the time you "waste" by testing some objects twice. "Usually"(tm) it is significantly greater.

---

For the super serious out there, use of "quotes"(tm) indicates evidence which is, at best, anecdotal, and should not be taken as The Final Word. Special cases abound. If you think you have one, profile it and find out if you're right.

# Answer
> 0 votes
For OBB to cylinder tests, you can use an OBB to line-segment/ray test and expand the OBB by the radius of the cylinder. This produces slight error in the corners but if you can suffer that little bit of accuracy loss, it is a pretty fast and simple way.

In Christer Ericson's book, "Real Time Collision Detection", He details how to test a line or ray against 3 slabs that intersect at the OBB. The OBB is simply a Matrix & 3 half-widths which are used to create the 3 slabs. If the line segment intersects all 3 slabs, you have a collision.

For a cylinder, when you expand the OBB, you expand each slab differently depending on the dot product of the line/ray to face normal times the radius... but for a capsule, you expand all 3 slabs by the radius.

EDIT. Of course, after re-reading your question, I thought your question was less general that it is. Sorry if I gave a mis-directed answer.

---
Tags: c++, 3d, collision-detection, aabb
---


# Question
Title: Unity3D How to write to the back buffer AFTER the final pass of deferred rendering?
I've been using this script and shader from the wiki, and they work wonders; my only problem is using them in deferred rendering.

Now, the way this shader works is by writing to the depth buffer to hide anything behind an object with this shader applied, but for some reason this wasn't working when I tried to use deferred rendering for shadows and better lighting. The problem is addressed by Kuba in the final post of this topic.

The final pass of prepass rendering (the part that renders geometry the second time and applies the result of the lighting pass to it) is rendered in to a texture, then blit-copied into the back buffer, which overrides everything that was rendered there before.

My question is if there is any way to render after that final pass, so I can still use my depth mask to hide objects behind it. If there is no way to directly write after the final pass, is there another solution I can try? Perhaps blending the two cameras on my own and some how blitting that on to the screen?

# Answer
> 0 votes
I actually got it working with this shader, this works on everything with the scene, no need for setting any render queues.

I made this in Strumpy Shader Editor, seeing as I don't have too much shader writing experience. All I had to do was turn off the RGBA on the color mask, set render queue to Geometry -10, and check the advanced shadows pass box (which adds in the bit below that renders after the final pass.)

```
 Shader "DepthMask/Mask"
{
    Properties
    {

    }

    SubShader
    {
        Tags
        {
"Queue"="Geometry-10"
"IgnoreProjector"="False"
"RenderType"="Opaque"

        }

Cull Back
ZWrite On
ZTest LEqual
ColorMask 0
Fog{
}

        CGPROGRAM
#pragma surface surf BlinnPhongEditor  addshadow vertex:vert
#pragma target 2.0

            struct EditorSurfaceOutput {
                half3 Albedo;
                half3 Normal;
                half3 Emission;
                half3 Gloss;
                half Specular;
                half Alpha;
                half4 Custom;
            };

            inline half4 LightingBlinnPhongEditor_PrePass (EditorSurfaceOutput s, half4 light)
            {
half3 spec = light.a * s.Gloss;
half4 c;
c.rgb = (s.Albedo * light.rgb + light.rgb * spec);
c.a = s.Alpha;
return c;

            }

            inline half4 LightingBlinnPhongEditor (EditorSurfaceOutput s, half3 lightDir, half3 viewDir, half atten)
            {
                half3 h = normalize (lightDir + viewDir);

                half diff = max (0, dot ( lightDir, s.Normal ));

                float nh = max (0, dot (s.Normal, h));
                float spec = pow (nh, s.Specular*128.0);

                half4 res;
                res.rgb = _LightColor0.rgb * diff;
                res.w = spec * Luminance (_LightColor0.rgb);
                res *= atten * 2.0;

                return LightingBlinnPhongEditor_PrePass( s, res );
            }

            struct Input {
                float4 color : COLOR;

            };

            void vert (inout appdata_full v, out Input o) {
float4 VertexOutputMaster0_0_NoInput = float4(0,0,0,0);
float4 VertexOutputMaster0_1_NoInput = float4(0,0,0,0);
float4 VertexOutputMaster0_2_NoInput = float4(0,0,0,0);
float4 VertexOutputMaster0_3_NoInput = float4(0,0,0,0);

            }

            void surf (Input IN, inout EditorSurfaceOutput o) {
                o.Normal = float3(0.0,0.0,1.0);
                o.Alpha = 1.0;
                o.Albedo = 0.0;
                o.Emission = 0.0;
                o.Gloss = 0.0;
                o.Specular = 0.0;
                o.Custom = 0.0;

float4 Master0_0_NoInput = float4(0,0,0,0);
float4 Master0_1_NoInput = float4(0,0,1,1);
float4 Master0_2_NoInput = float4(0,0,0,0);
float4 Master0_3_NoInput = float4(0,0,0,0);
float4 Master0_4_NoInput = float4(0,0,0,0);
float4 Master0_5_NoInput = float4(1,1,1,1);
float4 Master0_7_NoInput = float4(0,0,0,0);
float4 Master0_6_NoInput = float4(1,1,1,1);

                o.Normal = normalize(o.Normal);
            }
        ENDCG
    }
    Fallback "Diffuse"
}

```

---
Tags: c#, unity, deferred-rendering
---


# Question
Title: Issues with Sine Wave Generation and Rotation
I'm working on generating objects in sine wave that lets you specify parameters that are start x, end x, start y, and end y position.

Below is the method that I used to generate the debris

```
void generateWaveDebris(float startX, float endX, float startY, float endY, int numberToGenerate, bool randomizeDebrisDirection = false, bool randomizeDebrisFallSpeed = false, int[] numbersToSkip = null) {
    float totalXDistance = endX - startX;
    float xPositionOffset = 0f;
    float xStepSizeForGeneration = totalXDistance/numberToGenerate;
    xPositionOffset += xStepSizeForGeneration/2;

    float totalYDistance = endY - startY;
    float yPositionOffset = 0f;
    float yStepSizeForGeneration = totalYDistance/numberToGenerate;
    yPositionOffset += yStepSizeForGeneration/2;

    int generatedDebrisTracker = 0;

    float debrisRotation = 0;
    float debrisRotationSpeed = Random.Range(debrisImageRotationSpeedMin, debrisImageRotationSpeedMax);
    float debrisFallSpeed = Random.Range(debrisFallSpeedMin, debrisFallSpeedMax);

    bool skipThisDebris = false;

    Vector3 newPosition = Vector3.zero;
    newPosition.z = defaultGeneratedDebrisZPosition;
    while(generatedDebrisTracker < numberToGenerate) {

        if(numbersToSkip != null) {
            foreach(int number in numbersToSkip) {
                if(generatedDebrisTracker == number) {
                    skipThisDebris = true;
                }
            }
        }

        // X Tracking ----------------
        newPosition.x = startX + xPositionOffset;
        xPositionOffset += xStepSizeForGeneration;
        //----------------

        // Y Tracking ----------------
        newPosition.y = startY + yPositionOffset;
        yPositionOffset += yStepSizeForGeneration;
        //----------------

        float tempX = newPosition.x;
        float tempY = newPosition.y;

        newPosition.x += Mathf.Sin(normalizeValue(tempY, startY, endY, 0f, 359.9f)) * 5;
        newPosition.y += Mathf.Cos(normalizeValue(tempX, startX, endX, 0f, 359.9f)) * 5;

        if(!skipThisDebris) {
            GameObject newDebris = null;
            newDebris = generateRandomDebris(newPosition);

            if(newDebris != null) {
                Debris newDebrisReference;
                newDebrisReference = newDebris.GetComponent<Debris>();

                newDebrisReference.defaultObjectZRotation = 0;

                //This will randomize the direction that the debris falls in if
                //it is set to true when the method is called
                if(randomizeDebrisDirection) {
                    newDebrisReference.defaultObjectZRotation = Random.Range(debrisRotationMin, debrisRotationMax);
                }
                else {
                    newDebrisReference.defaultObjectZRotation = debrisRotation;
                }
                //This will randomize the fall speed of the debris if
                //it is set to true when the method is called
                if(randomizeDebrisFallSpeed) {
                    newDebrisReference.fallSpeed = Random.Range(debrisFallSpeedMin, debrisFallSpeedMax);
                }
                else {
                    newDebrisReference.fallSpeed = debrisFallSpeed;
                }

                newDebrisReference.rotationSpeed = debrisRotationSpeed;

                newDebris.transform.parent = transform;
            }
        }
        //-----------------------------
        generatedDebrisTracker += 1;

        //Resets for next loop
        skipThisDebris = false;
    }
}

```

It's important to note that the sections that matter are the lines:

```
newPosition.x += Mathf.Sin(normalizeValue(tempY, startY, endY, 0f, 359.9f)) * 5;
newPosition.y += Mathf.Cos(normalizeValue(tempX, startX, endX, 0f, 359.9f)) * 5;

```

When the line's start x and end x are the same, the wave generates fine. However when the line is diagonal it gets all sorts of messed up.

I know that there are ways to generate a sin wave and then use a linear transformation matrix to rotate it, however I've had a ton of issues getting that going, and it doesn't resolve one of my requirements where I specify the start x, end x, start y, and end y. This is because when the linear transformation rotation matrix is applied it doesn't keep the line scaled to the points I want.

So my question is: Is there a way to make a sine wave that can be oriented in any rotation, as well as specifying its start and end points for the x and y values?

If there is any more information I can provide, or anything I can do to help facilitate answers I would be more than happy to provide it.

# Answer
> 6 votes
There are a number of ways to do this, which end up being equivalent, but I'll explain how to do it in terms of basic vectors.

(By the way, I *strongly* recommend that you stop using paired 'x' and 'y' numeric variables and start using vectors for everything; it makes many things easier to express, and reduces the chance of making a mistake.)

Conceptually, we start with a line from the start point to the end point, break it up into segments, and then displace the points of the segments according to a sine function. I'm going to write an example in JavaScript and write my own vector functions, but it should be easy to translate.

A key point to note: I've written this code in terms of 2D vectors, but the basic algorithm is completely generic and will work equally well with 3D vectors. This is one of the key advantages of working with vectors: the code is designed to generate a wave in a 2D plane, and doesn't care how many extra dimensions it's not looking at there might be.

First, the setup:

```
<title>Sine Wave Demo</title>
<body style='margin: 0;'>
<canvas id='c' width='400' height='400'></canvas>
<script>
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');

```

Vector functions — you should find equivalents to all of these in Unity's vector libraries.

```
function vmul(s, a) { return [s*a[0], s*a[1]]; }
function vadd(a, b) { return [a[0] + b[0], a[1] + b[1]]; }
function vsub(a, b) { return [a[0] - b[0], a[1] - b[1]]; }
function vlength(a) { return Math.sqrt(a[0]*a[0] + a[1]*a[1]); }
function vnormalize(a) { return vmul(1/vlength(a), a); }

```

`vrotate` is a little tricky: it is a shortcut to rotate a *2D* vector by 90 degrees. If you're working in 3D vectors, then you'll probably use a "rotate about the Z axis" function instead. It doesn't matter how you do it as long as the resulting vector is perpendicular to the input (if it isn't, the wave will be skewed, which might be an interesting effect).

```
function vrotate(a) { return [a[1], -a[0]]; }

```

Now the actual algorithm. `start` is the start point of the wave, `end` the ending point (both vectors). `amplitude` is the amplitude of the wave: the maximum distance away from the center-line it reaches. `numPoints` is the number of points to generate. `numWaves` is the number of repetitions of the sine wave (I think your code has this at `1`).

```
function drawSine(start, end, amplitude, numPoints, numWaves) {

```

`displacement` is the vector from the beginning to the end, independent of location.

```
  var displacement = vsub(end, start);

```

We will want to use the length of it.

```
  var length = vlength(displacement);

```

`parallel` is a *unit* vector (vector of length 1) in the same direction. This gives us the basis for computing points along the wave.

```
  var parallel = vnormalize(displacement);

```

`perpendicular` is the key ingredient you didn't have: it points perpendicular to the line between the start and end points, and is what we use to displace the points according to the sine function.

(Linear algebra side note: If you combine `parallel` and `perpendicular` as the *columns of a matrix*, then that matrix is the transformation matrix of a rotation matching the orientation of the line!)

```
  var perpendicular = vrotate(parallel);

```

These will be explained later.

```
  var distanceScale = length / (numPoints - 1);
  var sineScale = 2 * Math.PI * numWaves / numPoints;

```

```
  for (var i = 0; i < numPoints; i++) {

```

Compute the appropriate sine function. `sineScale` was defined to make `numWaves` full cycles (`2 * Math.PI`) when `numPoints` reaches its limit.

```
    var sineValue = amplitude * Math.sin(i * sineScale);

```

`pointOnLine` is a point which is at step `i` along the straight line between `start` and `end`. This is just like linear interpolation in disguise. `distanceScale` was divided by `numPoints - 1` so that the last loop iteration, where `i == numPoints - 1`, hits the end point exactly.

```
    var pointOnLine = vadd(start, vmul(i * distanceScale, parallel));

```

Here's the key part: `pointOnSine` is moved away from `pointOnLine` *perpendicularly to the line* according to the sine function.

```
    var pointOnSine = vadd(pointOnLine, vmul(sineValue, perpendicular));

```

Now draw something. In your application you'd create the debris object instead, here.

```
    ctx.fillText('x', pointOnSine[0], pointOnSine[1]);
  }
}

```

Some additional code to demonstrate; move your mouse around to see the wave change.

```
var target = [400, 400];
function go() {
  drawSine([10, 10], target, 30, 70, 2.5);
}
window.addEventListener('mousemove', function(e) {
  target[0] = e.clientX;
  target[1] = e.clientY;
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  go();
});
function size() {
  canvas.width = document.body.offsetWidth;
  canvas.height = document.body.offsetHeight;
  go();
}
size();
</script>

```

Here's all of the above code collected so you can actually run it:

```
<title>Sine Wave Demo</title>
<body style='margin: 0;'>
<canvas id='c' width='400' height='400'></canvas>
<script>
function vmul(s, a) { return [s*a[0], s*a[1]]; }
function vadd(a, b) { return [a[0] + b[0], a[1] + b[1]]; }
function vsub(a, b) { return [a[0] - b[0], a[1] - b[1]]; }
function vlength(a) { return Math.sqrt(a[0]*a[0] + a[1]*a[1]); }
function vnormalize(a) { return vmul(1/vlength(a), a); }
function vrotate(a) { return [a[1], -a[0]]; }

var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');

function drawSine(start, end, amplitude, numPoints, numWaves) {
  var displacement = vsub(end, start);
  var length = vlength(displacement);
  var parallel = vnormalize(displacement);
  var perpendicular = vrotate(parallel);
  var distanceScale = length / (numPoints - 1);
  var sineScale = 2 * Math.PI * numWaves / numPoints;
  for (var i = 0; i < numPoints; i++) {
    var sineValue = amplitude * Math.sin(i * sineScale);
    var pointOnLine = vadd(start, vmul(i * distanceScale, parallel));
    var pointOnSine = vadd(pointOnLine, vmul(sineValue, perpendicular));
    ctx.fillText('x', pointOnSine[0], pointOnSine[1]);
  }
}

var target = [400, 400];
function go() {
  drawSine([10, 10], target, 30, 70, 2.5);
}
window.addEventListener('mousemove', function(e) {
  target[0] = e.clientX;
  target[1] = e.clientY;
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  go();
});
function size() {
  canvas.width = document.body.offsetWidth;
  canvas.height = document.body.offsetHeight;
  go();
}
size();
</script>
```

---
Tags: 2d, unity, geometry
---


title: Multiple Key Presses in XNA?

text:
# Question
Title: Multiple Key Presses in XNA?
I'm actually trying to do something fairly simple.

I cannot get multiple key presses to work in XNA. I've tried the following pieces of code.

```
else if (keyboardState.IsKeyDown(Keys.Down) && (keyboardState.IsKeyDown(Keys.Left)))
{
      //Move Character South-West
}

```

and I tried.

```
else if (keyboardState.IsKeyDown(Keys.Down))
            {
                if (keyboardState.IsKeyDown(Keys.Left))
                {
                      //Move Character South-West
                }
            }

```

Neither worked for me. Single presses work just fine. Any thoughts?

# Answer
> 7 votes
Use GetPressedKeys() to get all of the currently pressed keys and iterate through them doing what you want.

If you're moving the player or something, create an initial Vector3 at the beginning and add modifier values to it and add it to the player position after the input checking has completed.

Something like this:

```
Vector3 positionToAdd = Vector3.Zero;
Keys[] currentPressedKeys = currentKeyboardState.GetPressedKeys();
foreach( Keys key in currentPressedKeys )
{
    if( key == Keys.W )
        positionToAdd += Vector3( 0.0f, 1.0f, 0.0f );

    if( key == Keys.S )
        positionToAdd += Vector3( 0.0f, -1.0f, 0.0f );

    if( key == Keys.A )
        positionToAdd += Vector3( -1.0f, 0.0f, 0.0f );

    if( key == Keys.D )
        positionToAdd += Vector3( 1.0f, 0.0f, 0.0f );
}

player.Position += positionToAdd;

```

Personally, I don't do this, I just use if statements WITHOUT the else to make sure program flow isn't being disrupted unintentionally.

Ray

# Answer
> 9 votes
The code in your question is fine. The problem must be in the code above it, perhaps you are doing something like this:

```
// ...
if (ks.IsKeyDown(Keys.Down)) { /* ... */ }
else if (ks.IsKeyDown(Keys.Down) && (ks.IsKeyDown(Keys.Left))) { /* ... */ }
// ...

```

In which case the first condition will trigger and the second will not (due to `else`).

Here is how to do 2D input using the keyboard:

```
Vector2 direction = Vector2.Zero;
if(ks.IsKeyDown(Keys.Up)) direction += new Vector2(0, 1);
if(ks.IsKeyDown(Keys.Down)) direction += new Vector2(0, -1);
if(ks.IsKeyDown(Keys.Left)) direction += new Vector2(-1, 0);
if(ks.IsKeyDown(Keys.Right)) direction += new Vector2(1, 0);

// Optional: make sure direction is always of unit length (prevents straferunning)
if(direction.LengthSquared() > 1f) direction.Normalize();

```

Personally I'd *avoid* using `GetPressedKeys()`, because it allocates memory every time you call it. Probably not enough to be a performance issues on Windows, but it will be if you ever port to Xbox 360. It exists to support "press any key" scenarios only.

# Answer
> 1 votes
Your else if statements could be interfering with the program flow. Try restructuring your code, or setting bit flags for each key pressed. Or perhaps your keyboard doesn't support some keys simultaneosly pressed (happens to my old laptop).

# Answer
> 0 votes
I had the same problem when I used the arrows keys in conjunction with the space bar on my pc. I changed the arrow keys to WASD and the problem went away.

---
Tags: xna, events, keyboard, objects, movement
---


title: 2D Scrolling Background on XNA

text:
# Question
Title: 2D Scrolling Background on XNA
How do I create a scrolling X and scrolling Y background without weird things happening like the player disappearing or not getting the offset correct?

I have code at https://vanillity.kilnhg.com/Code/Repositories/Group/Aremac

Looks like this:

```
      var s = game.gd.Viewport.Bounds;
      var g = game.world.Bounds;
      var p = game.player.Bounds;
      var v = viewRectangle;

      var x = p.X  0 ? p.X - s.Width/2 :
              v.Right >= 1090 ?  90 :
              p.X > s.Width/2    ? p.X - s.Width/2 :
              0;

      var y = //v.Bottom >
              p.Y > s.Height/2 ? p.Y - s.Height/2:
              0;

      var w = s.Width;
      var h = s.Height;

      //view Rectangle
      Offset        = new Vector2(x , y);
      viewRectangle = new Rectangle( x, y ,w, h);

```

and then:

```
     //source rectangle
     var x = (int)0;
     var y = (int)0;
     var g = game.world.Bounds;
     var w = g.Width;
     var h = g.Height;
     var rect =  new Rectangle(x,y,w,h);

      spriteBatch.Draw(  w.boundsTexture
                        ,rect
                        ,viewRectangle
                        ,w.Color
                        ,0
                        ,Vector2.Zero
                        ,SpriteEffects.None
                        ,1
                        );

```

Before center, the grey guy is holding the rock in his left hand:

After center, the rock (and the white guy) drifts evermore to the right:

# Answer
> 3 votes
Rewrite this statement in a more readable fashion:

```
var x = p.X > v.Width     ? p.X - v.X/2:
          p.X > s.Width/2   ? p.X - s.Width/2 :
          0;

```

And your problem is solved.

```
if p.X > v.Width then
    x = p.x - v.x/2;
else
    if p.x > s.width/2 then
        x = p.x - s.width/2;
    else
        x=0;

```

Also, your viewRect should never have it's width or height changing. You seem to be trying to over complicate things.

You need a viewport offset for X and Y. You need a player position. The viewport offset is p.offset - viewport.size / 2 The viewport has a size.

You then want to draw from viewport offset (maybe - 1) to viewport offset + viewport size.

---
Tags: xna, 2d
---


# Question
Title: Trying to reduce health by a certain value once XNA
I've got a bullet and collision data for the bullet, when the bullet collides, it's supposed to cut an integer off of the max health for the object.

Basically heres what I want:

Object is shot, Object health = Object Health - 35

What I put in the code:

```
        if (game.bullet.BoundingBox.Intersects(game.temko.BoundingBox))
        {
            shotM1911 = true;
            game.bullet.Bullet = false;

        }

        if (shotM1911 == true && gameTime.ElapsedGameTime.Milliseconds == 3)
        {
            shotM1911 = false;

        }

        if (shotM1911 == true)
        {
            game.temko.temkohealth = game.temko.temkohealth - game.bullet.bulletdamage;
        }

```

I *think* its just updating too fast for the bullet to call it false again (resulting in the temkos measly 200 health to hit negative numbers real fast) how to I tell it to subtract 35 only *once* upon collision (and get ready to do it again when shot.

# Answer
In most games, bullets are removed from the game once they hit something, so they don't have this problem.

There are two situations where this problem crops up:

1. When bullets can hit many different objects at different times. Maybe the bullet travels through objects to hit more objects behind it; maybe the bullet bounces around and hits anything in its path
2. When bullets stick around and deal damage depending on how long an object is touching/intersecting it, such as a fireball or laser beam

Depending on which of the two (or both) applies, you can use several techniques:

* Add a "grace period/distance" for the bullet once it hits an object, during which it cannot hit any objects. After every collision, record the time and/or location of the collision, and don't let it collide again until enough time has passed or enough distance has been travelled. This is easy to implement but doesn't work well for a lot of edge cases, such as if your bullet will bounce many times in a short time or distance.
* If damage is a function of how long the bullet was "in collision", calculate collisions at fixed game time intervals, and calculate damage based on the number of intervals the bullet was "in collision". The downside is that you need to have a good understanding and control over your game loop to pull this off.
* If bullets can hit many objects but only once each, for every bullet remember which objects it has collided with so far. This is also very easy to implement, but may not scale well with the number of bullets/objects and collisions.
> 2 votes

# Answer
You are assuming that each frame will take exactly 3 milliseconds to execute, but if it's less or higher then it will continue to chip away the health.

Additionally you are not using a cumulative value for the elapsed time but instead using the one in ElapsedTime instance which will only relay the time elapsed since the last frame.

```
var isInvulnerable = false;
var milliseconds = 0;
...

if (game.bullet.BoundingBox.Intersects(game.temko.BoundingBox) && !isInvulnerable)
{
    shotM1911 = true;
    game.bullet.Bullet = false;
    game.temko.temkohealth = game.temko.temkohealth - game.bullet.bulletdamage;
    isInvulnerable = true;
    milliseconds = 0;
}

if (isInvulnerable)
{
    milliseconds += gameTime.ElapsedGameTime.Milliseconds;

    if (milliseconds > 3)
    {
        isInvulnerable = false;
    }
}

```
> 1 votes

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


# Question
Title: Are there tutorials which teach you to paint textures for 3d model UV maps in photoshop?
Are there tutorials out there which show how to paint textures for models in photoshop with their UV maps? I already have 4 years experience with modeling in 3ds max and I'm dying to learn how to paint textures for my models. U have photoshop with me but the problem is i don't know how to start or how my textures should look like.

For example this is a model that I'd like to practice painting textures for but it is too bland:

I'm currently using plain 3ds max mental ray materials for it right now but it just looks too bland and plain and I'd like to make more stylised like the following:

# Answer
The first thing you need to learn is UVW mapping get a complete grasp of how this works and you will start to understand how your texture maps should be structured.

This is a good tutorial that should explain all this - http://waylon-art.com/uvw\_tutorial/uvwtut\_01.html

Then you should try texturing, using your Photoshop skills to apply textures and paint to your model. Experimenting and practice is the key to this.

But in saying this, I would recommend practising on a simpler object just as a cube (make an awesome wooden crate) or a barrel etc.. This will help you before tackling a full mech, which will be more challenging.

Moreover, that looks to be a high-resolution model, and thus would need normal mapping, which involves creating a low resolution or game model, to which the high res information is baked onto a normal map - this is a more advanced process and equally requires a whole new level of information.

I recommend this tutorial http://wiki.polycount.com/NormalMap?action=show&redirect=Normal+Map

(also in that Wiki there are loads of other great tutorials as well as the forum its self which is a great place for feedback and inspiration)

Good luck!
> 3 votes

---
Tags: 3dsmax
---


# Question
Title: poor performance with kinect sdk and xna (color stream)
I'm trying to make an augmented reality game for advertisement, using the kinect sdk 1.6 and xna 4.0. I need to use the color image format rgb 1280X960, in spite of the fact that it runs at 12fps, because the quality of the image is important for this project. The problem is that when I call the function to build a color image frame, the fps of the game drops a lot. When I use only skeleton frame information to build a game scene, it runs at 50/60 fps, but when I call the function for the color frame the frames drop to 10/14 fps. The purpose of this function is the transformation of the stream to bgra format. If I comment out this loop, I get 30/40 fps. Is there any other way to make this more efficient?

```
public Texture2D Video()
{
   try
   {
      if (video == null)
        video = new Texture2D(gd, Sensor.ColorStream.FrameWidth, Sensor.ColorStream.FrameHeight);

      ColorImageFrame framecolor = Sensor.ColorStream.OpenNextFrame(100);

      if (framecolor != null)
      {
        byte[] bgraPixelData = new byte[framecolor.PixelDataLength];
        framecolor.CopyPixelDataTo(bgraPixelData);

        //Convert RGBA to BGRA
        byte[] colorbuffer = new byte[framecolor.PixelDataLength];

        for (int i = 0; i < bgraPixelData.Length; i += 4)
        {
          colorbuffer[i] = bgraPixelData[i + 2];
          colorbuffer[i + 1] = bgraPixelData[i + 1];
          colorbuffer[i + 2] = bgraPixelData[i];
          colorbuffer[i + 3] = (byte)255; //The video comes with 0 alpha so it is transparent
        }

        video.SetData(colorbuffer);
      }

    }
    catch
    {
      video = null;
    }

    return video;
  }

```

# -----How do i ressolve it?

I finally decide to use a shader to make the gpu deal with the process of tranform between formats, as it was suggested by @Seth Battin. this is the shader:

```
sampler sprite : register(s0);

/*
 * Convert from BGRX to RGBA
 */
float4 BGR2RGB(float2 texCoord : TEXCOORD0) : COLOR0
{
    float4 tex = tex2D(sprite, texCoord);
    return float4(tex.b, tex.g, tex.r, 1.0);
}

technique KinectVideo
{
    pass KinectVideo
    {
        PixelShader = compile ps_2_0 BGR2RGB();
    }
}

```

and the code i used before, as it no longer need to make the transform, now looks like this:

```
public RenderTarget2D Video()
        {
            try
            {
                if (Sensor != null)
                {
                    if (Sensor.ColorStream != null)
                    {
                        using (var frame = Sensor.ColorStream.OpenNextFrame(0))
                        {
                            if (frame != null)
                            {
                                if (buffer == null || buffer.Length != frame.PixelDataLength)
                                {
                                    buffer = new byte[frame.PixelDataLength];
                                }

                                frame.CopyPixelDataTo(buffer);
                                //GraphicsDevice.Textures[0] = null;

                                videoframe.SetData<byte>(buffer);

                            }
                        }
                    }
                }
            }
            catch
            {
            }
            return videoframe;
        }

```

I know that the try/catch its expensive, but now i have a good rate of fps, and its woorking fine. After that, i just apply the shader in the draw call, like this:

```
                sb.Begin(SpriteSortMode.Texture, null, null, null, null, kinectcolorvisualizer);
                sb.Draw(video, pantalla, null, Color.White, 0, Vector2.Zero, SpriteEffects.None, 1);
                sb.End();

```

where "sb" is spritebatch, "kinectcolorvisualizer" is the shader and "video" is the RenderTarget2D returned by the video function

Thanks to @Seth Battin and to @Mustafa Karakuş for their help.

# Answer
1. Use no try/catch in performance sensitive loops. You need to track down the source of what could cause an error, and prevent it from happening. Throwing and catching an exception is an extremely expensive operation.
2. You are creating a `Texture2D`, and populating it from a stream. You could probably save some memory by not creating a new one for every call to your function.
3. You grab a set of data from a stream, and then swizzle it on the CPU. Why not do that in a shader, so the GPU can do what it does best? It could correct for the alpha problem, too.
> 5 votes

# Answer
Because of `SetData`, performance suffers a lot. `SetData` makes a transfer between GPU's ram and CPU's ram. Imagine doing this operation every frame. This causes performance issues.

I recommend using Task for seperating AllFramesReady method (in which you call your `Video` method). The images from kinect sensor may still be a bit laggy, but since they are not on the same thread anymore, game will not suffer that much performance issues. Like this:

```
Task.Factory.StartNew(() => checkFrameEvent());

.
.
.

private void checkFrameEvent()
{
    kinect.AllFramesReady += new EventHandler<AllFramesReadyEventArgs>(kinect_AllFramesReady);
}

```

I don't need to mention that the first line must be **before** starting kinect sensor.

I hope this helps.
> 1 votes

---
Tags: xna, performance, kinect
---


# Question
Title: How to remove text from a command line box?
I'm currently writting a text based game and am currently having a slight issue where all of the text on the screen keeps going up and have had a couple of the testers complaining that it makes the game appear messy and somewhat confusing.

The game is written in C++ as a command line game and I was wondering if anyone knows of anyway that I could clear the screen up without putting a lot of white space into the game as I personally think that isnt a very nice way of doing it. Just to note that this is in a windows environment.

Thanks for any response

# Answer
EDIT: After a comment by @ChristianIvicevic I felt compelled to reword my answer to emphasise that the Article link I provided is a far better alternative to using a system call as it is more secure and does not risk producing false positives with anti-virus software.

---

Try and use this Microsoft solution:

Performing Clear Screen (CLS) in a Console Application

A system function to call clear screen on your application can work too but carries the risk of producing errors with anti-virus software as it is a low-level system call.

```
#include <stdlib.h>

void main()
{
   system("cls");
}

```
> 6 votes

# Answer
In case you ever need it in the future: For even more control of the display in consoles and cross platform support take a look at the ncurses library: https://en.wikipedia.org/wiki/Ncurses

It is a bit of an overkill for just clearing the screen, though to my knowledge it is currently the only portable way, but it also allows for colors, menus etc. Essentially it allows you to use the console like a screen.
> 4 votes

# Answer
I would start the game from a Windows bat file. Before the bat file starts executing the program, configure the command prompt to the desired number of columns and lines. See these links for examples: http://www.computerhope.com/movehlp.htm or https://stackoverflow.com/questions/8688846/resize-command-prompt-through-commands
The relevant command is "mode con:cols=80 lines=100" You can pass the number of columns and lines into your C++ program as command line parameters and can use this information inside your program to help control how text is displayed, paginated, cleared, etc.
> 1 votes

---
Tags: c++, windows, console, text-based
---


# Question
Title: How to handle a player's level and its consequent privileges?
I'm building a game similar to Mafia Wars where a player can do tasks for his gang and gain experience and thus advancing his level.

The game is built using PHP and a Mysql database.

In the game I want to limit the resources allowed to player based on his level.

For example:

```
________| (Max gold) | (Max army size) | (Max moves)  | ...
Level 1 |    1000    |       100       |      10      | ...
Level 2 |    1500    |       200       |      20      | ...
Level 3 |    3000    |       300       |      25      | ...
  .
  .
  .

```

In addition certain features of the game won't be allowed until a certain level is reached such as players under Level 10 can't trade in the game market, players under Level 20 can't create alliances,...etc.

The way I have modeled it is by implementing a very loooong ACL (Access Control List) with about 100 entries (an entry for each level).

However, I think there may be a simpler approach to this seeing that this feature have been implemented in many games before.

# Answer
> 1 votes
I would recommend using some type of algorithm rather than an ACL:

Algorithm for dynamically calculating a level based on experience points?

https://gamedev.stackexchange.com/a/14314/20399

These aren't specific to your question, but the general principle is that there are formulas you can use to determine the requirements rather than hardcoding every possible outcome

---
Tags: game-design, software-engineering, game-mechanics, php, mysql
---


# Question
Title: Why is my model flickering when translating
I have several models here. When they stand still during gameTime, there's no flickering. But as soon as I move them across the x-axis, they flicker on some places.

```
protected override void Draw(GameTime gameTime)
{
    graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

    Matrix[] transforms = new Matrix[myModel.Bones.Count];
    myModel.CopyAbsoluteBoneTransformsTo(transforms);

    foreach (ModelMesh mesh in myModel.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.World = transforms[mesh.ParentBone.Index] *
                Matrix.CreateRotationY(modelRotation)
                * Matrix.CreateTranslation(modelPosition);
            effect.View = Matrix.CreateLookAt(cameraPosition,
                Vector3.Zero, Vector3.Up);
            effect.Projection = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.ToRadians(45.0f), aspectRatio,
                1.0f, 10000.0f);
        }
        mesh.Draw();
    }
    base.Draw(gameTime);
}

```

Why is that happening and what could I do to prevent it?

# Answer
Issue was easy to solve:

My `farPlane` was too much (actually 10k). So I reduced that to 3k (according to my models) and also important is the `nearPlane`, which was at `0.1f`. I changed that to `1` and now everything works!
> 1 votes

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


# Question
Title: Unity: Is there a way to edit a Skin file?
My project has multiple skins and sometimes we have to deal with skins with many custom styles. Editing them in the editor is difficult, for instance, I cannot delete one style that is not the last one without deleting the ones after it.

Would there be a way to edit a file that represents this skin?

Could I edit a skin file if I use Text in the Asset Serialization Mode (Unity Pro)?

If not, is there something in the Unity Store to help me better edit skins?

# Answer
Yes, using the text serialization (a flavor of YAML) will allow you to hand edit the gui.skin file (but you'll need to be incredibly careful). I think text asset serialization is available in the free version of Unity now.

You can also write an Editor script that iterates of the fields of the GUISkin.

Here's a script I wrote to merge multiple GUISkins into a single GUISkin with multiple custom styles: https://gist.github.com/2242083
> 2 votes

# Answer
You can simply delete styles by selecting them (click the foldable header line) and press the DEL-button ;) This is valid for all arrays viewed in the inspector. If the array hold references to other assets pressing delete will just "null" the element. In this case you have to use Shift+DEL.

You can also duplicate an element be pressing CTRL+D. This will duplicate the current element and insert it right below the original. You almost never need to adjust the size value manually since you can easily add and remove elements. The only thing that is missing is reordering the elements.
> 0 votes

---
Tags: unity
---


# Question
Title: OBJ model loaded in LWJGL has a black area with no texture
I have a problem with loading an .obj file in LWJGL and its textures. The object is a tree(it's a paid model from TurboSquid, so I can't post it here,but here's the link if you want to see how it should look like): http://www.turbosquid.com/FullPreview/Index.cfm/ID/701294

I wrote a custom OBJ loader using the LWJGL tutorial from their wiki. It looks like this:

```
public class OBJLoader {
public static Model loadModel(File f) throws FileNotFoundException, IOException
{
    BufferedReader reader = new BufferedReader(new FileReader(f));

    Model m = new Model();
    String line;
    Texture currentTexture = null;
    while((line=reader.readLine()) != null)
    {
        if(line.startsWith("v "))
        {
            float x = Float.valueOf(line.split(" ")[1]);
            float y = Float.valueOf(line.split(" ")[2]);
            float z = Float.valueOf(line.split(" ")[3]);
            m.verticies.add(new Vector3f(x,y,z));
        }else if(line.startsWith("vn "))
        {
            float x = Float.valueOf(line.split(" ")[1]);
            float y = Float.valueOf(line.split(" ")[2]);
            float z = Float.valueOf(line.split(" ")[3]);
            m.normals.add(new Vector3f(x,y,z));
        }else if(line.startsWith("vt "))
        {
            float x = Float.valueOf(line.split(" ")[1]);
            float y = Float.valueOf(line.split(" ")[2]);
            m.texVerticies.add(new Vector2f(x,y));
        }else if(line.startsWith("f "))
        {
            Vector3f vertexIndicies = new Vector3f(Float.valueOf(line.split(" ")[1].split("/")[0]),
                    Float.valueOf(line.split(" ")[2].split("/")[0]),
                    Float.valueOf(line.split(" ")[3].split("/")[0]));
            Vector3f textureIndicies = new Vector3f(Float.valueOf(line.split(" ")[1].split("/")[1]),
                    Float.valueOf(line.split(" ")[2].split("/")[1]),
                    Float.valueOf(line.split(" ")[3].split("/")[1]));
            Vector3f normalIndicies = new Vector3f(Float.valueOf(line.split(" ")[1].split("/")[2]),
                    Float.valueOf(line.split(" ")[2].split("/")[2]),
                    Float.valueOf(line.split(" ")[3].split("/")[2]));

            m.faces.add(new Face(vertexIndicies,textureIndicies,normalIndicies,currentTexture.getTextureID()));
        }else if(line.startsWith("g "))
        {
            if(line.length()>2)
            {
                String name = line.split(" ")[1];
                currentTexture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("res/" + name + ".png"));
                System.out.println(currentTexture.getTextureID());
            }
        }
    }

    reader.close();

    System.out.println(m.verticies.size() + " verticies");
    System.out.println(m.normals.size() + " normals");
    System.out.println(m.texVerticies.size() + " texture coordinates");
    System.out.println(m.faces.size() + " faces");
    return m;
}
}

```

Then I create a display list for my model using this code:

```
objectDisplayList = GL11.glGenLists(1);
    GL11.glNewList(objectDisplayList, GL11.GL_COMPILE);
    Model m = null;
    try {
        m = OBJLoader.loadModel(new File("res/untitled4.obj"));
    } catch (Exception e1) {
        e1.printStackTrace();
    }

    int currentTexture=0;
    for(Face face: m.faces)
    {
        if(face.texture!=currentTexture)
        {
            currentTexture = face.texture;
            GL11.glBindTexture(GL11.GL_TEXTURE_2D, currentTexture);
        }

        GL11.glColor3f(1f, 1f, 1f);
        GL11.glBegin(GL11.GL_TRIANGLES);

        Vector3f n1 = m.normals.get((int) face.normal.x - 1);
        GL11.glNormal3f(n1.x, n1.y, n1.z);
        Vector2f t1 = m.texVerticies.get((int) face.textures.x -1);
        GL11.glTexCoord2f(t1.x, t1.y);
        Vector3f v1 = m.verticies.get((int) face.vertex.x - 1);
        GL11.glVertex3f(v1.x, v1.y, v1.z);

        Vector3f n2 = m.normals.get((int) face.normal.y - 1);
        GL11.glNormal3f(n2.x, n2.y, n2.z);
        Vector2f t2 = m.texVerticies.get((int) face.textures.y -1);
        GL11.glTexCoord2f(t2.x, t2.y);
        Vector3f v2 = m.verticies.get((int) face.vertex.y - 1);
        GL11.glVertex3f(v2.x, v2.y, v2.z);

        Vector3f n3 = m.normals.get((int) face.normal.z - 1);
        GL11.glNormal3f(n3.x, n3.y, n3.z);
        Vector2f t3 = m.texVerticies.get((int) face.textures.z -1);
        GL11.glTexCoord2f(t3.x, t3.y);
        Vector3f v3 = m.verticies.get((int) face.vertex.z - 1);
        GL11.glVertex3f(v3.x, v3.y, v3.z);

        GL11.glEnd();
    }
    GL11.glEndList();

```

The currentTexture is an int - it contains the ID of the currently used texture.

So my model looks absolutely fine without textures:

But look what happens if I enable GL\_TEXTURE\_2D:

As you can see an entire side of the tree appears to be missing - and it's not transparent, since it's not in the colour of the background - it's rendered black.

It's not a problem with the model - if I load it using Kanji's OBJ loader it works fine(but the thing is,that I need to write my own OBJ loader)

this is my OpenGL init section:

```
//init display
    try {
        Display.setDisplayMode(new DisplayMode(Support.SCREEN_WIDTH, Support.SCREEN_HEIGHT));
        Display.create();
        Display.setVSyncEnabled(true);
    } catch (LWJGLException e) {
        e.printStackTrace();
        System.exit(0);
    }
    GL11.glLoadIdentity();
    GL11.glEnable(GL11.GL_TEXTURE_2D);
    GL11.glClearColor(1.0f, 0.0f, 0.0f, 1.0f);

    GL11.glShadeModel(GL11.GL_SMOOTH);
    GL11.glEnable(GL11.GL_DEPTH_TEST);
    GL11.glDepthFunc(GL11.GL_LESS);
    GL11.glDepthMask(true);
    GL11.glEnable(GL11.GL_NORMALIZE);

    GL11.glMatrixMode(GL11.GL_PROJECTION);

    GLU.gluPerspective (90.0f,800f/600f, 1f, 500.0f);
    GL11.glMatrixMode(GL11.GL_MODELVIEW);

    GL11.glEnable(GL11.GL_CULL_FACE);
    GL11.glCullFace(GL11.GL_BACK);

    //enable lighting
    GL11.glEnable(GL11.GL_LIGHTING);

    ByteBuffer temp = ByteBuffer.allocateDirect(16);
    temp.order(ByteOrder.nativeOrder());

    GL11.glMaterial(GL11.GL_FRONT, GL11.GL_DIFFUSE, (FloatBuffer)temp.asFloatBuffer().put(lightDiffuse).flip());
    GL11.glMaterialf(GL11.GL_FRONT, GL11.GL_SHININESS,(int)material_shinyness);

    GL11.glLight(GL11.GL_LIGHT2, GL11.GL_DIFFUSE, (FloatBuffer)temp.asFloatBuffer().put(lightDiffuse2).flip());              // Setup The Diffuse Light
    GL11.glLight(GL11.GL_LIGHT2, GL11.GL_POSITION,(FloatBuffer)temp.asFloatBuffer().put(lightPosition2).flip());
    GL11.glLight(GL11.GL_LIGHT2, GL11.GL_AMBIENT,(FloatBuffer)temp.asFloatBuffer().put(lightAmbient).flip());
    GL11.glLight(GL11.GL_LIGHT2, GL11.GL_SPECULAR,(FloatBuffer)temp.asFloatBuffer().put(lightDiffuse2).flip());

    GL11.glLightf(GL11.GL_LIGHT2, GL11.GL_CONSTANT_ATTENUATION, 0.1f);
    GL11.glLightf(GL11.GL_LIGHT2, GL11.GL_LINEAR_ATTENUATION, 0.0f);
    GL11.glLightf(GL11.GL_LIGHT2, GL11.GL_QUADRATIC_ATTENUATION, 0.0f);
    GL11.glEnable(GL11.GL_LIGHT2);

```

Could somebody please help me?

# Answer
You just need to flip your texture! Your texture width and height **must** to be like in this order:

**(2X2), (8X8), (32X32), (64X64), (128X128), (256X256), (512X512), (1024X1024)** and so on! (else your texture will fill with black areas!)

The solution is to use slick library for loading your textures!

(You must download the Slick library and add it to your java program!)

First import this lines to your java program:

```
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;

```

Then use this method to load your texture:

```
private Texture loadTexture(String key){
    try {
        Texture texture = TextureLoader.getTexture("png", new FileInputStream( new File(key)), true);
        return texture;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

```

*This method flip your texture coordinates because OBJ origin is at upper left and OpenGL origin is at lower left.*

And last thing you need to do before calling **glBegin** is bind your texture:

```
texture.bind();

```

I hope it will help you to solve your problem! ^^
> 2 votes

# Answer
This problem has been solved and it works now. This used to be a university project,but now it has been marked and returned I am free to share the entirety of it with you. This is 3D space invaders game, with a custom OBJ loader writing in Java, you can download it from this repo on GitHub:

https://github.com/gambiting/Graphics\_Project

git://github.com/gambiting/Graphics\_Project.git
> 0 votes

---
Tags: textures, models, lwjgl, obj
---


# Question
Title: vertices, better to have more but draw a smaller area or less but expand a larger area
I have a simple question really. I am creating water for a game and had two different design approaches:

1. Make a single plane that expands the entire playspace, which would take 6 vertices but cover a much larger area. The idea being the plane would be at a certain height so the sourrong land if higher should cover it.
2. Check at regular intervals around the created land, ask if the height of that peice of land is below a certain height if so, draw a small square to cover the area and then check the next interval and the next... The idea being you'd have a lot more vertices but much less area will be drawn.

Any help would be appreciated as to which design approach makes more sense.

# Answer
That's really not that important. Computers nowadays are fast, more important is not to use a "dumb" approach.

When I first started programming in OpenGL (for Android, OpenGL 1.0) I made a Minecraft-like game, but instead of using VBOs or moving to OpenGL ES 2.0 I sent all vertex data, every frame to the GPU. You can imagine how slow it was. I was getting about 3-4 FPS on a 32x32x16 world. Then I implemented octree frustum culling which improved nothing. But I did learn a lot from that.
Logic of the program is much more important than some micro-optimisations in the code that only gets executed once.

About two years later I know better and program OpenGL for a hobby and it is very fun.
> 2 votes

# Answer
As long as you do not require the vertices for animation and you don't want to have caves or other holes below sea level you should probably use your first approach:

1. If you render the water after your land geometry all fragments not visible will get depth culled which is very efficient.
2. The water geometry is clipped before shading the fragments which means only visible fragments will get shaded.
3. You have only one draw call. 2 would require to batch the patches or combine them into one buffer.
> 1 votes

# Answer
You'll be fine with the first approach. Just don't make them too far away or you'll run the risk of having some odd graphical glitches due to floating point imprecision happening.
> 0 votes

# Answer
Making a big square that covers the entire game world is a fine approach unless you run into some problem with it. There are a couple of potential problems you should remain aware of that could make it better to tessellate the water a bit more:

* If the game world is very large, the water vertices will be very far away from the camera. It's possible to run into floating-point precision problems where the water plane would appear to be unstable and "vibrate" as the camera moves around. Tessellating the water plane more would alleviate this, since it would add vertices closer to the camera.
* If the water has an expensive pixel shader, you might end up paying the performance cost of it even when it's underground (because it's still being drawn). Removing water from underground areas would help this. However, you can also fix this by doing a depth pre-pass, or simply by drawing the ground before you draw the water. Then the GPU's hierarchical Z culling should eliminate the underground water pixels quite efficiently.

So, if you don't have such a large game world that floating-point precision becomes problematic, and you make sure to draw the ground before you draw the water, then having one big square for the water should be fine.
> 0 votes

---
Tags: xna, graphics
---


# Question
Title: What can I do to get audio into my game legally?
If making a game of my own, what should or what can I do to get audio in game? I understand that just going on the internet, and finding random tracks and putting in my game may raise a whole load of legal issues, but is there any "good" way to get audio in the game?

Basically, if making a game, would it be better to create your own music (regardless of experience) in house, or hire someone outside to do it?

Also, if I want to use music out on the internet, what steps should I take to use that music?

# Answer
> 7 votes
This is all going to depend on how capable you are as an audio machine and what your budget is.

If you do it yourself, you can either find some tools that let you generate sound effects or you can record your own from coconuts or something. If you try recording your own I would highly recommend you try renting or borrowing some nice audio equipment, since the better quality the audio to begin with the easier it will be to post process. Combine two home made sound effects to get one unique sound effect, for example! For music then, see if you can get some easy music making software that allows you commercial rights to the tracks. Overall, making audio yourself can be a painful process for you if you aren't experienced with audio at all and you might not produce good results after hours and hours of effort. On the plus side, this should be cheap if you don't value your time.

If you hire someone to do the work for you. It's possible you might have to hire several people to do the work since someone who is good at music might not be good at sound effects. Either way, this is going to cost you money but going to be the best for you in the long run if you are not very capable at producing the audio yourself. You will save yourself the headaches from not having to make it yourself. This route will also give you the freedom to be productive on areas you are good at while the contractor focuses on the audio. A professional should have the appropriate skill set and equipment (or means to acquire the equipment) to handle producing of the audio for you. In the end you should end up with a high quality product in exchange for a nice sum of money.

As a last alternative, there is royalty free audio out there in the world. You can explore the public domain or do some investigation via Google and maybe you'll be able to find something that suits your game, or at least find multiple sound effects you can modify to make work for you which will take significantly less effort than creating your own from scratch.

---
Tags: legal, music, project-management
---


# Question
Title: Variable timeStep not working as intended
I've been working on a game in javascript/html5 (through typescript) using my own little library. This library uses a variable timestep since I plan on using it on mobile devices, and I was under the assumption that this will help keep things roughly the same on both (I know there's probably a debate on that, but that's not what I'm asking).

The problem is, using my variable timestep, I'm getting wildly different entity speeds. I am working out how long in seconds the frame took to update and draw, then multiplying entity velocities by this.

I'm running the game loop using setInterval. It's set up to run at 60fps, so a 16(ish)ms interval.

```
var now: Date = new Date();
timeInterval = (now.getTime() - Engine.lastUpdate.getTime()) / 1000;
Engine.lastUpdate = now;
Input.update();
currentScene.update();
draw();

```

Player class:

```
        update() {

        //W:87 S:83 A:65 D:68

        this.velocity.y += this.gravity;

        if (SandLib.Input.isKeyJustDown(16)) {
            this.gravity *= -1;
            this.jumpPow *= -1;
        }

        this.velocity.x += this.accel;

        if (this.velocity.x > this.maxVel) {
            this.velocity.x -= this.decel;
        }

        if (this.x > this.cameraMoveZone) {
            SandLib.Engine.currentScene.camera.x = this.x - this.cameraMoveZone;
        }

        //Collision code here

        if (SandLib.Input.isKeyJustDown(32) && this.onGround) {
            this.velocity.y -= this.jumpPow;
            this.velocity.x *= this.jumpBoost;
            this.onGround = false;
            Main.jumpSnd.play();
        }

        if (this.y > 800 || this.y < -800) {
            this.die();
        }
        super.update();
    }

```

Any ideas why this gives a faster speed on lower fps devices.

# Answer
> 1 votes
It's possible that there's a bug in your delta time calculation or a bug in your calculations for entity movement. It's hard to say without seeing more code, but I don't think you need to divide the delta time by 1000. That value should already be in milliseconds. Your movement code should then multiply the entity's speed per millisecond by the number of milliseconds since last frame, which should generally be ~16.

```
// entity.speed is something like 0.25, deltaTime is ~16
// entity moves 4 pixels this frame
entity.x += (entity.speed * deltaTime);

```

Either way, you should be using requestAnimationFrame instead of setInterval as explained by Paul Irish. Also, checkout this update for sub-millisecond precision.

# Answer
> 0 votes
So, you calculate `timeInterval`, and then don't use that value for anything? At least that is what is visible in the code shown. If you want to use variable time step then you have got to multiply with the `timeInterval` in every integration step.

```
this.velocity.y += this.gravity * timeInterval;
this.velocity.x += this.accel * timeInterval;
this.velocity.x -= this.decel * timeInterval;

```

And I guess there is more of them outside of the shown code.

But really, fix your time step, it works great, but it is also the easy thing to do. A few lines of code to keep the timing, and the entire rest of your application can be written with no specific consideration for time.

---
Tags: javascript, timestep
---


# Question
Title: Centering GLViewport position within physical screen
I'm developing my app on one device and want it to display at the same ratio on all other devices.

Currently what I have is 'image 1' in my image below - the game fits perfectly onto my development device's screen.

If I keep the viewport at the same ratio then I get the results seen in 'image 2'.

This is great, but now I need to center the viewport , and I'm not sure how to do that.

What I'm aiming for is what is in 'image 3' - just not sure how to get there.

This is how I'm keeping the viewport at the same ratio:

the ratio is width / height (this is 1.702127659574468 and we will use this explicitly)

```
//Set viewport size based on screen dimensions
GLES20.glViewport(XVal, YVal, (int) (height * 1.702127659574468), height);

```

At the moment, XVal and YVal are both 0 - I need to change XVal to move the image along.

How do I work out the amount to move the viewport along by? (I know it will be equal to half of the space to the right of the viewport ('image 2') - just not sure how to work this out.......)

# Answer
> 3 votes
```
xoffset = (targetScreenWidth - image1Width)/2;

```

---
Tags: android, opengl-es2, aspect-ratio, viewport
---


title: MVC pattern for turn-based RPG

text:
# Question
Title: MVC pattern for turn-based RPG
I'd like to make a 2D game in Java using the Model-View-Controller (MVC) pattern, but I have some issues concerning the battles.

There are two groups of characters in each battle: heroes and monsters. The player controls the heroes. My game is turn-based: I'd like to select one character at a time, ask the player the action to use, its target, and finally execute the action. However I can't seem to adjust this sequence of commands with the MVC pattern.

Could anyone help me?

# Answer
> 3 votes
You can solve this by implementing the controller as a state machine with four states:

* select character
* select action
* select target
* wait for animation to finish

In each of these state different GUI elements are shown/hidden and the inputs of the user are interpreted differently.

Instead of implementing it as a state machine, you could also implement it with four individual controller classes, one for each state.

---
Tags: java, rpg, turn-based, mvc
---


# Question
Title: How to prevent the player from clicking too fast
I'm having trouble with some bullets in my game, the M1911, which is supposed to be semi-auto is only capable of shooting one projectile per mouse click (trying to learn how to do multiple ones at once). The problem is, if the player clicks the mouse ridiculously fast it causes the bullet to reset its position back to the player (not intended).

Basically I want to limit the clicks, or implement a cooldown after the left mouse buttons pressed which prevents the player from clicking at all during a certain timeframe (or until the bullet hits something).

I want it so that when LMB is pressed it starts a timer.

# Answer
> 7 votes
The usual way to handle this is that every time a bullet is fired you set some variable to your cooldown time. Every frame you decrement that variable by the frame time. If you try to fire and that value is greater than 0, you just ignore the fire input event.

If that feels bad, a next step is to queue up a "they want to fire" action if they try to click when the cooldown is happening and execute on it when the timer passes zero.

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


# Question
Title: How to implement deceleration and stopping over a certain distance
So I have a a character, say a spaceship. It needs to move distance R, and in direction T (Theta). So say if The object is at (0,0), and it needs to get to (4,3), it has R = 5 and T = about 36 degrees.

Essentially I know where the endpoint is, and the distance away. I want my spaceship to start decelerating when R becomes 8, and the object come to a halt when it reaches the location.

How can I do this. (Kinematics in answers is welcome)

# Answer
> 5 votes
Here are 3 standard (pre-calculus) kinematics formulae covering the case of constant acceleration, each with one of the unknowns (*t*, *v*, or _*d*) eliminated:

1. v^2 = u^2 + 2 a d
2. v = u + a t
3. d = u t + a (t^2) / 2

where:

* **u** and **v** are the *unitial* and *vinal* (sic) velocities respectively;
* **t** is the *time*;
* **d** is the *distance* travelled in time t; and
* **a** is the constant *acceleration*

For your case you know *u*, *v* and *d*, and need to know *a*, so use formula (1), rearranged into:
`a = (v^2 - u^2) / (2 d)`.

(2) and (3) can then be used to calculate *v* and *d* at each time until arrival.

---
Tags: physics, movement
---


# Question
Title: iOS OpenGL ES 2.0 How to Billboard on Sphere and Rotate with Sphere
I have a sphere (earth) in OpenGL ES 2.0 for iOS. I also have markers that I want to place at lat/lons on the earth - but I want the markers to always face the user ( billboards ) but also move with the Earth when it rotates by touch. So I've tried to research billboarding and put together the following code. This code is from the billboarding function that is called after I create the earth ( which is translated backwards 6 units on the Z axis). I can't seem to get the planes of the billboards to always face the camera but also move with the Earth as it rotates. How can I do that?

```
    // Get the current modelview matrix
    GLKMatrix4 originalMat = self.effect.transform.modelviewMatrix;
    GLKMatrix4 currMat = self.effect.transform.modelviewMatrix;

    // Define the buffer designators
    GLuint billboardVertexArray;
    GLuint billboardVertexBuffer;
    GLuint billboardIndexBuffer;

    glGenVertexArraysOES(1, &billboardVertexArray);
    glBindVertexArrayOES(billboardVertexArray);

    // Now draw the billboard
    glGenBuffers(1, &billboardVertexBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, billboardVertexBuffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(Billboard_vertex), Billboard_vertex, GL_STATIC_DRAW);

    glGenBuffers(1, &billboardIndexBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, billboardIndexBuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Billboard_index), Billboard_index, GL_STATIC_DRAW);

    // u0,v0,normalx0,normaly0,normalz0,x0,y0,z0
    glEnableVertexAttribArray(GLKVertexAttribPosition);
    glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 8*sizeof(float), BUFFER_OFFSET(5));
    glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
    glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, 8*sizeof(float), BUFFER_OFFSET(0));
    glEnableVertexAttribArray(GLKVertexAttribNormal);
    glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 8*sizeof(float), BUFFER_OFFSET(2));

    // Enable the Earth texture
    self.effect.texture2d0.name = _billBoardTextureInfo.name;
    self.effect.texture2d0.target = _billBoardTextureInfo.target;

    // Bind the earth vertex array
    glBindVertexArrayOES(billboardVertexArray);

    // Now put a billboard at a specific Lat Lon - so first
    // calculate XYZ from lat lon
    XYZ xyz;
    xyz.x = 0; xyz.y = 0; xyz.z = 0;
    [self LLAtoXYZwithLat:0 andLon:0 andXYZ:&xyz];
    //NSLog(@"XYZ after: %f %f %f",xyz.x,xyz.y,xyz.z);

    // Move the billboard back so we can see it
    GLKMatrix4 modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.0f, -6.0f);

    // In update, we convert the quaternion into a rotation matrix, and apply it to the model view matrix as usual.
    GLKMatrix4 rotation = GLKMatrix4MakeWithQuaternion(_quat);
    modelViewMatrix = GLKMatrix4Multiply(modelViewMatrix, rotation);

    // First create the variation translations to anchor the billboard
    GLKMatrix4 translationXYZ = GLKMatrix4MakeTranslation(xyz.x, xyz.y, xyz.z);
    GLKMatrix4 translationForLatLonWithTranslation = GLKMatrix4Multiply(modelViewMatrix,translationXYZ);

    // Scale this object as well
    GLKMatrix4 scaledWithTranslationAndRotation = GLKMatrix4Scale(translationForLatLonWithTranslation, scale, scale, scale);

    // Remove the Translation portion of the matrix
    // | xx xy xz xw |
    // | yx yy yz yw |
    // | zx zy zz zw |
    // | wx wy wz ww |
    //
    // | R       T |
    // | (0,0,0) 1 |
    //
    // d = sqrt( xx² + yx² + zx² )
    //
    // | d 0 0 T.x |
    // | 0 d 0 T.y |
    // | 0 0 d T.z |
    // | 0 0 0   1 |
    //
    // union _GLKMatrix4
    // {
    //     struct
    //     {
    //         float m00, m01, m02, m03;
    //         float m10, m11, m12, m13;
    //         float m20, m21, m22, m23;
    //         float m30, m31, m32, m33;
    //     };
    //     float m[16];
    // }
    // typedef union _GLKMatrix4 GLKMatrix4;

    // Construct the rows in the new matrix
    float d = sqrt( pow(currMat.m00,2) + pow(currMat.m10,2) + pow(currMat.m20,2) );
    GLKVector4 columnToInsert0 = GLKVector4Make(d, 0, 0, currMat.m03+xyz.x);
    GLKVector4 columnToInsert1 = GLKVector4Make(0, d, 0, currMat.m13+xyz.y);
    //GLKVector4 columnToInsert2 = GLKVector4Make(0, 0, d, currMat.m23-6+xyz.z);
    GLKVector4 columnToInsert3 = GLKVector4Make(0, 0, 0, 1);

    // Build the new Matrix
    GLKMatrix4 noTranslationInfo = GLKMatrix4SetRow(currMat, 0, columnToInsert0);
    noTranslationInfo = GLKMatrix4SetRow(noTranslationInfo, 1, columnToInsert1);
    //noTranslationInfo = GLKMatrix4SetRow(noTranslationInfo, 2, columnToInsert2);
    noTranslationInfo = GLKMatrix4SetRow(noTranslationInfo, 3, columnToInsert3);

    [self printMatrix:noTranslationInfo];

    // Assign the new matrix to draw with - no translation
    self.effect.transform.modelviewMatrix = noTranslationInfo;

    // Render the object with GLKit
    [self.effect prepareToDraw];

    // Draw elements from the index array and uv / vertex / normal info
    glDrawElements(GL_TRIANGLES,Billboard_polygoncount*3,GL_UNSIGNED_SHORT,0);

    // Restore the original matrix
    self.effect.transform.modelviewMatrix = originalMat;

```

# Answer
> 0 votes
This code works:

```
// Get the current modelview matrix
GLKMatrix4 originalMat = self.effect.transform.modelviewMatrix;
GLKMatrix4 currMat = self.effect.transform.modelviewMatrix;

// Print the original matrix for comparison
//NSLog(@"Original Matrix:");
//[self printMatrix:currMat];

// Define the buffer designators
GLuint billboardVertexArray;
GLuint billboardVertexBuffer;
GLuint billboardIndexBuffer;

glGenVertexArraysOES(1, &billboardVertexArray);
glBindVertexArrayOES(billboardVertexArray);

// Now draw the billboard
glGenBuffers(1, &billboardVertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, billboardVertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(Billboard_vertex), Billboard_vertex, GL_STATIC_DRAW);

glGenBuffers(1, &billboardIndexBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, billboardIndexBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(Billboard_index), Billboard_index, GL_STATIC_DRAW);

// u0,v0,normalx0,normaly0,normalz0,x0,y0,z0
glEnableVertexAttribArray(GLKVertexAttribPosition);
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 8*sizeof(float), BUFFER_OFFSET(5));
glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, 8*sizeof(float), BUFFER_OFFSET(0));
glEnableVertexAttribArray(GLKVertexAttribNormal);
glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, 8*sizeof(float), BUFFER_OFFSET(2));

// Enable the Earth texture
self.effect.texture2d0.name = _billBoardTextureInfo.name;
self.effect.texture2d0.target = _billBoardTextureInfo.target;

// Bind the earth vertex array
glBindVertexArrayOES(billboardVertexArray);

// Now put a billboard at a specific Lat Lon - so first
// calculate XYZ from lat lon
XYZ xyz;
xyz.x = 0; xyz.y = 0; xyz.z = 0;
[self LLAtoXYZwithLat:35 andLon:-97 andXYZ:&xyz];
//NSLog(@"XYZ after: %f %f %f",xyz.x,xyz.y,xyz.z);

// Scale this object as well
//GLKMatrix4 scaledWithTranslationAndRotation = GLKMatrix4Scale(translationForLatLonWithTranslation, scale, scale, scale);

// Remove the Translation portion of the matrix
// | xx xy xz xw |
// | yx yy yz yw |
// | zx zy zz zw |
// | wx wy wz ww |
//
// | R       T |
// | (0,0,0) 1 |
//
// d = sqrt( xx² + yx² + zx² )
//
// | d 0 0 T.x |
// | 0 d 0 T.y |
// | 0 0 d T.z |
// | 0 0 0   1 |
//
// union _GLKMatrix4
// {
//     struct
//     {
//         float m00, m01, m02, m03;
//         float m10, m11, m12, m13;
//         float m20, m21, m22, m23;
//         float m30, m31, m32, m33;
//     };
//     float m[16];
// }
// typedef union _GLKMatrix4 GLKMatrix4;

// Construct the rows in the new matrix
float d = sqrt( pow(currMat.m00,2) + pow(currMat.m10,2) + pow(currMat.m20,2) );
GLKVector4 columnToInsert0 = GLKVector4Make(d, 0, 0, xyz.x);
GLKVector4 columnToInsert1 = GLKVector4Make(0, d, 0, xyz.y);
GLKVector4 columnToInsert2 = GLKVector4Make(0, 0, d, xyz.z);
GLKVector4 columnToInsert3 = GLKVector4Make(0, 0, 0, 1);

// Build the new Matrix
GLKMatrix4 noTranslationInfo = GLKMatrix4SetRow(currMat, 0, columnToInsert0);
noTranslationInfo = GLKMatrix4SetRow(noTranslationInfo, 1, columnToInsert1);
noTranslationInfo = GLKMatrix4SetRow(noTranslationInfo, 2, columnToInsert2);
noTranslationInfo = GLKMatrix4SetRow(noTranslationInfo, 3, columnToInsert3);

// Print out the 'no translation' matrix
//NSLog(@"No Translation Matrix:");
//[self printMatrix:noTranslationInfo];

// Get a rotation matrix from the quaternion we last rotated the globe with
GLKMatrix4 rotationMatrixFromQuaternion = GLKMatrix4MakeWithQuaternion( _quat );
//NSLog(@"Rotation Matrix from Quaternion: ");
//[self printMatrix:rotationMatrixFromQuaternion];

// Now use the matrix produced from our Quaternion to rotate the global coordinates
// of the billboard object
GLKMatrix4 rotatedNoTranslationInfo = GLKMatrix4Multiply(rotationMatrixFromQuaternion, noTranslationInfo);

//NSLog(@"rotatedNoTranslationInfo:");
//[self printMatrix:rotatedNoTranslationInfo];

// Throw the world translation coordinates in the matrix
noTranslationInfo.m30 = ( rotatedNoTranslationInfo.m30 );
noTranslationInfo.m31 = ( rotatedNoTranslationInfo.m31 );
noTranslationInfo.m32 = ( rotatedNoTranslationInfo.m32 + GLOBAL_EARTH_Z_LOCATION );

//NSLog(@"Final Matrix:");
//[self printMatrix:noTranslationInfo];

// Assign the new matrix to draw with - no translation
self.effect.transform.modelviewMatrix = noTranslationInfo;

// Render the object with GLKit
[self.effect prepareToDraw];

// Draw elements from the index array and uv / vertex / normal info
glDrawElements(GL_TRIANGLES,Billboard_polygoncount*3,GL_UNSIGNED_SHORT,0);

// Restore the original matrix
self.effect.transform.modelviewMatrix = originalMat;

```

---
Tags: ios, opengl-es, rotation, opengl-es2, billboarding
---


# Question
Title: Set a variable inside a GLSL fragment shader that persists for the render
Is it possible to set a `varying` variable inside a fragment shader and have it persist? I'd like to use the depth component of the first fragment and use it on all the others, making the fragments all flat to the camera.

Secondary question: Is it the whole frag shader that runs per-fragment, or just the stuff inside `main()`? Is everything redeclared each time?

# Answer
> 6 votes
If you mean: Can I compute a variable in the first fragment and pass it around? No, not like that. The fragments are processed in parallel.

If you need to do that, compute the variable CPU side and pass it in as a uniform. If you needed to do a lot of computation you could output to a texture or a buffer and then read it back, but you only need one float from the sounds of it.

# Answer
> 3 votes
As Lewis said, fragments are processed in parrallel, each fragment shader is executed once per fragment. In GLSL there are three ways to communicate between your application and your shaders:

1. uniform variables: variables that are set from user code, but only are allowed to change between different glDraw\* calls. Uniforms can be queried and set by the code external to a particular shader.
2. varying variables: are used as a communication between different shader stages, varying variables must be written in vertex shader, they will be interpolated by the graphics driver and then read from the fragment shader. (Please note that the qualifier "varying" has been deprecated and replaced with the more "descriptive" In/Out, yet the same functionality remains.
3. vertex attributes: are values necessary to draw a model and change per vertex, they are fed to GLSL via user code and usually include Position, Normals, Tangents, Colors.
4. if you mean **Communication between different fragments processed by the same shader**, well as said above GLSL executes a fragment shader once per fragment, but you can still share data between different fragments (for example to apply image processing effects) this usually done via Texture Samplers to access neighbor fragments. keep in mind that you usually need multipass algorithms for this, example usage may be: **1-** Render you scene to texture. **2-** apply it to a screen algined quad. **3-** run your fragment shader on the quad and send the texture sampler to it. **4-** access neighbor fragments by using offset when looking up texture coordinates ( e.g. glTexCoord.s+0.1).

# Answer
> 0 votes
You can achieve what you wish, but not the way you're thinking of doing it.

If you want to output a common depth for all fragments belonging to a primitive, you can add an extra vertex attribute - say, the midpoint of the primitive - which can be a per-instance attribute (if using instancing) or an extra per-vertex attribute (or even set via a glVertexAttrib3f call). The method used to set it doesn't matter much; what's important is that it has the same value for each vertex.

Duplicate your per-vertex calculations for position and for this extra attribute, then pass the extra attribute to your fragment shader as a varying. From there you just need to output depth from your fragment shader based on this extra attribute.

At this stage you're probably worrying a little about having to do the extra redundant calculations per-vertex, but this is not going to be a big deal compared to the overhead of outputting depth from your fragment shader, which will disable early-depth-testing for that shader, and which will be a requirement anyway if you want all fragments to have common depth.

---
Tags: opengl, glsl
---


title: Trap mouse in SDL2

text:
# Question
Title: Trap mouse in SDL2
When using SDL 1.2 it the way to implement full screen or windowed applications with "no cursor" you did the following:

```
SDL_ShowCursor(SDL_DISABLE);
SDL_WM_GrabInput(SDL_GRAB_ON);

```

See Trap mouse in SDL

Unfortunately I am unable to get the same behavior with SDL 2.0. I implemented the above as:

```
SDL_Window* window;
// ...
SDL_ShowCursor(SDL_DISABLE);
SDL_SetWindowGrab(window, SDL_TRUE);

```

Am I missing something or do you have to wrap the cursor manually back to the center of the window/screen?

# Answer
The solution is SDL\_SetRelativeMouseMode. How can I have missed that.
> 10 votes

---
Tags: sdl, mouse
---


title: Irrlicht rendering basic OBJ

text:
# Question
Title: Irrlicht rendering basic OBJ
I have been trying to render a "room" with some basic functions and I found some "bugs".

So at first I have made a "room" out of 6 planes in blender and gave each of them a diffrent color.

Afterwards I rendered it using Irrlicht and here is the first resault :

But if I go around the room to see the other sides they start to dissapear:

At first, I though it may be due to the fact that i was "too close" or "too far" from the object, or that the object was "too small" but I have tested all those and got the same resault.

So I guess the problem comes from the way I import and load in the mesh, but I couldn't find a way to solve it.

Here is the code for importing the mesh / rendering it :

```
IAnimatedMesh* mesh2 = smgr->getMesh("Sky.obj");
ISceneNode* node2 = 0;

if(mesh2)
{
    node2 = smgr->addOctreeSceneNode(mesh2->getMesh(0), 0, -1, 1024);
    //node2 = smgr->addMeshSceneNode(mesh2->getMesh(0));
    node2->setMaterialFlag(EMF_LIGHTING,false);
}

```

I would like to know why this happens and how to solve it.

# Answer
It is probably better to make the room with a cube thinned to the size of the walls, as a plane is only showing one sided, where as a cube shows both sides, (as well as top bottom left and right which can be textured black for faster rendering). A plane is just not right for a room unless you are only going to view room from inside, then you have to flip the normals in edit mode in blender.

Or as in previous post The button you are looking for is now called "BackFace Culling" in the materials menu under Game Settings.

OR see this link http://www.blender.org/forum/viewtopic.php?t=21544&highlight=double+side
> 3 votes

# Answer
This is most likely a normal problem. Since the planes in Blender are not connected (they're just standalone planes, i.e. not connected) Blender can't calculate the normals. You can check if this problem exists in Blender as well by selecting **Backface culling** in the properties panel in the 3d view (`n` key).
> 2 votes

---
Tags: rendering, 3d-meshes, irrlicht
---


# Question
Title: How can I get pre-release reviews of my mobile game?
My iOS and Android game is at its last stage of development. Is there a way for me to get pre-release reviews from people? Or maybe from the press? How should I proceed?

# Answer
Giving it away for free to a SMALL(ER) ammount of people. Using the Redeem code option over on the Appstore, you can give payed versions of the game for free. But it will work slower / have effect on a smaller group of people, I'd go with another technique which is widely used.

Distribute it and do the following:

Add a pop up - Rate us after 15+ minutes of playing.

1)

> People make the game price free for a limited time period. The Fruit Ninja did that, once they have become popular they released the "lite version" next to the paid version which contains less features. That way, when someone sees the full version of Fruit ninja at someones phone, he might want to buy it.

2)

> Depending on the game, if you made a role playing game, with a story that drives the players attention. You can create the first chapter (however it is called) playable to anyone and once the player wants to hear the rest of the story and he likes the game, he will buy it. "Horn" by Zynga has used this technique. (Sadly, it worked on me). This will get you both, more sells and reviews
> 1 votes

---
Tags: android, ipad, casual-games, arcade
---


# Question
Title: Memory allocation patterns used in game development
I have been researching creating my own allocator methods (that will support things such as a memory pool and profiling), however, as I continue my research I have been looking for how this was done in game development.

What memory allocation technique could I use, and why is it a good technique?

# Answer
> 27 votes
Game Engine Architecture has some information regarding this topic. The basics are that you need to do some analysis to understand what your memory requirements per level/frame/etc. are like, but there are a few patterns the author mentions having seen several times:

* **Stack-based allocators:** These allocate a large segment of memory once, and then allocate pointers within that block of memory in response to requests from elsewhere in the game. This is useful to avoid context switches required by memory allocation, and also because you can use your own techniques to enforce contiguity, or specific alignment for SIMD operations. Some engines also use a double-ended stack where one kind of resource is loaded from the top and the other is loaded from the bottom. Perhaps LSR (Load and Stay Resident, the kind of thing that will be needed throughout the entirety of your game) from the top, and per-level data from the bottom.
* **Single frame memory, or double-buffered frame memory:** Memory for operations that occur within one or two frame cycles. This is useful because rather than having to allocate/deallocate every frame, you can simply blow away last frame's data by resetting the pointer you use to keep track of memory to the beginning of the block.
* **Object Pools:** A block of memory for many same-size objects, such as particles, enemies, projectiles. These are useful because you can easily achieve contiguity by finding the first unused segment in your pool. They also make iteration easy, because each object is at a known offset from the last.

The biggest thing the author mentions to look out for is memory fragmentation. This is less of an issue if you're developing for e.g. a PC where you have some kind of memory paging backup that you can count on, but in a fixed memory context like a console, there's the risk of being "out of memory" when trying to allocate for a large object because your memory is fragmented in such a way that only small contiguous blocks are available. To that end, he recommends that a stack-based allocator as above also include a method of periodically defragmenting its contents.

For more information on the actual code involved in this, I highly recommend Christian Gyrling's article, "Are we out of memory?", which covers techniques for custom allocators, mostly from a perspective of analyzing memory usage patterns, but this is also applicable to devising a custom solution for memory management.

# Answer
> 1 votes
From what I have seen (but not done) each game tends to either inherit the allocation mechanisms from a framework, from a game engine, from the previous version (2010 -\> 2011) or it gets a set of new ones written specifically for its structure (either when data structures are reusable and of fixed size or of numerous types and variable sizes).

Also we had different allocators for sound files/components than for levels and other game objects in the same project. In other projects allocators are inherited from external libraries only for the components managed by that lib.

The optimization really depends on your needs. But usually allocation is done before entering to the game scene and then memory is reused. Some games can get away with gaving no custom allocators. But for action games where the processor, memory and data resources are budgeted you can't afford to lose processing time on large allocations, you can't waste memory to fragmentation and other problems.

Concerning examples you should simply start by having a look at the OGRE 3D game engine it has a few options to configure memory allocators.

# Answer
> -2 votes
The mistake that is often made is to write your own allocators so that you can have more control over how much memory is used by each system and have more visibility on what is going on. A much better way to achieve this is to use a memory profiler. There are plenty of memory profilers out there, my profiler MemPro being one example. This is a totally non-invasive way to keep track of all memory usage, and you can automatically break it down into sub systems using callstack wildcard filters. Ideally its best to keep your memory allocation and memory tracking totally separate, they have totally different requirements.

Arbitrarily dividing your memory into pools can often be detrimental because each pool will have an overhead. You can end up using much more memory than you need without actually realising it. To reduce wastage it’s always better to lump everything together, the slack is then shared by the whole system.

The only reasons for using custom allocators are CPU performance (mainly for cache coherency) and to limit fragmentation. A perfect example of this is a particle system. You want all particles contiguous in memory and you don’t want to pepper main memory with lots of short lived allocations. Another good example for partitioning off is a scripting language.

If you want an example of a general purpose malloc replacement you can have a look at my VMem allocator. It has been used in a number of shipped AAA games. It has techniques that limit fragmentation and keep the memory footprint low, something critical for console games. It’s also very fast under high thread contention. My website has extensive documentation on these techniques.

---
Tags: c++, architecture, design-patterns, memory-efficiency
---


# Question
Title: Detect when two keys are pressed at the same time
I'm doing a game with XNA and I need an animation when two keys are pressed.. I tried this but it doesn't function.

```
if (Keyboard.GetState().IsKeyDown(Keys.D) && Keyboard.GetState().IsKeyDown(Keys.W))
{
    jumpRight(gameTime);
    vel.X = +2;
}

```

The jump functions and the others animations with only one key pressed function too, but this one doesn't work. What should I do?

# Answer
I would recommend using `Console.WriteLine("some text")` in the future to determine whether or not your code gets reached, in this case:

```
if (Keyboard.GetState().IsKeyDown(Keys.D) && Keyboard.GetState().IsKeyDown(Keys.W))
{
    Console.WriteLine("D and W pressed!");

    jumpRight(gameTime);
    vel.X = +2;
}

```

If the message is printed, it could be an error in your `jumpRight`-method.

If the message is NOT printed, it could be an error in the way you setup your logic.

Alternatively, you could learn how to debug your code, for that, refer to this neat little tutorial: http://www.dotnetperls.com/debugging

EDIT:

To answer your question in this particular case, instead of `else if` in say `else if (Keyboard.GetState().IsKeyDown(Keys.A))` use just `if`.

Why? Because when you press A, it does what it has to do when you press A, and then skips over the rest of the if-statement blocks. If you use `if` instead, it won't.

Your new Update-method would look like this (I also removed my earlier suggested code):

```
public void Update(GameTime gameTime)
{
    NS = VS;
    rect = new Rectangle(frameCor * largFrame, 0, largFrame, altFrame);
    origine = new Vector2(rect.Width / 2, rect.Height / 2);
    posizione = posizione + velocita;

    velocita = Vector2.Zero;

    if (Keyboard.GetState().IsKeyDown(Keys.D))
    {
        animazioneDestra(gameTime);
        velocita.X = 3.5f;
    }

    if (Keyboard.GetState().IsKeyDown(Keys.A))
    {
        animazioneSinistra(gameTime);
        velocita.X = -3.5f;
    }

    if (NS.IsKeyDown(Keys.D) && VS.IsKeyDown(Keys.W))
    {
        SaltoDX(gameTime);
        velocita.X = +3;
    }

    if (Keyboard.GetState().GetPressedKeys().Length == 0)
    {
        Stato(gameTime);
        velocita.X = 0;
    }
}

```
> 3 votes

# Answer
Please note that although you said that you wanted to check if `D` and `W` keys were pressed simultanously, you don't. What you do is, you check if the D key is down. Next, you check if the W key is down. Nothing in your code makes sure that **both** are down at the very same time. Any time you call `GetState` you query the keyboard for it's state. In your code, you check two different keyboard states. If you want to check if both keys are down *in the same instant of time* you need to check it on the *same* keyboard state.

```
// get the state once
var state = Keyboard.GetState();

// check if D and W are down in the same state
if (state.IsKeyDown(Keys.D) && state.IsKeyDown(Keys.W))
{
    // code
}

```
> 1 votes

# Answer
Your NS and VS KeyboardState objects are never used. Because of this, you are never checking against your current KeyboardState.

You will need to do something like:

```
VS = Keyboard.GetState()

```
> 1 votes

---
Tags: animation, jumping
---


# Question
Title: XNA - 2D Rotation of an object to a selected direction
I'm trying to figure out the best way of rotating an object towards the directional input of the user. I'm attempting to mimic making turns on ice skates.

For instance, if the player is moving right and the input is down and left, the player should start rotating to the right a set amount each tick. I'll calculate a new vector based on current velocity and rotation and apply that to the current velocity. That should give me nice arcing turns, correct?

At the moment I've got eight if/else statements for each key combination which in turn check the current rotation:

```
// Rotate to 225
if (keyboardState.IsKeyDown(Keys.Up) && keyboardState.IsKeyDown(Keys.Left))
{
    // Rotate right
    if (rotation >= 45 || rotation < 225)
    {
        rotation += ROTATION_PER_TICK;
    }
    // Rotate left
    else if (rotation < 45 || rotation > 225)
    {
        rotation -= ROTATION_PER_TICK;
    }
}

```

This seems like a sloppy way to do this and eventually, I'll need to do this check about 10 times a tick. Any help toward a more efficient solution is appreciated.

# Answer
```
Vector2 Forward = Vector2.Zero;

if (keyboardState.IsKeyDown(Keys.Up)) Forward+= Vector2.UnitY;
if (keyboardState.IsKeyDown(Keys.Down)) Forward-= Vector2.UnitY;
if (keyboardState.IsKeyDown(Keys.Left)) Forward-= Vector2.UnitX;
if (keyboardState.IsKeyDown(Keys.Right)) Forward+= Vector2.UnitX;

if (forward != Vector2.Zero)
{
   PlayerForward = Vector2.Lerp(PlayerVelocity, Forward, RotationSpeed);
   PlayerForward.Normalize();

   PlayerPosition += PlayerForward * Speed;
}

```

This can do the trick, though if angle between forward and playerForward is 180º, it won't turn

If you need the angle... you can use this:

```
 rotation = Math.Atan2(PlayerForward.Y, PlayerForward.X);

```
> 1 votes

---
Tags: xna-4.0, movement, rotation
---