# Question
Title: 2D scene graph not transforming relative to parent
I am currently in the process of coding my own 2D Scene graph, which is basically a port of flash's render engine.

The problem I have right now is my rendering doesn't seem to be working properly. This code creates the `localTransform` property for each `DisplayObject`.

```
Matrix m_transform =
                Matrix.CreateRotationZ(rotation) *
                Matrix.CreateScale(scaleX, scaleY, 1) *
                Matrix.CreateTranslation(new Vector3(x, y, z));

```

This is my render code.

```
float dRotation;
Vector2 dPosition, dScale;
Matrix transform;
transform = this.localTransform;
if (parent != null) transform = localTransform * parent.localTransform;
DecomposeMatrix(ref transform, out dPosition, out dRotation, out dScale);

spriteBatch.Draw(this.texture, dPosition, null, Color.White, dRotation,
new Vector2(originX, originY), dScale, SpriteEffects.None, 0.0f);

```

Here is the result when I try to add the Stage then to the stage a First `DisplayObjectContainer` and then a second one.

It may look fine but the problem lies in the fact that I add a first DisplayObjectContainer at (400,400) and the second one within it (that's the smallest one) at position (0,0). So he should be right over its parent but he gets render within the parent at the same position the parent has (400, 400) for some reason. It's just as if I double the parent's `localMatrix` and then render the second cat there.

This is the code i use to loop through every childs.

```
base.Draw(spriteBatch);
foreach (DisplayObject childs in _childs)
{
    childs.Draw(spriteBatch);
}

```

# Answer
> 1 votes
I could not figure out exactly where the code is failing, but I've noticed several things that you might want to change nonetheless.

**1) The multiplication by the parent transform should be recursive all the way to the root**

I recommend for instance using a recursive `GlobalTransform` property such as:

```
public Matrix GlobalTransform {
  get { return Parent != null ? LocalTransform : LocalTransform * Parent.GlobalTransform;
}

```

Otherwise your scene graph will only work for children one level deep.

**2) Don't translate the Z component**

In your matrix you're doing `Matrix.CreateTranslation(new Vector3(x, y, z))`. I'm not sure but I think using a `z` different from `0` might cause problems because the `SpriteBatch.Draw` parameter called `layerDepth` is the one responsible for controlling the depth of the sprite, and this might mess that up.

**3) You could also add the origin into the transform matrix**

This one is optional ,but if you incorporate the `origin` into your matrix (by doing `-origin * scale * rotation * translation`) and leave it as `Vector2.Zero` on the `SpriteBatch.Draw` call, it can make other tasks easier to implement because you don't have to account for the origins separately.

For example, you could check if the mouse is intersecting the oriented bounding rectangle of the display object simply by multiplying it by the inverse `GlobalTransform` and then seeing if the result is within the `(0,0)` to `(TextureWidth, TextureHeight)` range.

---
Tags: xna, c#, architecture, rendering, scene-graph
---


title: Threading iPhone

text:
# Question
Title: Threading iPhone
Say I have a group of large meshes that I have to intersect rays against. Assume also, for whatever reason, I cannot further simplify/reduce poly check count by spatial subdivisioning. I can do this in parallel:

```
bool intersects( list of meshes ) // a mesh is a group of triangles
{
    create n threads

    foreach mesh in meshes
        assign to a thread in threads

    wait until ( threads.run() ) ; // run asynchronously

    // when they're all done
    // pull out intersected triangles
    // from per-thread context data
}

```

Can you do this in ios for games? Or is the overhead of thread creation and mutex waiting going to beat-out the benefit of multithreading?

# Answer
If your array is a NSArray, use method like -enumerateObjectsUsingBlock:. This method will use GCD and will dispatch enumeration to different cores, according to number of CPU cores and the array size.
> 1 votes

# Answer
iPhone has 2 cores. Your code looks more like you have 8 or 16 cores. If you have 2 cores then you may split app in animation and physics threads. Physics thread would be connected with animation thread with 2 channels (pipes)

Everyframe animation will write commands/messages to pipe and read messages Message may contain anything.

Object A Position Time Velocity

So if phsyics do not give update for object A then animation thread will be able to interpolate position for every frame knowing it original position at a time, ceocity and current time.

With that system you can outsource any tasks to second thread.

But high frame rate is most important. It is more important then long time waiting.
> 0 votes

---
Tags: ios, multithreading
---


title: Making AI jump on a spot effectively

text:
# Question
Title: Making AI jump on a spot effectively
How to calculate, in 3D environment, the closest point, from which an AI character can jump onto a platform?

**Setup**

I have an initial velocity V(Vx,Vy,VZ) and a spot where the character stands still at S(Sx,Sy,Sz). What I'm trying to achieve is a successful jump on a spot E(Ex,Ey,Ez) where you have clicked on(only lower or higher spot, because I've in place a simple steering behavior for even terrains). There are no obstacles around.

I've implemented a formula that can make him jump in a precise way on a spot but you need to declare an angle: the problem arise when the selected spot is straight above your head. It' pretty lame that the char hang there and can reach a thing that is 1cm above is head. I'll share the code I'm using:

```
    Vector3 dir = target - transform.position;  // get target direction
    float h = dir.y;  // get height difference
    dir.y = 0;  // retain only the horizontal direction
    float dist = dir.magnitude ;  // get horizontal distance
    float a = angle * Mathf.Deg2Rad;  // convert angle to radians
    dir.y = dist * Mathf.Tan(a);  // set dir to the elevation angle
    dist += h / Mathf.Tan(a);  // correct for small height differences
    // calculate the velocity magnitude
    float vel = Mathf.Sqrt(dist * Physics.gravity.magnitude / Mathf.Sin(2 *a));
    return vel * dir.normalized;

```

Ended up using the lowest angle (20 degree) and checking for collision on the trajectory. If found any increase the angle. Here some code (to improve the code maybe must stop the check at the highest point of the curve):

```
Vector3 BallisticVel(Vector3 target, float angle)
    {
        Vector3 dir = target - transform.position;  // get target direction
        float h = dir.y;  // get height difference
        dir.y = 0;  // retain only the horizontal direction
        float dist = dir.magnitude ;  // get horizontal distance
        float a = angle * Mathf.Deg2Rad;  // convert angle to radians
        dir.y = dist * Mathf.Tan(a);  // set dir to the elevation angle
        dist += h / Mathf.Tan(a);  // correct for small height differences
        // calculate the velocity magnitude
        float vel = Mathf.Sqrt(dist * Physics.gravity.magnitude / Mathf.Sin(2 * a));
        return vel * dir.normalized;
    }

    Vector3 TrajectoryPoint(Vector3 startingPosition, Vector3 startingVelocity, float n )
    {
         float t = 1/60 ; // seconds per time step
      Vector3 stepVelocity = t * startingVelocity; // m/s
      Vector3 stepGravity = t * t * Physics.gravity; // m/s/s

      return startingPosition + n * stepVelocity + 0.5f * (n*n+n) * stepGravity;
    }

    bool CheckTrajectory(Vector3 startingPosition,Vector3 target, float angle_jump)
    {
        Debug.Log("checking");
        if(angle_jump < 80f)
        {
            Debug.Log("if");

            Vector3 startingVelocity = BallisticVel(target, angle_jump);

            for (int i = 0; i < 180; i++)
            {
                //Debug.Log(i);
                Vector3 trajectoryPosition = TrajectoryPoint( startingPosition, startingVelocity, i );

                if(Physics.Raycast(trajectoryPosition,Vector3.forward,safeDistance))
                {
                    angle_jump += 10;
                    break; // restart loop with the new angle
                }
                else
                    continue;

            }

                return true;
                JumpVelocity = BallisticVel(target, angle_jump);
            }

        return false;
    }

```

# Answer
Your question is still missing the physics of your jumps. Does player's avatar accelerate when in air? Do jump physics simulate gravity well? That is the avatar's initial Vy is decelerated by 9.81 m/s every second? Still, I will present you a way how easily solve this mathematic problem.

1. Let's start with representing our problem. In this case we can do this in 2D!
2. Now let's assume a few things:
    * we're using real physics (considering gravity, but not considering air friction etc.)
    * you can still steer while in air, and therefore, you can easily avoid such situation:
    * this means we should only care about being near enough to be able to jump onto a platform; we want to find an outermost distance from our target, that we can jump through to it.
3. Let's analyze what happens, when we jump:
    * we get initial speed **Vy**
    * gravity makes this speed decrease by **g** m/s every second
    * at some moment we reach the highest point and start to fall
    * speed increases by **g** m/s until we fall on something
    * all this time we're moving 'forward' by our initial velocity **Vx**
    * moreover, all this time we're accelerating (because if we want to reach the platform from the furthest place possible, we need to hold UP key), increasing our **Vx**
    * what we want to know is, how long have we been in air, and therefore, how much could we travel.
4. Time of the jump
    * here's a nice article about jump math: How to Calculate the Jump Height From Acceleration
    * time to reach top of our jump is: **t = Vy/g** (it's obvious, we need to lose our vertical speed completely)
    * height of our jump is: **h = Vy*t + (g*t²)/2** WARNING: this formula assumes your "g" is a negative number. if not, change the formula to: **h = Vy*t - (g*t²)/2**
    * formula for time we will fall from there to the platform is: where **d** is `h - platform.height` (taken from Wikipedia:Equations for a falling body)
    * sum both t, and we get a time of our jump.
5. Now we need to know how far the player will move during the jump. If he doesn't accelerate, this will be `distance = Vx*t`, but he does. So there's formula for that too: `d = Vt + (1/2)at²`
6. We found the max distance of the jump! You need to get to the platform to that distance or closer to be able to jump onto it - good luck!

And here's code:

```
var vertical_distance:Number = platform.height - ground.height;
var Vh:Number = Math.sqrt ( Vx*Vx + Vz*Vz );
var time_to_top:Number = Vy/GRAVITY;
var jump_height:Number = Vy*time_to_top - GRAVITY*time_to_top*time_to_top/2
if ( jump_height >= vertical_distance ) {
   var falling_distance:Number = jump_height - vertical_distance;
   var time_to_fall:Number = Math.sqrt ( 2 * falling_distance / GRAVITY );
   var jump_time:Number = time_to_top + time_to_fall;
   var jump_length = Vh*jump_time + .5 * ACCELERATION * jump_time * jump_time;
   return jump_length;
} else throw error or something

```

Check out The Jumping Squareman minigame!
> 7 votes

---
Tags: physics
---


# Question
Title: Working out of a vertex array for destrucible objects
I have diamond-shaped polygonal bullets. There are lots of them on the screen.

I did not want to create a vertex array for each, so I packed them into a single vertex array and they're all drawn at once.

```
| bullet1.xyz | bullet1.rgb | bullet2.xyz | bullet2.rgb

```

This is great for performance.. there is

```
struct Bullet
{
    vector<Vector3f*> verts ; // pointers into the vertex buffer
} ;

```

This works fine, the bullets can move and do collision detection, all while having their data in one place.

Except when a bullet "dies"

Then you have to clear a slot, and pack all the bullets towards the beginning of the array.

Is this a good approach to handling lots of low poly objects? How else would you do it?

# Answer
> Then you have to clear a slot, and pack all the bullets towards the beginning of the array.

Don't shuffle all the bullets down toward the beginning of the array; just swap the last bullet into the newly cleared slot. That way you don't need to repack the whole vector; you only need to move a single element to fill the space that was made by the dead bullet.
> 4 votes

# Answer
If the number of bullets is fixed at the start, then you can leave the vert data in the array. Create a second array that is a list of Booleans that represent each bullet. As a bullet dies flip the value in the second tracking array to false. Use this array as a filter for you vertex loop.

So if each bullet has 4 verts, the second array is 1/4 the size, with each boolean representing 1 bullet of 4 verts.
> 3 votes

---
Tags: rendering, low-poly
---


# Question
Title: How to render axometric/isometric tiles that are a 2d array in logic, but inclined 45º visually?
I am making a tile-based strategy game which i plan to have 2.5D visuals in an axometric/isometric fashion.

Right now i'm programming it's logic and rendering it as a literal 2-dimensional array (perfect squares, like an isometric top-down-view).

In short, i have something like this:

And i want to turn it to something like this:

---

Do i keep going on the 2d-array logic?

Is it all just a change in rendering behavior, as i'm thinking it is? or 2d-array is the wrong approach for my objective and I should change before it's too late?

What are the ways of doing it, anyways? How should i apply the 2.5D axometric/isometric view (45º rotation to the side, and 45º rotation upwards)?

# Answer
> 1 votes
Yes, that's exactly what you should do! Only a few days ago I answered another guy, suggesting him such logic here: Free movement in a tile-based isometric game

This is a simple MVC approach. Keep your model and controller simple, every 3D game with objects on flat surface with same height and on same height is really 2D underneath it's view.

# Answer
> 2 votes
A good example with pictures using libgdx was provided in libgdx's blog Isometric Tilemap Rendering with libgdx

# Answer
> 1 votes
Yes, isometric maps are just rendered differently. For the game logic it makes no difference what kind of angle the coordinates have.

Isometric rendering is similar to the rendering of square tiles, the difference is just how the tiles are aligned (how the drawing position is calculated).

Instead of drawing tile *x,y* at

```
x*tileWidth, y*tileHeight

```

they are drawn at

```
tileWidth/2*x+tileHeight/2*y, tileWidth/2*x+tileHeight/2*y

```

---
Tags: java, isometric, lwjgl, slick, 2.5d
---


# Question
Title: How do I render a 2D sprite in 3D space?
I am currently working on a game in XNA 4.0, where I want to implement 2.5D, like in *"Paper Mario"*. I feel like it has something to do with z-buffering a Texture2D, and drawing that, but I really have no idea where to start.

How do I render a 2D sprite in 3D space?

# Answer
> 2 votes
Rendering a 2D sprite in a 3D space could be handled as a specific case of rendering a 3d object. The 3d model being a flat rectangular shape that is textured with the sprite in question. This is how I would suggest you handle your sprites.

I think this tutorial gives an example:

http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series2/Point\_sprites.php

The way bullets are handled there (2d images in 3d space) is what you are looking to do with characters in your game.

---
Tags: xna, 3d
---


title: One-way platform collision

text:
# Question
Title: One-way platform collision
I hate asking questions that are specific to my own code like this, but I've run into a pesky roadblock and could use some help getting around it. I'm coding floating platforms into my game that will allow a player to jump onto them from underneath, but then will not allow players to fall through them once they are on top, which require some custom collision detection code. The code I have written so far isn't working, the character passes through it on the way up, and on the way down, stops for a moment on the platform, and then falls right through it. Here is the code to handle collisions with floating platforms:

```
protected void HandleFloatingPlatforms(Vector2 moveAmount)
    {
        //if character is traveling downward.
        if (moveAmount.Y > 0)
        {
            Rectangle afterMoveRect = collisionRectangle;
            afterMoveRect.Offset((int)moveAmount.X, (int)moveAmount.Y);
            foreach (World_Objects.GameObject platform in gameplayScreen.Entities)
            {
                if (platform is World_Objects.Inanimate_Objects.FloatingPlatform)
                {
                    //wideProximityArea is just a rectangle surrounding the collision
                    //box of an entity to check for nearby entities.
                    if (wideProximityArea.Intersects(platform.CollisionRectangle) ||
                        wideProximityArea.Contains(platform.CollisionRectangle))
                    {
                        if (afterMoveRect.Intersects(platform.CollisionRectangle))
                        {
                            //This, in my mind would denote that after the character is moved, its feet have fallen below the top of the platform, but before he had moved its feet were above it...
                            if (collisionRectangle.Bottom <= platform.CollisionRectangle.Top)
                            {
                                if (afterMoveRect.Bottom > platform.CollisionRectangle.Top)
                                {
                                    //And then after detecting that he has fallen through the platform, reposition him on top of it...
                                    worldLocation.Y = platform.CollisionRectangle.Y - frameHeight;
                                    hasCollidedVertically = true;

                                }
                            }
                        }
                    }
                }
            }
        }
    }

```

In case you are curious, the parameter moveAmount is found through this code:

```
elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

        float totalX = 0;
        float totalY = 0;

        foreach (Vector2 vector in velocities)
        {
            totalX += vector.X;
            totalY += vector.Y;
        }

        velocities.Clear();

        velocity.X = totalX;
        velocity.Y = totalY;

        velocity.Y = Math.Min(velocity.Y, 1000);

        Vector2 moveAmount = velocity * elapsed;

```

# Answer
> 2 votes
Sorry for wasting anybody's time; I located my issue, it wasn't actually with my collision resolution code, just where I had placed it in my character's class.

The original code looked like this:

```
        Vector2 moveAmount = velocity * elapsed;

        slopeCollisionMode = false;

        moveAmount = horizontalCollision(moveAmount, layer);
        moveAmount = verticalCollision(moveAmount, layer);

        //The problem exists right here.
        HandleFloatingPlatforms(moveAmount);

        if (hasCollidedVertically)
        {
            selfSpeed.Y = 0;
        }
        if (hasCollidedHorizontally)
        {
            selfSpeed.X = 0;
        }

        Location newPosition = new Location((worldLocation.X + (int)moveAmount.X),(worldLocation.Y + (int)moveAmount.Y));

        newPosition = new Location(
            (int)MathHelper.Clamp(newPosition.X, 0, layer.Map.DisplayWidth - frameWidth),
            (int)MathHelper.Clamp(newPosition.Y, -layer.Map.DisplayHeight * 2, layer.Map.DisplayHeight + frameHeight));

        oldLocation = worldLocation;
        worldLocation.X = (int)newPosition.X;
        worldLocation.Y = (int)newPosition.Y;

        collisionRectangle = new Microsoft.Xna.Framework.Rectangle(WorldLocation.X + 39, WorldLocation.Y + 21, 50, 78);

```

Being as HandleFloatingPlatforms() adjusts the world location of the entity, it being placed before the character is even moved, its adjustments were just being overwritten a few lines down. After readjusting a few things, it works. The working code looks like this:

```
Vector2 moveAmount = velocity * elapsed;

        slopeCollisionMode = false;

        moveAmount = horizontalCollision(moveAmount, layer);
        moveAmount = verticalCollision(moveAmount, layer);

        Location newPosition = new Location((worldLocation.X + (int)moveAmount.X),(worldLocation.Y + (int)moveAmount.Y));

        newPosition = new Location(
            (int)MathHelper.Clamp(newPosition.X, 0, layer.Map.DisplayWidth - frameWidth),
            (int)MathHelper.Clamp(newPosition.Y, -layer.Map.DisplayHeight * 2, layer.Map.DisplayHeight + frameHeight));

        oldLocation = worldLocation;
        worldLocation.X = (int)newPosition.X;
        worldLocation.Y = (int)newPosition.Y;

        HandleFloatingPlatforms(moveAmount);

        collisionRectangle = new Microsoft.Xna.Framework.Rectangle(WorldLocation.X + 39, WorldLocation.Y + 21, 50, 78);

        if (hasCollidedVertically)
        {
            selfSpeed.Y = 0;
        }
        if (hasCollidedHorizontally)
        {
            selfSpeed.X = 0;
        }

```

# Answer
> 1 votes
Where do you get the `frameHeight` variable from, is it large enough to ensure the `worldLocation.Y` will be low enough to meet the condition `collisionRectangle.Bottom <= platform.CollisionRectangle.Top` the second time? You said that it stops for a second and then continues to fall so my educated guess is that you are not fixing it up enough.

Give this a shot:

```
worldLocation.Y = platform.CollisionRectangle.Y - frameHeight - 20;

```

See if it gets stuck on top, 'bouncing' in a jerky motion.

If that is the case then `frameHeight` is too small to correct the player back on the platform right after the player falls through.

It appears the issue was in the order of the code. The player fell through the platform, it was detected and the speed on y-axis was reset(hence he stopped for a second). Moving the player was handled after that and the player was moved through the platform to the originally designated new position.

---
Tags: xna, 2d, xna-4.0, physics, platformer
---


# Question
Title: Camera changes view when controller connected
I have a weird situation. I have a model set to 0 for X,Y and Z. My camera's position is set to:

* 0 (X-value, but updates when the model moves around)
* the model's height + 20f (about the same level as the model's shoulders)
* `25f` (behind the model)

Without the controller plugged in, everything looks fine as I want it. But as soon as I plug the controller in, the camera aims to the sky! But when I unplug the controller, the camera is back to what it should be.

Does anyone have any insight as to what may cause this from plugging a controller in?

# Answer
> 1 votes
Based upon your observation that the camera changes when you plug in a controller, your program apparently has some code which notices that a controller is connected, and changes the camera behaviour in that situation.

If you remove or disable that code, then connecting a controller should stop causing problems.

Hope this helps.

---
Tags: xna, camera, xbox-controller
---


# Question
Title: Depth buffer values reset on change shader?
I have 2 different shaders, and when I change the shader (glUseProgram), it *seems* that the depth information is lost, because everything drawn with the 2nd shader appears completely on top of anything drawn by the first shader.

If I switch the order of shader use/drawing, then it's the same (the last drawn object always appears on top of the first drawn object if there is a shader change between the 2 objects, even if the last drawn object is further away)

# Answer
Ok, I had the depth test enabled but I didn't have a depth buffer. That was surprising!

To add a depth buffer in ES2:

The entire `init` and `resizeFromLayer` functions become:

```
// Create an ES 2.0 context
- (id <ESRenderer>) init
{
  if (self = [super init])
  {
    context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];

    // Create the vertex formats + shaders
    if (!context || ![EAGLContext setCurrentContext:context] || ![self loadShaders])
    {
      return nil;
    }

    // Create default framebuffer object. The backing will be allocated for the current layer in -resizeFromLayer
    glGenFramebuffers(1, &defaultFramebuffer);
    glGenRenderbuffers(1, &colorRenderbuffer);

    glBindFramebuffer(GL_FRAMEBUFFER, defaultFramebuffer);
    glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorRenderbuffer);

    /////NEW!!////////////////////////
    glGenRenderbuffers(1, &depthRenderbuffer);
    glBindRenderbuffer(GL_RENDERBUFFER, depthRenderbuffer);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderbuffer);
  }
  return self;
}

- (BOOL) resizeFromLayer:(CAEAGLLayer *)layer
{
  // Allocate color buffer backing based on the current layer size
  glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer);
  [context renderbufferStorage:GL_RENDERBUFFER fromDrawable:layer];

  int backingWidth,backingHeight;

  /////NEW!!////////////////////////
  glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth);
  glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight);
  glBindRenderbuffer(GL_RENDERBUFFER, depthRenderbuffer);
  glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, backingWidth, backingHeight);
  glBindRenderbuffer(GL_RENDERBUFFER, colorRenderbuffer); // linked post says need this

  if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
  {
    NSLog(@"Failed to make complete framebuffer object %x", glCheckFramebufferStatus(GL_FRAMEBUFFER));
    return NO;
  }

  return YES;
}

```
> 1 votes

# Answer
I'll confirm that the depth buffer is not cleared by OpenGL ES2 when changing shaders.

If it appears to be doing so in your code, that indicates a bug on your side. Check for calls to `glClear(GL_DEPTH_BUFFER_BIT)` which might be getting triggered indirectly from your shader-changing code (I recommend putting a breakpoint on every call to glClear in a debugger, to see exactly when they're being called)

You should probably also check that you're not calling `glDisable(GL_DEPTH_TEST)` or modifying `glDepthFunc()` in a way that would result in the depth buffer appearing to have been cleared, when actually the depth test has been completely disabled (these two different issues can often look identical, in many types of scenes).
> 3 votes

---
Tags: shaders, glsl, opengl-es2
---


# Question
Title: What's the difference between Canvas and WebGL?
I'm thinking about using CAAT as a part of a HTML5 game engine. One of it's features is the ability to render to Canvas and WebGL without changing anything in the client code. That is a good thing, but I haven't found precisely: what are the differences between those two technologies?

I would specially like to know the differences of Canvas and WebGL in the following regards:

* Framerate
* Desktop browser support
* Mobile browser support
* Futureproofability (TM)

# Answer
1. Framerate varies by browser. A few still do not support accelerated canvas rendering, others don't support WebGL at all. Best bet is to profile actual code on actual target hardware/browsers to determine which performs best for your specific needs and user demographics.
2. WebGL is only supported on IE in version 11+ but canvas has been supported for several versions. Consider the current market share of older versions of IE.
3. WebGL support is sometimes blacklisted by the browser on older hardware or drivers. When it comes to support, you need to consider this in addition to the minimum browser versions, and clearly communicate these requirements to customers.
4. Few mobile browsers support WebGL today. They mostly all support canvas.
5. Both canvas and WebGL are around to stay. Neither is more future proof than the other.
> 10 votes

---
Tags: html-canvas, webgl
---


title: Server-side Input

text:
# Question
Title: Server-side Input
Currently in my game, the client is nothing but a renderer. When input state is changed, the client sends a packet to the server and moves the player as if it were processing the input, but the server has the final say on the position.

This generally works really well, except for one big problem: falling off edges. Basically, if a player is walking towards an edge, say a cliff, and stops right before going off the edge, sometimes a second later, he'll be teleported off of the edge. This is because the "I stopped pressing W" packet is sent after the server processes the information.

Here's a lag diagram to help you understand what I mean: https://i.stack.imgur.com/SPPAB.png

I could just send a "W Pressed" packet each frame for the server to process, but that would seem to be a bandwidth-costly solution.

Any help is appreciated!

# Answer
While the server has the final say on the position, it should do that by verifying and sanity-checking what the client sends over as the inputs and position. I say this because what you're doing is moving the player immediately and the expectation that creates in your code is that the client is the real position.

You think it generally works well, but it's not. Side note: you say that your client is nothing more than a renderer, then promptly give it local control to move around without server messages. You can't have it both ways, either wait for the server to tell you to move or assume some control over your position and use the server to verify cheats.

I note that your responses are reaching one whole second? That's 500ms latency which is ridiculously large for any kind of action game. Try to find out why this turnaround is taking so long, it could be anything from command queues backing up from not getting handled promptly to flooded bandwidth or even demons causing many lost packets.

What I think should happen is that

```
client sends a move + position update
server gets it t+latency time later
server verifies and sends out info to all clients
client receives this at (t+latency + latency)

```

The tricky part here is that if a client receives a message about itself it should mostly ignore it unless that message is something like "invalid move, go to XYZ instead." If that message is for anyone else's client that you're getting info about then you'll have to extrapolate forwards in time so it looks to be kind of where it will be.
> 5 votes

# Answer
I understand you question as:

The server gets a packet when I start pressing the 'forward' button and another packet when I finally released the 'forward' button. Therefore the actual movement on the server starts and ends about 100 milliseconds 'too late' in actual game vs. what the player is expressing on the client-side. So if the player wants to move 10 seconds, he may end up move 10.x seconds instead where `x >= 1` online.

This is a bad design strategy because it does not express the player's will in the game world as the player intends, creating a rather poor user experience.

The solution I would recommend is sending a packet (as often as you can) that indicates how many steps the player took and in which direction. The server then updates the game world with the new player location if it passes a correctness check. So the player can move with great precision and avoid falling off high ledges.

The alternative would be to remember the player's positions in the past second and correct the position in retrospect to the time the button was released. Sounds like it would create that rubber-band effect of the olden days.(only for a different reason)

So basically you would need to send a packet of which button is pressed and what was the actual game time the button was pressed and then later, which button was released and at what exact time.
> 0 votes

---
Tags: xna, c#, networking, interpolation, udp
---


title: Interaction using Kinect in XNA

text:
# Question
Title: Interaction using Kinect in XNA
So i have written a program to play a sound file when ever my RightHand.Joint touches the 3D model . . It goes like this . . even though the code works somehow but not very accurate . . for example it will play the sound when my hand is slightly under my 3D object not exactly on my 3D object . How do i make it more accurate? here is the code . . (HandX & HandY is the values coming from the Skeleton data RightHand.Joint.X etc) and also this calculation doesnt work with Animated Sprites..which i need to do

```
foreach (_3DModel s in Solar)
{
    float x = (float)Math.Floor(((handX * 0.5f) + 0.5f) * (resolution.X));
    float y = (float)Math.Floor(((handY * -0.5f) + 0.5f) * (resolution.Y));
    float z = (float)Math.Floor((handZ) / 4 * 20000);

    if (Math.Sqrt(Math.Pow(x - s.modelPosition.X, 2) + Math.Pow(y - s.modelPosition.Y, 2)) < 15)
    {
        //Exit();
        PlaySound("hyperspace_activate");

        Console.WriteLine("1" + "handx:" + x + "," + " " + "modelPos.X:" + s.modelPosition.X + "," + " " + "handY:" + y + "modelPos.Y:" + s.modelPosition.Y);
    }

    else
    {
        Console.WriteLine("2" + "handx:" + x + "," + " " + "modelPos.X:" + s.modelPosition.X + "," + " " + "handY:" + y + "modelPos.Y:" + s.modelPosition.Y);
    }
}

```

# Answer
Instead of testing for distance to can test if it is contained. The Problem with distance is that it forms a circle of acceptance around you model (with radius=15 with the given code) so either way you can decrease the radius or switch to containing test.

For this change the if statement to something like this (Pseudo)

```
if(x>=s.model.PosX && x<=s.model.PosX+s.model.Width && y>=s.model.PosY && y<=s.model.PosY+s.model.Height)

```

This will test with a rectangular shape. If you want a really 100% accurate result you will have to look into *picking* (This may get you started)

Hope this helps ;)

floAr
> 2 votes

---
Tags: xna-4.0, kinect
---


# Question
Title: Why is C++ used for game engines? How about its future in game engines?
C++, as I have seen, is being heavily used in 3d video game engines.... Is it because of the performance issues, legecy code or libraries such as DriverX?

If performance, libraries and code infrastructure are the reasons, dosen't that make C++ indispensible, at least for game engines? (ie, we have no other option even in the very distant future).

I asked this because, I have the right to know the upcomming future trends in game engines.

# Answer
Some reasons off the top of my head because there are no, IMHO, technical no goers to have say a C# engine:

* It has been like that for long time (so Nintendo won't send you a python engine because your team programs in python)
* C++ is *Fast* (which is good not only for physics engines but also for scene node traversal, occlusion queries, ...)
* I'm not sure about this but maybe (personal opinion here!) : You hire a C++ programmer because if you can program in C++ you are at least at a minimum level and can easily learn other languages / techniques. Maybe I'm just believing that there is some sort of C++ Lisp-like genius myth though.
* C++ can be very *efficient* when it comes to memory usage. A low overhead of your triangle class is important when you want to load up 12 million triangles in your octree.
* There are a lot of libraries compilers and tools, well tested, out there for C++.

But I guess it's most historical reasons.

Don't forget that many engines comes with *bindings* to other languages. They are coded in one (say C/C++) but can be used by another (say java).
> 4 votes

---
Tags: c++
---


# Question
Title: Is it possible to emulate a MovieTexture with dynamically loaded images?
Say I have a short video and want to play the video in a game scene, but I can't use the MovieTexture for whatever reason. Is it technically possible and feasible to dynamically load images (in a flip book fashion) in order to emulate a video being played in a scene?

# Answer
> 1 votes
It is possible, the limitation is not in the software. Depends on the resolution of the video and the total amount of frames, it could use a lot of memory. The reason a video is not saved as collection of jpeg's or png's is compression.Raw video data in a resolution of 512 x 512 and a frame rate of 10fp that lasts about one minute would take about:

```
3 bytes * (512 * 512)res * 10 fps * 60 seconds = 500 MB

```

That does not sound like a reasonable way to handle it.

If you had only 3 seconds of 256 x 256 a the same rate, it would still take around 5 MB so I would only use it as a workaround in cases where I felt it was necessary.

Once the raw data is in memory, it is possible to display it as a texture.

---
Tags: video
---


# Question
Title: How to code Time Stop or Bullet Time in a game?
I am developing a single-player RPG platformer in XNA 4.0. I would like to add an ability that would make the time "stop" or slow down, and have only the player character move at the original speed(similar to the Time Stop spell from the Baldur's Gate series). I am not looking for an exact implementation, rather some general ideas and design-patterns.

**EDIT:** Thanks all for the great input. I have come up with the following solution

```
    public void Update(GameTime gameTime)
        {

            GameTime newGameTime = new GameTime(gameTime.TotalGameTime,
 new TimeSpan(gameTime.ElapsedGameTime.Ticks / DESIRED_TIME_MODIFIER));
            gameTime = newGameTime;

```

or something along these lines. This way I can set a different time for the player component and different for the rest. It certainly is not universal enough to work for a game where warping time like this would be a central element, but I hope it should work for this case. I kinda dislike the fact that it litters the main Update loop, but it certainly is the easiest way to implement it. I guess that is essentialy the same as tesselode suggested, so I'm going to give him the green tick :)

# Answer
This might be a bad solution, but not necessarily. If you're using delta time, you can change that to change the speed of certain things.

For example:

```
player.update(dt)
dt = dt * .5 --half speed
enemy.update(dt)

```

This, of course, only works if you can tell when you're updating the enemy rather than something else. You could also just give everything a speed value and do something like:

```
x = x + xspeed * dt * speed

```
> 8 votes

# Answer
Using delta time(milliseconds that passed since the last frame) may not be sufficient to slow enemies down. Things like attack rate might be implemented based on the last attack time. While it will slow down movement if it is time based, it will neglect to slow attack rate, spell casting and other effects (Health regeneration, spell effects duration).. and such

If you want to slow down a large group of game elements in a single player game, you could create a second internal clock for each creature, the clock starts at the current time when the creature appears. When a slow spell is cast, each frame, the clock is incremented by x% of the time that actually passed. All monster behavior is then determined by it's internal clock. If various monsters have resistance to slow, they can use their own clock, it is basically an integer that does not require a lot of space or computation.

When the slow effect stops, the clocks are still being used and get incremented by 100% of the time that actually passed.

This could also work for hasten spells.

@Sidar : I see two choice,

1. Internal clock per creature. In order to find out if the creature is ready to attack again: save the the last time each attack was used + recharge time and check if the internal clock is already passed that time.
2. One timer per attack: You know how long it takes the attack to recharge and you simply set a timer and subtract the time that passed * (1-slowdown%) each turn.

I personally prefer to avoid subtracting multiple individual timers and user one internal clock to save on processing time and complexity.

It is really up to preference(It doesn't affect performance that much).
> 3 votes

# Answer
You can start with a simple solution as the one exposed by tesselode or Mr Beast. But if you start mixing complex things, i.e. a bullet time *while* a slowdown spell is cast, you'll get stuck.

I suggest you implement a **clock hierarchy**:

```
.
├── Main clock
│   └── UI clock
│   └── 3D clock
│       ├── GFX clock
│       └── Gameplay clock
│           └── Slowdown spell clock 01
│           └── Slowdown spell clock 02

```

Everything in your game should use delta times from one of the clock: graphics effects run on the GFX clock, AI & animation runs on the Gameplay clock, creatures affected by a slowdown spell run on a temporary Slowdown spell clock, etc. Then various things affect different parts of your hierarchy: a slowdown spell creates and affects a custom clock, while a bullet time will affect the whole 3D clock hierarchy.
> 2 votes

# Answer
You just need two different clocks instead of one, one for the time relevant to the gameplay and one "true" time.

```
currentGameTime = 0;
gameSpeed = 1.0f;
[...]
currentApplicationTime = GetTime():
timeDelta = (currentApplicationTime - lastApplicationTime)*gameSpeed;
currentGameTime += timeDelta;
lastApplicationTime = currentApplicationTime;

```

Then you can simply change gameSpeed to speed up (\>1) or slow down time (\<1). For the player to move at different speed just check wheter the time is slowed down or not.
> 1 votes

---
Tags: xna, time-travel
---


# Question
Title: Free movement in a tile-based isometric game
Is there a reasonable easy way to implement free movement in a tile-based isometric game? Meaning that the player wouldn't just instantly jump from one tile to another or not be "snapped" to the grid (for example, if the movement between tiles were animated but you'd be locked from doing anything before the animation finishes). I'm a really beginner with anything related to game programming, but with the help of this site and some other resources it was quite easy to do the basic stuff, but I haven't been able to find any useful resources for this particular problem.

Currently I've improvised something close to this: http://jsfiddle.net/KwW5b/4/ (WASD movement). The idea for the movement was to use the mouse map to detect when the player has moved to a different tile and then flip the offsets, and for the most part it works correctly (each corner makes the player move to wrong location: see http://www.youtube.com/watch?v=0xr15IaOhrI, which is probably because I couldn't get the full mouse map work properly), but I have no illusions that it is even close to a good/sane solution. And anyway, it's mostly just to demonstrate what kind of a thing I'd like to implement.

# Answer
> 10 votes
First of all I suggest that you change directions from: W - up-left S - down-right A - down-left D - top-right

into more intuitive: W - up S - down A - left D - right

As for your concern, I suggest that you make two functions, one translating isometric tile coordinates into grid coordinates, and second the other way around. That way you could simply separate MVC and it would make your life easier when computing active tile:

# Answer
> 0 votes
If I understand, you want the player move tile to tile but without jumping. You can:

1- Start with tile t0 and offset 0

2- When player move to tile t1 set offset = -(t1 - t0)

3- In the player update, if offset is not 0, decrement using the update time and player speed.

```
amount = deltatime * playerSpeed
deltaoff = sqrt(offsetX*offsetX + offsetY*offsetY)
total = min( amount, deltaoff )
offsetX = offsetX - (total * offsetX / deltaoff)
offsetY = offsetY - (total * offsetY / deltaoff)

```

4- Yo can use offset == 0 check to know when player is on tile.

With this you get a player that move free in the map but stick to the tiles.

---
Tags: html5, movement, isometric, html-canvas
---


# Question
Title: How to create OpenGL (ES 1.0) texture programmatically?
I need to draw inside a buffer and then upload it as texture to OpenGL. So basicaly unsigned char\* buffer and then call to glTexImage2D().

I will be using Marmalade mobile SDK and OpenGL ES 1.0.

# Answer
You're looking for a frame buffer object (FBO). If you're buffer generating doesn't need anything too complex, you can just do as you said..
> 1 votes

# Answer
In addition to DevilWithin's answer using FBOs, you can also use `glCopyTex(Sub)Image2D` if FBOs are not supported (which may be the case on an ES 1.0 device, don't know). This invloves a copy, but only a single GPU-GPU copy, since it copies the current framebuffer directly into the texture. But by any means don't do a `glReadPixels` followed by a `glTexImage2D`.
> 1 votes

# Answer
This function can create 4 different OpenGL textures (red, green, blue, or chessboard) programmatically, of size `VIEW_TEX_SIZE` x `VIEW_TEX_SIZE`. It returns the texture ID.

```
GLuint colourTexture(int colour)
{
    GLubyte image[VIEW_TEX_SIZE][VIEW_TEX_SIZE][3]; // RGB storage

    for (int i = 0; i < VIEW_TEX_SIZE; i++)
    {
        for (int j = 0; j < VIEW_TEX_SIZE; j++)
        {
            switch(colour)
            {
                case 0:
                    image[i][j][0]  = (GLubyte)255;
                    image[i][j][1]  = (GLubyte)0;
                    image[i][j][2]  = (GLubyte)0;
                    break;
                case 1:
                    image[i][j][0]  = (GLubyte)0;
                    image[i][j][1]  = (GLubyte)255;
                    image[i][j][2]  = (GLubyte)0;
                    break;
                case 2:
                    image[i][j][0]  = (GLubyte)0;
                    image[i][j][1]  = (GLubyte)0;
                    image[i][j][2]  = (GLubyte)255;
                    break;
                case 3:
                    int c = ((((i & 0x8) == 0) ^ ((j & 0x8)) == 0))*255;
                    image[i][j][0]  = (GLubyte)c;
                    image[i][j][1]  = (GLubyte)c;
                    image[i][j][2]  = (GLubyte)c;
                    image[i][j][3]  = (GLubyte)255;
                    break;
            }
        }
    }

    GLuint texName;
    glGenTextures(1, &texName);
    glBindTexture(GL_TEXTURE_2D, texName);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, VIEW_TEX_SIZE, VIEW_TEX_SIZE, 0, GL_RGB, GL_UNSIGNED_BYTE, image);

    return texName;
}

```
> 1 votes

# Answer
Marmalade has exactly that example

```
c:\Marmalade\6.0.6\examples\IwGL\IwGLExt\

```

It implements CFBO class that is used to render in buffer then it uses FBO's texture for further rendering.

Also it checks if FBO extension is available if there is not FBO extension then you get red square texture 1x1 pixel size.
> 0 votes

---
Tags: opengl-es, graphics-programming, marmalade
---


# Question
Title: Procedural object generation and unique identification
My question relates to procedural content generation and data management of the emerging objects in a database.

I assume a networked game, with a server-client model. Unspecified objects in the game world are generated while the game is running with procedural algorithms (for example perlin noise). The players (/clients) can modify the properties of these objects, but have to notify the server of these changes. How could this communication address unique objects, so that both the server and the client know of which object they are speaking?

Not only the inner properties of the objects can differ, but also visible, such as the position. When the player wants to select one of these objects the game has to find out the id - does anyone know which methods or algorithms can accomplish that?

# Answer
To simplify the discussion lets assume a 2d - world. Let us also decide the world is divided into sectors, a gird of squares.

We wish to prevent cheating so all objects are generated on the server side.

When a player reaches a certain area, the server informs the client of all relevent objects in his sector and adjacent sectors. When the player is informed of the objects, it also receives their position which is needed for rendering and their visual data which type of image or model should be rendered to represent them, as well as their bounding boxes (the space they take in the world).

When a player is near one of these objects, since the client has already received the object collection from the server, it knows their 'index' or unique id and sends a packet to the server with an object id and an action. since each movement by the player has to be authorized by the server (to prevent cheating) the server also knows where the player is standing and if she is close enough to interact with the object. If these conditions are met, the action is authorized and the object data is modified on the server side Data Model.

The object you are interacting with could be decided based on proximity and the angle in which you are facing.
> 1 votes

# Answer
In a client-server model, all procedural generation should be performed on the server. When your server generates an object, it gives it an UID, which is then used in all client-server communications.

If you're doing procedural generation on the client, then this isn't only a client.
> 4 votes

---
Tags: game-design, networking, procedural-generation
---


# Question
Title: How to create array with unique sprites? in cocos2d iphone
I write the code like this. This displays only one sprite (red colour bubble) with number of times and moving down, but actually I want to display different sprites (different colour bubble) every time and moving down. I also add no of .png images in resource folder of my project. Here I used only 3.png, but I need to display all \*.png images (different colour bubbles) in my project but I don't know how to get this. Please help me Thank you. Here is the code:

```
-(void)addTarget {
CCSprite *target = [CCSprite spriteWithFile:@"3.png" rect:CGRectMake(0, 0, 256, 256)];

CGSize winSize = [[CCDirector sharedDirector] winSize];
int minY = target.contentSize.height/2;
int maxY = winSize.height - target.contentSize.height/2;
int rangeY = maxY - minY;
int actualY = (arc4random() % rangeY) + minY;

// Create the target slightly off-screen along the right edge,
// and along a random position along the Y axis as calculated above
target.position = ccp(winSize.width + (target.contentSize.width/2), actualY);

[self addChild:target];

// Determine speed of the target
int minDuration = 4.0;
int maxDuration = 12.0;
int rangeDuration = maxDuration - minDuration;
int actualDuration = (arc4random() % rangeDuration) + minDuration;

// Create the actions
id actionMove = [CCMoveTo actionWithDuration:actualDuration position:ccp(-target.contentSize.width/2,actualY)];
id actionMoveDone = [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)];
[target runAction:[CCSequence actions:actionMove, actionMoveDone, nil]];

// Add to targets array
target.tag = 2;
[_targets addObject:target];
}

-(void)gameLogic:(ccTime)dt {

[self addTarget];

}

-(id) init
{

if( (self=[super initWithColor:ccc4(255,255,255,255)] )) {

// Enable touch events
self.isTouchEnabled = YES;

// Initialize arrays
_targets = [[NSMutableArray alloc] init];
_projectiles = [[NSMutableArray alloc] init];
// Get the dimensions of the window for calculation purposes

CGSize winSize = [[CCDirector sharedDirector] winSize];

[self schedule:@selector(gameLogic:)
interval:1.0];
[self schedule:@selector(update:)];

}
return self;
}

- (void)update:(ccTime)dt {

NSMutableArray *projectilesToDelete = [[NSMutableArray alloc] init];
for (CCSprite *projectile in _projectiles) {
CGRect projectileRect = CGRectMake(projectile.position.x - (projectile.contentSize.width/2),
projectile.position.y - (projectile.contentSize.height/2),
projectile.contentSize.width,
projectile.contentSize.height);

NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init];
for (CCSprite *target in _targets) {
CGRect targetRect = CGRectMake(target.position.x - (target.contentSize.width/2),
target.position.y - (target.contentSize.height/2),
target.contentSize.width,
target.contentSize.height);

if (CGRectIntersectsRect(projectileRect, targetRect)) {
[targetsToDelete addObject:target];
}
}

for (CCSprite *target in targetsToDelete) {
[_targets removeObject:target];
[self removeChild:target cleanup:YES];
_projectilesDestroyed++;
if (_projectilesDestroyed > 30) {
//GameOverScene *gameOverScene = [GameOverScene node];
//  [gameOverScene.layer.label setString:@"You Win!"];
//  [[CCDirector sharedDirector] replaceScene:gameOverScene];
}
}

if (targetsToDelete.count > 0) {
[projectilesToDelete addObject:projectile];
}
[targetsToDelete release];
}

for (CCSprite *projectile in projectilesToDelete) {
[_projectiles removeObject:projectile];
[self removeChild:projectile cleanup:YES];
}
[projectilesToDelete release];

}

```

# Answer
You should try an animation using a sprite sheet. Just have each frame of the animation be a different color. Ray Wenderlich, where you got your (base) code from, has a tutorial on it here.

This is a bit more complicated than just changing the color of a sprite (as suggested in Jamornh's answer), but I see it as a good segue into incorporating animations into your games.
> 1 votes

# Answer
Assuming that all your bubbles are the same shape and size where the only difference is just their color, you can instead use a white bubble and change the Sprite's color like this:

target.color = ccc3(0, 0, 0);

Where the 0 values should be replaced by RGB values respectively.

Then you can just generate a different color bubble each time, so you can just keep calling addTarget: until you have enough bubbles.
> 1 votes

---
Tags: cocos2d-iphone
---


# Question
Title: How can I show a texture in a separate window in an XNA game?
I'm playing around with random map generation and what I want to do is:

1. Input a command to generate a random map.
2. A texture will be created resembling the generation, each pixel resembling each tile.
3. A new window will pop-up, without removing the original one, that will contain the texture.

I know how to do this except for the last part. Would someone please tell me how to create a new window and draw a texture to this window?

# Answer
Unfortunately there isn't anything in the XNA framework which could help you, but there are two other solutions:

The second solution is simpler because you can use it in this way:

```
System.Windows.Forms.Form form = new System.Windows.Forms.Form();
form.Show();

```

Then if you want to show the texture in the new form you should create a bitmap, and you can do it in this way (you have to add a reference to `System.Drawing` and `System.IO`):

```
System.IO.MemoryStream ms = new System.IO.MemoryStream();
Texture2D texture = Content.Load<Texture2D>( "Images\\test" ); //example
texture.SaveAsJpeg( ms, texture.Width, texture.Height );
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap( ms );

```

The complete code could be:

```
protected override void Update(GameTime gameTime){
    //...

    ShowForm(CreateBitmap(texture));
    base.Update(gameTime);
}

private Bitmap CreateBitmap(Texture2D texture){
    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    texture.SaveAsJpeg( ms, texture.Width, texture.Height );
    return new System.Drawing.Bitmap( ms );
}

private void ShowForm(Bitmap bmp){
    System.Windows.Forms.Form form = new System.Windows.Forms.Form();
    form.Location = new System.Drawing.Point(100, 100); //example
    form.Text = "Texture2D";
    form.BackgroundImage = bmp; //Set the texture as background
    form.ClientSize = bmp.Size;
    form.Show();
}

```
> 4 votes

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


title: Game Clock Precision

text:
# Question
Title: Game Clock Precision
I'm reading a fantastic article about game timer precision and here is a quote about 2/3 of the way into the article:

> If you start your game clock at about 4 billion (more precisely 2^32, or any large power of two) then your exponent, and hence your precision, will remain constant for the next ~4 billion seconds, or ~136 years.

He doesn't give a concrete example of this though. Does this mean I would want to add 2^32 to the game clock value that I store at the beginning of each frame? Or is there a way to actually set the clock in Windows so that the numbers start at 2^32?

# Answer
> 11 votes
**TL;DR The author is not suggesting you implement this in your game. He's telling you that the precision will be slow changing, but bad.**

This means the `float` you're using to track your game time would start at 2^32. Because setting the number that large to start with, whatever you add on to it in the next 136 years, won't change the exponent.

Though, the precision will remain constant, it doesn't mean it's better. The precision gets worse the larger the number. Starting with a large number just means that the precision won't change over the life of the counter, but the precision is worse than starting with a small number. If you started at `0` the exponent would change frequently at first, meaning the precision changes frequently.

Concrete example:

```
float twoToThirtyTwo = 4294967296;
float game_time_elapsed = twoToThirtyTwo;

float getTimeElapsed() {
     return game_time_elapsed - twoToThirtyTwo;
 }

```

I believe overall the article is suggesting using floats for time deltas (short/small time spans) and using `int`s or `long`s for time elapsed (long/large time spans).

---

The author suggests a change to the code above to make it usable, since it's currently an example of how you can have constant *bad* precision. Change to a double:

```
double twoToThirtyTwo = 4294967296;
double game_time_elapsed = twoToThirtyTwo;

double getTimeElapsed() {
     return game_time_elapsed - twoToThirtyTwo;
 }

```

That code should give a constant *good* precision (around 1 microsecond) for a long time.

# Answer
> 8 votes
Most games have a function that calculates the current time -- perhaps using `QueryPerformanceCounter()`, perhaps using `GetTickCount64()`, perhaps using something else. Normally this function is designed so that it initially returns zero, and then gradually returns larger numbers.

What the author is saying (and I can be definitive about this because I am the author) is:

* The first value returned should be 2^32 instead of zero and it should smoothly increment from there.
* The return value should be a double, not a float.
* Comments on the article itself instead of here would be better.

# Answer
> 2 votes
Here's another discussion on game timer implementation and accuracy, complete with source code, that may help you with your game timer requirements.

Cygnon's Blog: Game Programming Adventures

# Answer
> 1 votes
From Tom Forsythe's article (which is linked from Bruce's article, but not really discussed:

> One "solution" **\[to floating point precision problems\]** is to turn on double precision, because then you get more bits. Yeah, but you've just shuffled the problem around. Doubles have exactly the same weaknesses **\[as floats\]** \- all you've done is shuffle the problems into a corner, stuck your fingers in your ears and yelled "lalalalalala". They'll still come back to bite you, and because it's double precision, it'll be even rarer and even harder to track down. And they're slower on most machines, so you've hurt your execution speed.

*(my clarifications in bold)*

Precision problems make floats and doubles just a fundamentally bad choice for representing absolute time. This is why Windows doesn't use them to represent absolute time. This is why OS X doesn't use them to represent absolute time. This is why Linux, BSD, Solaris, and every other OS under the sun doesn't use them to represent absolute time.

If you're storing the absolute game time, you really are better off using fixed point integers. Reliable, repeatable, and with consistent precision across their whole range. "Because I like seconds" is a pretty feeble reason to move to imprecise and error-prone storage for something as critical to a game as its internal clock, if you ask me.

---
Tags: c++, events, timer
---


title: Camera closes in on the fixed point

text:
# Question
Title: Camera closes in on the fixed point
I've been trying to create a camera that is controlled by the mouse and rotates around a fixed point (read (0, 0, 0)), both vertical and horizontal. This is what I've come up with:

```
camera.Eye = Vector3.Transform(camera.Eye, Matrix.CreateRotationY(camRotYFloat));

Vector3 customAxis = new Vector3(-camera.Eye.Z, 0, camera.Eye.X);
camera.Eye = Vector3.Transform(camera.Eye, Matrix.CreateFromAxisAngle(customAxis, camRotXFloat * 0.0001f));

```

This works quite well, except for the fact that when I 'use' the second transformation (go up and down with the mouse) the camera not only goes up and down, it also closes in on the point. It zooms in.

How do I prevent this?

Thanks in advance.

# Answer
I don't see any thing in this snippet that will cause a zooming affect. I do, however, see a problem in the pitch rotation. `customAxis` needs to be normalized before using it as an argument in `CreateFromAxisAngle` method or the rotation amount will be incorrect. This may appear masked at the moment by your *.0001* scaling but it would be worth normalizing it to see if it is somehow playing a part in your errant zoom affect.
> 1 votes

---
Tags: xna, c#, camera, matrix
---


# Question
Title: Semi Fixed-timestep ported to javascript
In Gaffer's "Fix Your Timestep!" article, the author explains how to free your physics' loop from the paint one.

Here is the final code, written in C:

```
double t = 0.0;
const double dt = 0.01;

double currentTime = hires_time_in_seconds();
double accumulator = 0.0;

State previous;
State current;

while ( !quit )
{
     double newTime = time();
     double frameTime = newTime - currentTime;
     if ( frameTime > 0.25 )
          frameTime = 0.25;   // note: max frame time to avoid spiral of death
     currentTime = newTime;

     accumulator += frameTime;

     while ( accumulator >= dt )
     {
          previousState = currentState;
          integrate( currentState, t, dt );
          t += dt;
          accumulator -= dt;
     }

     const double alpha = accumulator / dt;

     State state = currentState*alpha + previousState * ( 1.0 - alpha );

     render( state );
}

```

I'm trying to **implement this in JavaScript** but I'm quite confused about the second `while` loop...

Here is what I have for now (simplified):

```
...
(function animLoop(){
  ...

  while (accumulator >= dt) { // While? In a requestAnimation loop? Maybe if?
    ...
  }

  ...
  // render

  requestAnimationFrame(animLoop); // stand for the 1st while loop [OK]
}())

```

As you can see, I'm not sure about the `while` loop inside the requestAnimation one...

I thought replacing it with a `if` but I'm not sure it will be equivalent...

Maybe some can help me.

# Answer
I'm not entirely sure that you understand what the article means by a **fixed** timestep.

`requestAnimationFrame` is defined as:

> Tells the browser that you wish to perform an animation; this **requests that the browser schedule a repaint of the window for the next animation frame**.

The amount of time that passes between each invocation of the function varies based on computer specification, CPU load, etc. `rAF` simply does not guarantee consistency. As an example, consider this list of `delta`s (i.e. duration between invocations)\[1\]:

```
0.016 0.016 0.016 0.2 0.016 0.026 0.016 1.2

```

Obviously, this is not exactly going to fly as far as physics go, so what the article is trying to do is to make sure that your games updates are as regular as possible.

This means that when you get a `delta` that is 1/30 of a second (as opposed to 1/60), you need to invoke your games logic **twice** in that loop to ensure that the game's internal state is somewhat close to the viewer's expectation. It might sound scary to update the game's internal state multiple times per frame, but it may be necessary, depending on the circumstance.

Let's say you have a typical RPG hero on a tiled map, moving at a velocity of 1 tile per second east. This would mean that for each frame, he should move approximately **1/60th** of a tile east. But say that a popup comes up, slowing the computer, and your next frame takes **1.2** seconds to come to the screen. The hero should have moved **1.2 tiles** east in this time, but if you were to just `hero.positionX += 1/60`, he would have still only moved 1/60th of a tile.

To fix this, you'd need to fix your timestep, and integrate his position: `hero.positionX += hero.velocityX * delta`.

Here's an example of how you might accomplish this:

```
var lastCall = Date.now();
var accum = 0;
var dt = 1 / 60;
function mainLoop() {
    // Figure out how long it's been since the last invocation
    var delta = Date.now() - lastCall;

    //Cache the current timestep so we can figure out the next delta
    lastCall = Date.now();

    // Add the delta to the "accumulator"
    accum += delta;

    // As long as the accumulated time passed is greater than your "timestep"
    while (accum >= dt) {
        // Update the game's internal state (i.e. physics, logic, etc)
        game.update();

        // Subtract one "timestep" from the accumulator
        accum -= dt;
    }

    // Finally, render the current state to the screen
    game.render();
}
window.requestAnimationFrame(mainLoop);

```

\[1\] As a side note, last I'd heard, Chrome capped its FPS at 60, so you won't get better than that.
> 6 votes

# Answer
You only use the semi-fixed time step code once in your code. You'll use it in a main update loop. If you're processing an animation, you'd pass in your current time to set the animation to the appropriate frame. The time you pass in comes from the main update loop. The reason you're having a hard time figuring out where/how to use a `while` loop is because you wouldn't use one outside the main loop. If you were to recreate this time-step inside your animation function, you could only play one animation at a time, and everything would have to wait for that animation to finish.
> 1 votes

# Answer
`requestAnimationFrame` is here for *animating*, definitely not doing physics. So you should remove that part, and only put your rendering code in there. You also have a syntax error, I believe:

```
(function bla()
{

})();

```

And I don't see a need for a self executing function at all. Just create a normal one.
> 0 votes

---
Tags: javascript, box2d, c, physics-engine, fixed-timestep
---


# Question
Title: How to handle loading and keeping many bitmaps in an Android 2D game
In an Android 2D game which is using SurfaceView where its onDraw is driven by a loop from a Thread, I use many bitmap sprites (sprite sheets) and two background size bitmaps, which are all loaded into memory at the start.

It all works fine, however, when the activity is onPause or after reloading it few times, Android shows a tendency to wipe out the big bitmaps only, probably to free memory. Sometimes this happens even in the middle of loading this very activity.

In order to counter this, I made a check in the onDraw method to test if the big bitmaps are still there and reload them if they are forcefully recycled by Android, before drawing them on Canvas.

This solution may not be the most stable, and since I know that there are much more accomplished android game programmers here than myself, I hope you can reveal some tricks or secrets or at least provide some good hints, how to overcome this.

# Answer
> 0 votes
The way to do it:

* never create any new bitmaps unless you don't really have to, check every bit of the code
* set the Activity on RGB\_565, and especially the SurfaceView

> getHolder().setFormat(0x00000004); //RGB\_565

* load bitmpas with

> options.inPreferredConfig = Bitmap.Config.RGB\_565;

RGB\_565 is good enough for images with many details and SurfaceView runs almost twice faster in frame rates

* use ARGB\_4444 for small images in drop down lists etc, or anything that does not require very good quality

Have not had any out of memory errors in the same game after implementing this.

# Answer
> 3 votes
The Android OS is only allowed to free up your memory while your application is halted with onPause(). You should be able to check for and load the assets during onResume() and then feel safe knowing they will be there until you get another onPause() callback.

Further reading:

---
Tags: android
---


title: Android in-game pause screen

text:
# Question
Title: Android in-game pause screen
Right now Im calling a new activity with an xml-view when I pause my game, but Since I do this I need to use `context` in my real-time code, and this is causing a memory leak. Is there any preffered way to pause the game? By pause I mean if game is over, if I die, or if I press pause-button. Would a custom dialog work just aswell? this would mean I wont have to leave my main-activity while im in-game.

# Answer
> 1 votes
You can use **startActivityForResult**, that works fine and it does not need passing the context. But in my games I've created a game object which looks like and behaves like a dialog and simply activate it on pause or game over, thus never create other activity or Android dialog.

EDIT An example using Options, which some say is safer in order to avoid out of memory errors:

```
private Bitmap loadBitmap(int resourceID){
            Options options = new BitmapFactory.Options();
            options.inScaled = false;
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            Bitmap tempBmp = null;
            try{
                tempBmp = BitmapFactory.decodeStream(new BufferedInputStream(getResources().openRawResource(resourceID)), null, options);
            }catch(OutOfMemoryError e){

            }catch (Error e){

            }
            return tempBmp;
}

```

---
Tags: android
---


# Question
Title: Logic / Render phases with a single thread
The question I have may generate different opinions from different developers, but I'd still like to have an answer on this.

Its all about the updating and rendering steps of the game loop, and their use under multi and single threaded environments.

Currently, there is one thread running, which takes care of sequentially executing events , logic and rendering. Sometimes, the logic part may wish to change the game state to something else, and in between do some loading of files.

The result is that the game hangs completely while loading, and then proceeds to normal rendering of the new state. To go around this, i could make another thread, do the loading there while the main thread renders a smooth loading animation, and then proceed normally.

The real question is about if i don't create another thread. I could refresh the screen from the logic thread, and provide some basic loading screen, which could be not so smoothly updated while the files load.

In fact, this approach is not loved by a lot of developers, as it scrambles render code in the logic step, which may cause problems of different sorts..

Hope its clear!

# Answer
There is nothing directly wrong with keeping rendering in your logic thread, especially for simpler games that aren't in need of extreme performance. Indeed, even if you keep rendering, if logic is blocked on file I/O then the game is still going to look and feel like it is hung up.

The correct solution to your problem is to use event driven programming for your logic and file I/O. If logic needs a resource, it should start loading it in the background (using either a thread or asynchronous I/O APIs), and expect that the rest if the game and logic keeps running until that request is complete. If the game must stop and wait because the resource is critical, logic can at least handle a friendly loading screen ( or better, some kind of interactive amusement) while it waits.

Short version: just don't make API calls that block and stall the application, unless those calls themselves are on another thread.
> 1 votes

# Answer
You should not put render code into your update method.

If you can break your code into parts where you would call Render(), you can also easily just exit for this frame and let the render function do its job.

I'm assuming all resources that you want to load share a common interface that defines methods like `Load()` and `IsLoaded()` (and a few more for unloading). Given a list of these resources to load you have the option to simply load one and be done, like

```
bool everythingLoaded = true;
foreach(ILoadableResource resource in resourcesToLoad){
  if(resource.IsLoaded()) continue;
  resource.Load();
  everythingLoaded = false;
  break;
}

if(everythingLoaded){ ... }

```

That will render a frame after every resource loaded. As long as you can guarantee that not one resource will take longer than ~33ms - render time(=30fps) you will have a smooth animation. Alternatively you can load as many as possible while keeping track of a high precision timer until you reach ~33ms (render time should be close to non existent and since the scene will be most likely static you could go even further up)

If you are loading huge resources that take long to load but absolutely must maintain a smooth animation you need to chunk your loading process further, or use another thread. For loading chunks you could consider giving the interface a `GetChildren()` function and load everything recursively before you load the parent resource. To actually get chunks of data to load you would need to prepare your data that way, like splitting a huge texture into smaller parts and have the parent resource assemble that together. Although I guess at this point a threaded solution should be much simpler.
> 0 votes

---
Tags: architecture, rendering, loading, logic
---


title: What is "top new free" on GooglePlay

text:
# Question
Title: What is "top new free" on GooglePlay
On Android Market i.e. GooglePlay, there used to be a page with the latest new games. So every game had a chance to get noticed and make its way up especially if it was good.

But now I see "top new free" page and no more the latest apps. I don't understand how can be "top new" Anybody knows how this works?

If there are no more pages with the very latest uploaded games then the new apps will be barely seen to exist even if they are excellent, and new programmers have very little chance of getting noticed. Any good advice how to promote a new Android app these days?

# Answer
From their help page:

> Top New Free: popular free apps less than 30 days old

The second part of your question is off topic. See this question for an answer.

---

If you wanted to know how a new app can become popular if there's no longer just a "new" list, the answer is simple. **The app developer cannot rely solely on the app store for getting recognized.** Have friends, family and fans rate your app when it is released. Announce the release of your game on your blog, Twitter and Facebook. Embrace social media to get the word about your game out there. Do that within 30 days of the games release and you have a chance of making it onto the "Top New Free" apps list.
> 3 votes

# Answer
Apps become popular when people rate them well. When apps are rated well within the first 30 days, they show up on the Top New Free list. Simple as that.
> 2 votes

---
Tags: android
---


# Question
Title: Collision Detection with SAT: False Collision for Diagonal Movement Towards Vertical Tile-Walls?
I'm developing my first tile-based 2D-game with Javascript. To learn the basics, I decided to write my own "game engine". I have successfully implemented collision detection using the separating axis theorem, but I've run into a problem that I can't quite wrap my head around.

If I press the \[up\] and \[left\] arrow-keys simultaneously, my character moves diagonally towards the upper left. If he hits a horizontal wall, he'll just keep moving in x-direction.

The same goes for \[up\] and \[left\] as well as downward-diagonal movements, it works as intended:

*Diagonal movement works fine for horizontal walls, for both left and right-movement*

**However: this does not work for vertical walls**.

Instead of keeping movement in y-direction, he'll just stop as soon as he "enters" a new tile on the y-axis.

So for some reason SAT thinks my character is colliding vertically with tiles from vertical walls:

*My character stops because he thinks that he is colliding vertically with tiles from the wall on the right.*

This only occurs, when:

* Moving into top-right direction towards the right wall
* Moving into top-left direction towards the left wall

Bottom-right and bottom-left movement work: the character keeps moving in y-direction as intended.

Is this inherited from the way SAT works or is there a problem with my implementation? What can I do to solve my problem?

Oh yeah, my character is displayed as a circle but he's actually a rectangular polygon for the collision detection.

Thank you very much for your help.

# Answer
> 2 votes
Big thanks to Jonathan who pointed me in the right direction. Sean describes the method I used in a different thread. Also big thanks to him! :)

Here is how I solved my problem:

If a collision is registered by my SAT-method, only fire the collision-event on my character if there are no neighbouring solid tiles in the direction of the returned minimum translation vector.

---
Tags: 2d, collision-detection, movement, separating-axis-theorem
---


title: collideWith Call Back Method

text:
# Question
Title: collideWith Call Back Method
In my class, I extend Sprite class. I override one of the method collideWith(). But my problem was that when current sprite collide with other sprite it does not call the call back method collideWith(). Here is my implementation.

```
@Override
public boolean collidesWith(IShape pOtherShape) {
    System.out.println("collide with called");
    return true;
}

```

Any member please help me.

# Answer
> 1 votes
This is not a callback, you have to call the method yourself to find out whether the Sprites collide. By overriding it you broke its functionality. What you want to do (I think) is override the onUpdate method of the Sprite and put there an if statement calling the `collidesWith(otherSprite)` method.

# Answer
> 1 votes
Just to clarify a bit.

First read about about callbacks.

If you have to call it yourself, it's probably not a callback.

In java, you can override a method (maybe you should read about OO concepts) like you did:

```
@Override
public void foo() {
}

```

The method *foo* is override in a custom class that probably extends another class (or implements an interface but in this case you **have to** override all the methods of the interface since they are **abstract**. Read more about interfaces here.) that contains a *foo* method itself.

```
class ParentClass {

    public void foo() {
        //do something
    }

```

Since overriding a method mean "redefining" his behavior, if you call the *foo* method from your custom class extending *ParentClass* it will (in this case) not do anything. If you want to reach a method from a parent class, use *super*.

```
@Override
public void foo() {
    super.foo(); //will call the foo method of the parent class
    //add custom code here
}

```

Also you should read this great tutorial covering inherence in Java: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

---
Tags: andengine
---


# Question
Title: How to use proximity sensor in android with unity3d?
I want to create a android game with unity3d using proximity sensor an I don't know how to access that sensor with java script

# Answer
> 1 votes
There is the GyroDroid (at the time of writing, costs 35$), which enables access to "every single sensor of your Android".

However, I guess you can try to find how to access Android's sensors using mono, if that is the target platform for Unity's Android games, and apply that to your Unity project.

---
Tags: android, unity, platformer
---


title: Change collision action

text:
# Question
Title: Change collision action
I have a collision detection and its working fine, the problem is, that whenever my "`bird`" is hitting a "`cloud`", the cloud dissapers and i get some points. The same happens for the "`sol`" which it should, but not with the clouds.

How can this be changed ? ive tryed a lot, but can seem to figger it out.

**Collision Code**

```
- (void)update:(ccTime)dt {
    bird.position = ccpAdd(bird.position, skyVelocity);

    NSMutableArray *projectilesToDelete = [[NSMutableArray alloc] init];
    for (CCSprite *bird in _projectiles) {
        bird.anchorPoint = ccp(0, 0);
        CGRect absoluteBox = CGRectMake(bird.position.x, bird.position.y, [bird boundingBox].size.width, [bird boundingBox].size.height);

        NSMutableArray *targetsToDelete = [[NSMutableArray alloc] init];
        for (CCSprite *cloudSprite in _targets) {
            cloudSprite.anchorPoint = ccp(0, 0);
            CGRect absoluteBox = CGRectMake(cloudSprite.position.x, cloudSprite.position.y, [cloudSprite boundingBox].size.width, [cloudSprite boundingBox].size.height);

            if (CGRectIntersectsRect([bird boundingBox], [cloudSprite boundingBox])) {
                [targetsToDelete addObject:cloudSprite];

            }
        }

        for (CCSprite *solSprite in _targets) {
            solSprite.anchorPoint = ccp(0, 0);
            CGRect absoluteBox = CGRectMake(solSprite.position.x, solSprite.position.y, [solSprite boundingBox].size.width, [solSprite boundingBox].size.height);

            if (CGRectIntersectsRect([bird boundingBox], [solSprite boundingBox])) {
                [targetsToDelete addObject:solSprite];
                score += 50/2;
                [scoreLabel setString:[NSString stringWithFormat:@"%d", score]];
            }
        }

        // NÅR SKYEN BLIVER RAMT AF FUGLEN
        for (CCSprite *cloudSprite in targetsToDelete) {
            //[_targets removeObject:cloudSprite];
            //[self removeChild:cloudSprite cleanup:YES];
        }

        // NÅR SOLEN BLIVER RAMT AF FUGLEN
        for (CCSprite *solSprite in targetsToDelete) {
            [_targets removeObject:solSprite];
            [self removeChild:solSprite cleanup:YES];

        }

        if (targetsToDelete.count > 0) {
            [projectilesToDelete addObject:bird];
        }
        [targetsToDelete release];
    }

    // NÅR FUGLEN BLIVER RAMT AF ALT ANDET
    for (CCSprite *bird in projectilesToDelete) {
        //[_projectiles removeObject:bird];
        //[self removeChild:bird cleanup:YES];
    }
    [projectilesToDelete release];

}

```

# Answer
You keep your objects in the same list (\_targets). Therefore the game can not decide if you are talking about a cloud or about a sol, both are just CCSprites for the game. Therefore it loops through every element, handling it as a cloud and then does the same thing again, handling the objects a sol.

To prevent this save the objects into 2 differnt lists: Clouds into \_cloudTargets and the sol into \_solTargets and change the two loops to:

```
for (CCSprite *cloudSprite in _cloudTargets) {
      [..]

        if (CGRectIntersectsRect([bird boundingBox], [cloudSprite boundingBox])) {
            [targetsToDelete addObject:cloudSprite];

        }
    }

    for (CCSprite *solSprite in _solTargets) {
       [..]

        if (CGRectIntersectsRect([bird boundingBox], [solSprite boundingBox])) {
            [targetsToDelete addObject:solSprite];
            score += 50/2;
            [scoreLabel setString:[NSString stringWithFormat:@"%d", score]];
        }
    }

```

This should work fine.

Hope this helps

floAr
> 0 votes

---
Tags: collision-detection, cocos2d-iphone
---


# Question
Title: How do I implement a selectable world map?
I want to have a selectable map of the world, preferably zoomable, in a cocos2d project. When I tap on a country, I want that country to be selected so that I can perform some other operations with it. It seems that the best approach would be to use a vector world map, but I'm unsure how to implement this with cocos2d. Other options include using map tiles, but it seems that still would require the implementation of country polygons for tap/click detection.

Depending on user input, I want to add icons to various countries on the map.

What is a good way to approach the implementation of this type of map?

# Answer
I would likely create CGRects using node/world coordinates, I can never remember which is which until I do it, of where the picture of this place would be. That way instead of creating separate sprite entities for every city you could just create one map with everything on it. Then when you tap the country, you're really just getting the detection against the CGRect in the same position.

I also might instead make a circle or something to place under the countries and create the circle as CCMenus. Alternatively, you could create them as sprites as well that sit under the map.

As far as the zooming in and out and using a vector map I'm not sure. Depending on how much zoom you wanted I don't know if it would be necessary but I'm also not sure what you're doing.

Hopefully there is a better answer than mine because I'm sort of curious as to how someone else would do this.
> 1 votes

---
Tags: cocos2d-iphone, maps, vector, macos
---


# Question
Title: 2D Grid based game - how should I draw grid lines?
I'm playing around with a 2D grid based game idea, and I am using sprites for the grid cells. Let's say there is a 10 x 10 grid and each cell is 48x48, which will have sprites drawn there. That is fine.

But in design mode, I'd like to have a grid overlay the screen. I can do this either with sprites (2x600 pixel image etc) or with primitives, but which is best? Should I really be switching between sprites and 3d/2d rendering?

Like so:

Thanks!

# Answer
> 8 votes
Figured out an easy way to do it. Should have been obvious to me to begin with.

First I create a 1px texture:

```
texture1px = new Texture2D(graphics.GraphicsDevice, 1, 1);
texture1px.SetData(new Color[] { Color.White });

```

Then I just draw stretched sprites as lines, rather than creating long sprite pngs:

```
for (float x = -cols; x < cols; x++)
{
    Rectangle rectangle = new Rectangle((int)(centerX + x * gridSize), 0, 1, height);
    spriteBatch.Draw(texture1px, rectangle, Color.Red);
}
for (float y = -rows; y < rows; y++)
{
    Rectangle rectangle = new Rectangle(0, (int)(centerY + y * gridSize), width, 1);
    spriteBatch.Draw(texture1px, rectangle, Color.Red);
}

```

And I get:

Hope this helps someone, some day!

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


# Question
Title: How to deal with OpenGL and Fullscreen on OS X
I do most of my development on OS X and for my current game project this is my target environment. However when I play games I play on Windows. As a windows gamer I am used to Alt+Tab switching from within the game to the last application that was open.

On OS X I currently can't find either a game that supports that nor can I find a way to make it possible. My current project is based on SDL 1.3 and I can see that cmd+tab is a sequence that is sent directly to my application and not intercepted by the operating system.

Now my first attempt was to hide the rendering window on cmd+tab which certainly works, but has the disadvantage that a hidden OpenGL window in SDL cannot be restored when the user tabs back to the application. First of all, there is no event fired for that or I can't find it, secondly the core problem is that when that application window is hidden, my game is still the active application, just that the window disappeared.

That is incredible annoying.

Any ideas how to approximate the windows / linux behavior for alt+tab?

# Answer
> 2 votes
The issue is that you are capturing the display, as described in the Apple documentation here: https://developer.apple.com/library/mac/#documentation/graphicsimaging/Conceptual/QuartzDisplayServicesConceptual/Articles/DisplayCapture.html

This means that ALL keyboard commands are intercepted by your application. There are advantages to this approach, depending on your application.

The Apple docs say, at the bottom:

> Note: It’s not necessary to capture a display to do full-screen drawing. Another approach is to create and draw into a borderless window the size of the display. This approach allows you to use all the features of the windowing system. It also plays well with the rest of the operating system, and it reduces the complexity of display handling (for example, you don’t have to worry about mirrored displays). With this approach, you can receive error alerts that might be missed with a captured display. You can also use Command-Tab to change applications with this approach. On systems with modern graphics hardware, drawing performance in a full-screen window is almost as fast as a full-screen drawing context.

What you need to do is make your openGL view full screen without capturing the display. This is how cocos2d currently handles full screen OS X applications. You can browse the code for cocos2d Mac here: https://github.com/cocos2d/cocos2d-iphone/tree/master-v2/cocos2d/Platforms/Mac

Look specifically in CCDirectorMac.m and CCGLView.m for their implementation.

If you determine that you want to selectively limit some of the functions, such as process switching, without limiting all of the features of the windowing system, you can look to the Apple Kiosk Mode Technical Note: http://developer.apple.com/library/mac/#technotes/KioskMode/Introduction/Introduction.html

# Answer
> 1 votes
My experience of this on the Mac is that there's normally a shortcut to exit fullscreen mode into windowed mode (typically CMD+M or CMD+Return). Once you've switched into windowed mode then you can access all your applications as normal. Windowed mode also nicely allows the user to monitor their game amongst all their other apps. So I guess you could just implement this sort of functionality to your game.

---
Tags: opengl, sdl, macos
---


# Question
Title: How to make a Sprite using CoreGraphics iOS - Cocos2d-iPhone
I'm trying to make a sprite that uses the graphics that are made with core graphics. I cant seem to find anything to explain how to make shapes using core graphics to create a sprite to use in cocos2d-iPhone.

Thanks for any insights and help!

# Answer
i don't know cocos2d, so i just can just give you some tricks about CoreGraphics on iOS.

First, the simple case, if you can create sprite from a UIImage or a CGImageRef.

```
/* function that draw your shape in a CGContextRef */
 void DrawShape(CGContextRef ctx)
 {
     // draw a simple triangle

     CGContextMoveToPoint(ctx, 50, 100);
     CGContextAddLineToPoint(ctx, 100, 0);
     CGContextAddLineToPoint(ctx, 0, 0);
     CGContextClosePath(ctx);
  }

    void CreateImage(void)
    {
       UIGraphicsBeginImageContext(CGSizeMake(100, 100));

       DrawShape(UIGraphicsGetCurrentContext());

       UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

       UIGraphicsEndImageContext();

       // now you've got an (autorelease) UIImage, that you can use to
       // create your sprite.
       // use image.CGImage if you need a CGImageRef
    }

```

If you need to provide a buffer of data, and create your own CGContextRef :

```
CGContextRef CreateBitmapContextWithData(int width, int height, void *buffer)
{
    CGContextRef ctx;
    CGColorSpaceRef colorspace;
    size_t bytesPerRow;
    size_t bitsPerComponent;
    size_t numberOfComponents;
    CGImageAlphaInfo alpha;

    bitsPerComponent = 8;
    alpha = kCGImageAlphaPremultipliedLast;

    numberOfComponents = 1;
    colorspace = CGColorSpaceCreateDeviceRGB();

    numberOfComponents += CGColorSpaceGetNumberOfComponents(colorspace);
    bytesPerRow = (width * numberOfComponents);

    ctx = CGBitmapContextCreate(buffer, width, height, bitsPerComponent, bytesPerRow, colorspace, alpha);

    CGColorSpaceRelease(colorspace);

    return ctx;
}

void CreateImageOrGLTexture(void)
{
   // use pow2 width and height to create your own glTexture ...
   void *buffer = calloc(1, 128 * 128 * 4);
   CGContextRef ctx = CreateBitmapContextWithData(128, 128, buffer);

   // draw you shape
   DrawShape(ctx);

   // you can create a CGImageRef with this context
   // CGImageRef image = CGBitmapContextCreateImage(ctx);

   // you can create a gl texture with the current buffer
   // glBindTexture(...)
   // glTexParameteri(...)
   // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

   CGContextRelease(ctx);
   free(buffer);
}

```

See Apple documentation for all CGContext functions : https://developer.apple.com/library/mac/#documentation/graphicsimaging/reference/CGContext/Reference/reference.html

Hope this help.
> 0 votes

---
Tags: graphics, cocos2d-iphone, sprites, ios
---


# Question
Title: Creating an interactive grid for a puzzle game
I am trying to make a slitherlink game, and am not too sure how to approach creating the game, more specifically the grid structure on which the puzzle will be played on.

This is what a empty and completed slitherlink grid would look like:

The numbers in the squares are sort of clues and the areas between the dots need to be clickable:

I would like to create the game in VB .NET. What data structures should I try to use, and would it be beneficial using any frameworks such as XNA?

# Answer
> 1 votes
Hey Noupoi and welcome to gamedev.stackexchange! Starting with your first question:

As your game board will be a nice rectangular thingy you can use an array. http://msdn.microsoft.com/en-us/library/wak0wfyt.aspx

To represend the game board you may want to create your own data structure which contains the folowing informations:

* The number of the field
* Information about the walls

As an alternative you can use an int array for the numbers and another array for the walls and binary code the walls.

As for XNA it will help you with some higher MAth (which I assume you dont need) and with the rendering part. It is basicly a framework which helps you at working with directX, so if you want to extend your game in this direction (maybe use 2D graphics instead of plain numbers) it may get very handy. For me the structure used by XNA also feels very confortable so I use it even in some non directly gaming related project. But this is of course a personal opinion.

I hope this helps a bit!

Regards

floAr

---
Tags: .net, grid, puzzle
---


# Question
Title: How can I correctly manage different utility classes between engine and libraries?
I'm currently building an engine over SFML and Box2D.

The problem is that each of these use different types for things like Vector2, etc.

So to the question: is it a good idea to replace Box2D and SFML vectors with my own vector class (which is one of my better implementations)? My idea then was to have a separate .lib with all my classes that should be shared between all the projects in the solution.

# Answer
That's a very good question, mismatches in utility classes (vectors, matrices or even containers) between libraries is often an overlooked issue.

I wouldn't try to modify SFML or Box2D:

* Your own utilities classes might be missing a few features that those libraries rely on;
* If you need to update your libs to integrate some new features or bugfixes, you'll have do re-do all that work again.

What you should do is wrap those libraries in classes of your own, so that other parts of your engine can manipulate them without "polluting" everything with external dependencies. E.g. if you need to use a function that requires a `Box2D::Vector2`, don't rewrite it, instead wrap it in a function that requires a `hayer::Vector2`:

```
// this is declared by Box2D
void Box2D::DoStuffWithVector2( Box2D::Vector2 foo )

// this is a wrapper function for your engine
void hayer::DoStuffWithVector2( hayer::Vector2 foo )
{
    Box2D::DoStuffWithVector2( hayer::ConvertToBox2D( foo ) );
}

```

You don't have to wrap everything though, just wrap what you need when you need it, iteratively. You won't need everything in the library interface, so that's the best way to limit the code size. I'd say that creating this kind of "glue code" is roughly the same amount of work than rewriting the libs, but it brings much more benefits:

* Changing libs (e.g. from Box2D to another physics lib) will be easier, as you'll just have to modify this "glue code";
* You'll be able to integrate new features or bugfixes from your external libs almost instantaneously.

Doing a separate .lib for your utility classes is a good idea, it'll keep a good modularity and can't do any harm. And it'll fit in that model as well.
> 4 votes

---
Tags: architecture, data-structure
---


# Question
Title: Strange behavior of RigidBody with gravity and impulse applied
I'm doing some experiments trying to figure out how physics works in Unity.

I created a cube mesh with a `BoxCollider` and a `RigidBody`. The cuve is laying on a mesh plane with a `BoxCollider`.

I'm trying to update the object position applying a force on its `RigidBody`. Inside script `FixedUpdate` function I'm doing the following:

```
public void FixedUpdate()
{
    if (leftButtonPressed())
        this.rigidbody.AddForce( this.transform.forward * this.forceStrength, ForceMode.Impulse);
}

```

Despite the object is aligned with the world axis and the force is applied along Z axis, it performs a quite big rotation movement around its y axis. Since I didn't modify the center of mass and the BoxCollider position and dimension, all values should be fine.

Removing gravity and letting the object flying without touching the plane, the problem doesn't show. So I suppose it's related to the friction between objects, but I can't understand exactly which is the problem.

Why this? What's my mistake? How can I fix this, or what's the right way to do such a moving an object on a plane through a force impulse?

# Answer
I tried to replicate your example and you're right:

**I had to set the plane's material to Ice to see the cube moving as it should**. Without a material set to the plane, the cube won't "slide" forward (will do a simple somersault) for values like 25, and for bigger values (like 250) the cube's behaviour is really weird!!! (it moves forward, that moves backwards, then starts flying in the upper direction!!! Really funny; here is a link to a video).

To have access to the Ice material you have to import the Physic Materials package.

To set the plane's material you have to select the plane and go to Mesh Collider -\> Material.
> 1 votes

---
Tags: physics, unity, rigid-body-dynamics
---