title: Using elapsed time for SlowMo in XNA

text:
# Question
Title: Using elapsed time for SlowMo in XNA
**UPDATE 2:** I've tried to pass in GameTime to my Update method, just as I did for the bats, but I'm not seeing any change to the ball's speed. I've also changed my moveSpeed to:

\*moveSpeed += (15f * elapsedTime);\*

where previously it was simply *moveSpeed += 15f;* and it still hasn't yielded any results. What could I be doing wrong?

```
Class Ball
{

   public void UpdatePosition(GameTime gameTime)
    {
        elapsedTime = 50.0f * (float)gameTime.ElapsedGameTime.TotalSeconds;

        size.X = (int)position.X;
        size.Y = (int)position.Y;
        oldPos.X = position.X;
        oldPos.Y = position.Y;
        position.X += speed * ((float)Math.Cos(direction));
        position.Y += speed * ((float)Math.Sin(direction));
        bool collided = CheckWallHit();
        particleEngine.Update();

        previous = current;
        current = Keyboard.GetState();
        if (current.IsKeyDown(Keys.Z))
        {
            elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds * 5.0f;
        }

        /// <summary>
    /// Check for the ball to return normal speed after the Powerup has expired
    /// </summary>
    public void NormalSpeed(GameTime gameTime)
    {
        moveSpeed += (15f * elapsedTime);
    }
 }

```

**UPDATE:**

I seem to have found a temporary solution, by using the follow method, however I am not sure of where I should place ElapsedTime so that it affects ALL of my classes and their updates (ex: the ball as well). As it stands, when I hit Z the bat will slow down because I am changing the ElapsedTime float, but I think I may have figured out a way to allow the ball to use it too. I may just have the Z key turn float down from 50 into 5 in all classes when pressed:

```
        /// <summary>
    /// Updates the position of the AI bat, in order to track the ball
    /// </summary>
    public virtual void UpdatePosition(Ball ball, GameTime gameTime)
    {
        size.X = (int)Position.X;
        size.Y = (int)Position.Y;

       elapsedTime =  50.0f * (float)gameTime.ElapsedGameTime.TotalSeconds;

       previous = current;
       current = Keyboard.GetState();
       if (current.IsKeyDown(Keys.Z))
       {
           elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds * 5.0f;
       }
     }

        /// <summary>
    /// Controls the bat moving up the screen
    /// </summary>
    public void MoveUp()
    {
        SetPosition(Position + new Vector2(0, -moveSpeed * elapsedTime));

    }

```

---

I'm trying to create a slow-mo effect in my pong game so that when a player is a button the paddles and ball will suddenly move at a far slower speed. I believe my understanding of the concepts of adjusting the timing in XNA are done, but I'm not sure of how to incorporate it into my design exactly.

The updates for my bats (paddles) are done in my Bat.cs class:

```
        /// Controls the bat moving up the screen
    /// </summary>
    public void MoveUp()
    {
        SetPosition(Position + new Vector2(0, -moveSpeed));
    }

    /// <summary>
    /// Controls the bat moving down the screen
    /// </summary>
    public void MoveDown()
    {
        SetPosition(Position + new Vector2(0, moveSpeed));
    }

    /// <summary>
    /// Updates the position of the AI bat, in order to track the ball
    /// </summary>
    /// <param name="ball"></param>
    public virtual void UpdatePosition(Ball ball)
    {
        size.X = (int)Position.X;
        size.Y = (int)Position.Y;
    }

```

While the rest of my game updates are done in my GameplayScreen.cs class (I'm using the XNA game state management sample)

```
Class GameplayScreen
{
        ...........
        bool slow;
        ..........
      public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)

  base.Update(gameTime, otherScreenHasFocus, false);

     if (IsActive)
            {
                // SlowMo Stuff
                Elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
                if (Slowmo) Elapsed *= .8f;

                MoveTimer += Elapsed;

                    double elapsedTime = gameTime.ElapsedGameTime.TotalMilliseconds;

                if (Keyboard.GetState().IsKeyDown(Keys.Up))
                    slow = true;
                else if (Keyboard.GetState().IsKeyDown(Keys.Down))
                    slow = false;

                    if (slow == true)
                    elapsedTime *= .1f;

                    // Updating bat position
                leftBat.UpdatePosition(ball);
                rightBat.UpdatePosition(ball);

                // Updating the ball position
                ball.UpdatePosition();

```

and finally my fixed time step is declared in the constructor of my Game1.cs Class:

```
    /// <summary>
/// The main game constructor.
/// </summary>
public Game1()
{
    IsFixedTimeStep = slow = false;

}

```

So my question is: *Where do I place the **MoveTimer** or **elapsedTime**, so that my bat will slow down accordingly?*

# Answer
> 0 votes
I thought I had answered this the other day, but I guess it didn't go through for some reason.

Thank you all for taking the time to help me. My problem was that I had two floats for determining how quickly my ball was traveling, for some reason. I had speed and moveSPeed. I'm not sure why I ever had this, but it was casing issues. Therefore everything is just using speed now and it looks like this:

```
        ///<summary>
    ///Used for slowing down the ball when SlowMo is active
    ///</summary>
    public void SlowMoBall()
    {
        speed = 2f;
    }

```

# Answer
> 1 votes
I'm currently on my smartphone so can't provide a lengthy awnser right now.

Implementing slowmotion is as easy as this :

Leftbat.x += (leftbat.speedX * gametime.ElapsedSeconds) * 0.1; //0.1 is 10% of original speed

You don't have to modify the elapsedtime variable itself.

# Answer
> 1 votes
You only need to multiply your velocity vector by the time to know the offset, this way if time is smaller, then the offset applied to the position will be smaller too:

```
public void MoveUp()
{
    SetPosition(Position + new Vector2(0, -moveSpeed) * ElapsedTime);
}

public void MoveDown()
{
    SetPosition(Position + new Vector2(0, moveSpeed ) * ElapsedTime);
}

```

EDIT:

I'd pass the elapsedtime as a function argument, doing something like this

```
Vector2[] Directions = { Vector.UnitX, -Vector.UnitX, Vector.UnitY, -Vector.UnitY }
enum Direction { Right, Left, Down, Up };
public void Move(Direction dir, float ElapsedTime) {
   SetPosition(Position + Directions[(int)dir] * moveSpeed * ElapsedTime);
}

```

EDIT FOR UPDATE2:

I think you are a bit confused... :) ,

you are doing

```
 position.X += speed * ((float)Math.Cos(direction))

```

if speed is constant, the ball will move at constant speed. I can see:

```
public void NormalSpeed(GameTime gameTime)
{
    moveSpeed += (15f * elapsedTime);
}

```

but yor not using moveSpeed, you are using speed to modify position. :? and you are adding speed in method named normalspeed ... I can't understand what are you doing... :(

I'd do it this way:

```
public void UpdatePosition(GameTime gameTime)
{
    float newSpeed = default_speed;
    float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds;

    // Update position
    size.X = (int)position.X;
    size.Y = (int)position.Y;
    oldPos.X = position.X;
    oldPos.Y = position.Y;

    if (ActivePowerUps.Contains(PowerUp.SlowDown))
    {
        newSpeed *= 0.5f; // 50% slowdown
    }

    position.X += newSpeed * ((float)Math.Cos(direction));
    position.Y += newspeed * ((float)Math.Sin(direction));
    bool collided = CheckWallHit();
    particleEngine.Update();
}

public void UpdatePowerUps()
{
    previous = current;
    current = Keyboard.GetState();

    if (!ActivePowerUps.Contains(PowerUp.SlowDown))
    {
      if (current.IsKeyDown(Keys.Z)) ActivePowerUps.Add(PowerUp.SlowDown);
    }
}

public void RemovePowerUp(PowerUp power)
{
    if (ActivePowerUps.Contains(power)) ActivePowerUps.remove(power);
}

```

# Answer
> 0 votes
you can do like above using a multiplication factor. However it should be noted, you do not want to change the elapsed time (you can't I don't think anyway) because it refers to the actual FPS of the game and that is the worst way to affect in game time.

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


title: How do I repeat a texture with GLKit?

text:
# Question
Title: How do I repeat a texture with GLKit?
I am using GLKit in order to show textures on my project. The code is like this:

```
-(void)setTextureImage:(UIImage *)image {
  NSError *error;
  texture = [GLKTextureLoader textureWithCGImage:image.CGImage options:nil error:&error];
  if (error) {
      NSLog(@"Error loading texture from image: %@",error);
  }
}

effect.texture2d0.envMode = GLKTextureEnvModeReplace;
effect.texture2d0.target = GLKTextureTarget2D;
effect.texture2d0.name = texture.name;

glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, 0, self.textureCoordinates);

```

Now I want to repeat this texture on a rectangle. Is there any way use GLKit for this behavior? I've tried to use opengl function in addition to the glkit ones, but it raises errors:

```
glEnable(GL_TEXTURE_2D);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
glBindTexture( GL_TEXTURE_2D, texture.name );

```

> 2011-11-09 20:10:28.614 ********\[16309:207\] GL ERROR: 0x0500
>
> 2011-11-09 20:10:30.840 ********\[16309:207\] Error loading texture from image: Error Domain=GLKTextureLoaderErrorDomain Code=8
>
> "The operation couldn’t be completed. (GLKTextureLoaderErrorDomain error 8.)" UserInfo=0x68545c0 {GLKTextureLoaderGLErrorKey=1280, GLKTextureLoaderErrorKey=OpenGL error}

# Answer
> 1 votes
Probably a bit out-dated, But you need to set `NSError *error;` to `NSError *error = nil;` Already broke my head around this.

# Answer
> 1 votes
Your images have to be powers of 2, you shouldn't call glEnable(GL\_TEXTURE\_2D), and you need to call

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

```

after

```
[_baseEffect prepareToDraw];

```

# Answer
> 0 votes
Not sure if you ever solved it, but this is what worked for me:

```
texture = [GLKTextureLoader textureWithCGImage:image.CGImage options:nil error:&error];
if(error) {
    NSLog(@"Error loading texture from image: %@", error);
} else {
    glEnable(GL_TEXTURE_2D);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
}

```

---
Tags: opengl-es, ios
---


# Question
Title: How do I handle specific tile/object collisions?
What do I do after the bounding box test against a tile to determine whether there is a real collision against the contents of that tile? And if there is, how should I move the object in response to that collision?

I have a small object, and test for collisions against the tiles that each corner of it is on.

Here's my current code, which I run for each of those (up to) four tiles:

```
// get the bounding box of the object, in world space
objectBounds = object->bounds + object->position;
if ( (objectBounds.right >= tileBounds.left) &&
     (objectBounds.left <= tileBounds.right) &&
     (objectBounds.top >= tileBounds.bottom) &&
     (objectBounds.bottom <= tileBounds.top))
{
    // perform specific test to see if it's a left, top , bottom
    // or right collision. If so, I check to see the nature of it
    // and where I need to place the object to respond to that collision...
    // [THIS IS THE PART THAT NEEDS WORK]
    //
    if( lastkey==keydown[right] && ((objectBounds.right >= tileBounds.left) &&
                                   (objectBounds.right <= tileBounds.right) &&
                                   (objectBounds.bottom >= tileBounds.bottom) &&
                                   (objectBounds.bottom <= tileBounds.top)) )
    {
        object->position.x = tileBounds.left - objectBounds.width;
    }
    // etc.

```

# Answer
What I do in my 2D engine, is that I define a Polygon type property (called CollisionPolygon) for all classes that represent collidable objects. My Polygon type is basically just a list of lines. (More precisely, line sections. Each line is defined by its 2 end points.) You have to define the edges of the collision polygon of your objects manually once. If you have only a couple of objects to be tested for collision, you can use complex polygons with 100+ edges and it won't affect the performance drastically. If you have hundreds of objects, than you should stick to 4-12 sided polygons, just in case.

The next step is to implement the Point-in-Polygon algorithm. Since you didn't state which programming language or framework do you use, here's a sample implementation:

https://stackoverflow.com/questions/217578/point-in-polygon-aka-hit-test

Then you create another method, using Point-in-Polygon, that tests if two Polygons are colliding (if any of Polygon A's edges is inside Polygon B, then it's a collision).

**NOTE:** You have to do it both ways (it is possible, that A has none of its edges in B, but B has one or more of its edges in A). Also note, that depending on the velocity of the objects, and your game's refresh rate, you might miss some collisions! Imagine two needle-like polygons crossing each other's path at high velocity. At time T1, they have no overlapping areas. At time T2, they intersect, but none of them have edges in the other one. This will not be detected with the Point-in-Polygon method. If this seems to be a problem in your engine, you will have to do some more research.

Finally, implement your own way of handling actual collisions. It really depends on what you want to do... In my engine, I always store the previous position of the object, and reset the colliding objects' positions to it whenever a collision occurs. I also calculate the inertia of the two objects (velocity * mass), multiply it with an arbitrary \<1 value ("energy loss"), and calculate the new velocities of the colliding objects, using good old primary school physics.

I recommend defining an interface for all of these (ICollidable, for example), that contains the following: CollisionPolygon property (type: Polygon), BoundingRectangle property (type: Rectangle), bool CollidesWith(ICollidable otherObj) method.

Then your collision detection will be basically this: 1. For every ICollidable on the scene, do the BoundingRectangle test with all the other objects. 2. If two objects' bounding rectangles collide, then do the polygon-based collison test. 3. If the polygon-based test is also positive, then register the collision (perhaps by storing indexes of the two objects). 4. Once all the objects have been tested for collisions, go through the registered collision instances, and do your "OnCollision" stuff. In my engine, this is where I sum up all the inertia changes for a given object, and then apply the changes.
> 2 votes

# Answer
This explanation is a working solution, but it's not the most optimal.

You can build a mask for the tile and also the object it collides with ... these may be pre-computed along with the bitmap you draw, but sometimes the mask is made up of non-zero pixels. So where a pixel is color 0, you don't considder it to be part of the object or part of the tile. So, by using pixel color 0, you remove the need to build a seperate mask. Now, where a bounding box collision has occured, you want to create a mask-collision box that encompasses both the tile and object (this is in an offscreen buffer). For any pixel where both masks collide ... that is, a pixel is visible on both masks, you have a collision.

What to do from here ... you could bounce the object back in the direction it came from, (which makes a collision feel "sticky"), or you could have another mask with collision actions stored in it ... essentially saying "If you collide with this pixel, move in this direction".

You can optimise this approach by several ways ... 1) Using a preset color to use as the masks, meaning you don't need to build seperate masks for collision 2) when building the mask collision box, it only needs to encompass either the tile OR the object, and then you draw to that box using clipping, just like when drawing to the screen. 3) If your mask is a bitmap array, you could use the number 1 to indicate that this pixel is collidable, and 0 for not being collidable, and then you only need to perform a LOGIC AND of the two masks together, and any non-zero value means a collision occured. 4) If you are using paletised bitmaps, you could see if you could get away with only 127 colors in your bitmap, and allocate 1 bit in the colors to the mask, thereby combining method 1 and 3. 5) If you have managed to implement methods 2 and 4, you might realise that you don't actually need to draw to a collision box, but can perform inline collision testing.
> 0 votes

---
Tags: 2d, collision-detection, tiles, tilemap
---


# Question
Title: Split a 2D scene in layers or have a z coordinate
I am in the process of writing a 2D game engine, and a dilemma emerged. Let me explain the situation...

I have a Scene class, to which various objects can be added (Drawable, ParticleEmitter, Light2D, etc), and as this is a 2D scene, things will obviously be drawn over each other.

My first thought was that I could have basic add and remove methods, but I soon realized that then there would be no way for the programmer to control the order in which things were drawn.

So I can up with two options, each with its pros and cons.

**A)** Would be to **split the scene in layers**. By that I mean instead of having the scene be a container of objects, have it be a container of layers, which are in turn the containers of objects.

**B)** Would require to **have some kind of z-coordinate**, and then have the scene sorted so objects with lower z get drawn first.

Option **A** is pretty solid, but the problem is with the lights. In what layer do I add it? Does it work cross-layer? On all bottom layers? And I still need the Z coordinate to calculate the shadow!

Option **B** would require me to change all my code from having Vector2D positions, to some kind of class that inherits from Vector2D and adds a z coordinate to it (I don't want it to be a Vector3D because I still need all the same methods the 2D kind has, just with .z clamped on).

Am I missing something? Is there an alternative to these methods?

I'm working in Javascript, if that makes a difference.

**Edit:** it was hard to decide with which option should I go, but I chose option **B, adding the z coordinate.** Some other design choices that might help others reading this question:

* The actual map is a 2D space, and therefor, all positions should be Vector2D instances. But, as I also need a third coordinate, I made a new class, called ScenePosition, which inherits from Vector2D and just adds a z option. What was crucial was to keep the methods thinking that they are still operating on a Vector2D instance.
* There is no way that sorting the scene by the z axis on every frame would be efficient, so watch out when adding things to the scene. For example: you would add a `4` at the end of this list, not the beginning: `[1, 2, 3]`.
* I chose to have a `changedOrder` property on the Scene, which you set to true when you change the z coordinate of some object. Then, the array is sorted before rendering, and `changedOrder` is set to `true`.

# Answer
I'd go for **option B**, and yes this will require that you slighly modify the base classe(s) of you renderable objects so it contains at least the following:

* A 2D vector for the position;
* A Z-coordinate for depth sorting.

Using layers (option A) might seem to be a good idea when you start, but it's not necessarily the best option. This way your objects don't know where they are: **this adds extra levels of indirection when they need to retrieve their depth**.

That's why, to me, option B is the way to go if you want to avoid code complexity on the long term. It'll take a bit more time to implement first, sure. But I've seen a big option A -\> option B refactoring on a quite mature engine and a quite advanced production, and this wasn't pretty.

There are some caveats, such as making sure you'll always sort the same 2 objects with identical Z-coordinates (hint: give them UIDs). Otherwise that's a call for Z-fighting.

A good idea, but not necessarily a must, is to use a floating-point format for your Z-coordinate. You can have a few preset values (eg `PlayerZ = 0.0`, `EnemiesZ = -1.0`, `BackgroundZ = 10.0`). But you keep an almost-infinite number of "layers" when you need to change your draw order. Let's say you need to add a weapon to your player and enemies: just use a `WeaponsZOffset = -0.1` for them. Simply more flexible than integers.
> 4 votes

# Answer
Option `A` seems best to me. I don't do much in 2D, but isn't the draw order what's really important?

Each item has an index, things added last get drawn last therefore being on top. You can give the user the option to change the order ("send to back", "bring to front" type things). I don't know how you're using lights, but it seems like those could be at any layer as well. Meaning things on top of lights would be dark and things under lights would be lit. That's just my rambling thoughts, perhaps telling me how I'm wrong will spark a new idea :)
> 4 votes

# Answer
I currently implement Option B in my engine, but it was built from the ground up with z-indexes in mind (and in C++). 2D Vectors are just 3D Vectors with the third parameter set to 1, so refactoring a z-index into your 2D vectors wouldn't be hard.

See SourceMaking.com's page on the subject (Well, not really, it's for adding a parameter to a method, but it should still work)
> 1 votes

---
Tags: 2d, javascript
---


# Question
Title: How to synchronise the acceleration, velocity and position of the monsters on the server with the players?
I'm building an MMO using Node.js, and there are monsters roaming around. I can make them move around on the server using vector variables acceleration, velocity and position.

acceleration = steeringForce / mass;

velocity += acceleration * dTime;

position += velocity * dTime;

Right now I just send the positions over, and tell the players these are the "target positions" of the monsters, and let the monsters move towards the target positions on the client with a speed dependant on the distance of the target position. It works but looks rather strange.

How do I synchronise these properly with the players without looking funny to them, taking into account the server lag?

The problem is that I don't know how to make use of the correct acceleration/velocity values here; right now they just move directly in a straight line to the target position instead of accelerating/braking there properly. How can I implement such behaviour?

# Answer
> 5 votes
There are several things you could do to reduce the visible effects of lagging. Just some ideas:

1. Send the current acceleration, velocity and position values to the client, and let the client calculate the new velocities and positions until it receives a new data package.
2. Avoid using frequently changing acceleration.
3. You should consider defining states of the characters. For example: When a monster attacks, it has 2 acceleration, 0 starting velocity (vector pointing towards the player), and this state lasts for 2 seconds. You can send the identifier of the monster's current state, and the client will know the speed and acceleration values, and will know that it's gonna last exactly for 2 seconds. This way the client can draw the movement smoothly. If something happens in those 2 seconds, eg. the monster dies, then the client receives the new state ("Dying") and can show the animation of that state. Also, define default state changes. For example, a monster will have the "Dead" state as default after the "Dying" state. If "Dying" lasts for 3 seconds, and the client doesn't receive any updates for 3 seconds, your monster isn't gonna get stuck in the "Dying" state, but will die properly on the client side as well.
4. You could implement some kind of lag compensation on the client side. For example, a small delay to the actions of the player, or effects of spells etc. If the player pushes the jump button, he won't jump immediately, but only after 40 milliseconds or so. The packet gets sent to the server with a timestamp, and forwarded to another player if necessary. The server and the other player's client will know that the actual jumping should be displayed only at Timestamp + 40 milliseconds. You can make this work with most actions without making the delay frustratingly high.
5. Further reading:

https://stackoverflow.com/questions/1448997/do-good-multiplayer-mmo-clientserver-games-use-latency-within-movement-calcula

Low traffic client synchronization with server in MMO

How do I keep an MMO synchronized?

---
Tags: architecture, physics, server, node.js
---


# Question
Title: Blur gets displaced compared to original image
I have implemented a SSAO and I'm using a blur step to smooth it out. The problem is that the blurred texture is slightly displaced compared to the original. I'm blurring using a 4x4 kernel since that was my noise kernel in SSAO. The following is the blurring shader:

```

float result = 0.0;
for(int i = 0; i < 4; i++){
    for(int j = 0; j < 4; j++){
        vec2 offset = vec2(TEXEL_SIZE.x * i, TEXEL_SIZE.y * j);
        result += texture(aoSampler, TexCoord + offset).r;
    }
}

out_AO = vec4(vec3(0.0), result * 0.0625);

```

Where `TEXEL_SIZE` is one over my window resolution.

I was thinking that this is was an error based on how OpenGL counts the Texel center, so I tried displacing the texture coordinate I was using by `0.5 * TEXEL_SIZE`, but there was still a slight displacement.

The texture input to my blur shader, has wrap parameters:

```

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

```

When I tell the blur shader to just output the the value of the pixel, the result is not displaced, so it must have something to do with how neighboring pixels are sampled.

Any thoughts?

# Answer
> 2 votes
I think you should change your for loop to something like this (you should take current pixel and few pixels around it, not only one way from current pixel):

```
for(int i = -2; i < 2; i++){
    for(int j = -2; j < 2; j++){
        vec2 offset = vec2(TEXEL_SIZE.x * i, TEXEL_SIZE.y * j);
        result += texture(aoSampler, TexCoord + offset).r;
    }
}

```

Because your kernel is 4\*4, it's even count, it could be still shifted. If it's odd (for example 3\*3 or 5\*5), it would be better.

---
Tags: opengl, shaders, glsl, blur
---


# Question
Title: Is there an ideal width to height ratio?
I would like to know if there is any "ideal" width to height ratio when creating games for the web.

My canvas is fluid, and resizes according to the browser width and height. But with all the devices out there it's difficult to know what ratio to choose.

Right now i have 4:3 (Width:Height), but is there any ratio that would fit well in most devices?

Thank you.

# Answer
> 4 votes
There is no standard size for screens and it is big problem. Andriod uses some standard screen sizes then stretches one of them for any other size of screen

* res-long-land-hdpi 800x480
* res-long-land-ldpi 400x240
* res-long-port-hdpi 480x800
* res-long-port-ldpi 240x400
* res-notlong-land-hdpi 800x480
* res-notlong-land-ldpi 320x240
* res-notlong-land-mdpi 480x320
* res-notlong-port-hdpi 480x800
* res-notlong-port-ldpi 240x320
* res-notlong-port-mdpi 320x480

You might like to design your game screen in a way that your GUI scale with any size of screen. for example have your toolbar attach to top of screen and your action buttons stick to bottom of screen, as for background you can scale width or height to fit the smallest screen dimension and the biggest will hide some part of background.

# Answer
> 3 votes
Is not a Standard, but I like the Golden Ratio

With b + a = 480 a = 300.

Its your canvas, you choose the size. You must calculate a according with user's resolution

---
Tags: html5
---


# Question
Title: Question about BoundingSpheres and Ray intersections
I'm working on a XNA project (not really a game) and I'm having some trouble with picking algorithm. I have a few types of 3D models that I draw to the screen, and one of them is a switch. So I'm trying to make a picking algorithm that would enable the user to click on the switch and that would trigger some other function. The problem is that the BoundingSphere.Intersect() method always returns null as result. This is the code I'm using:

In the declaration section: \`

```
//Basic matrices
private Matrix world = Matrix.CreateTranslation(new Vector3(0, 0, 0));
private Matrix view = Matrix.CreateLookAt(new Vector3(10, 10, 10), new Vector3(0, 0, 0), Vector3.UnitY);
private Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), 800f / 600f, 0.01f, 100f);

//Collision detection variables
Viewport mainViewport;
List<BoundingSphere> spheres = new List<BoundingSphere>();
Ray ControlRay;
Vector3 nearPoint, farPoint, nearPlane, farPlane, direction;

```

\`

And then in the Update method: \`

```
nearPlane = new Vector3((float)Mouse.GetState().X, (float)Mouse.GetState().Y, 0.0f);
farPlane = new Vector3((float)Mouse.GetState().X, (float)Mouse.GetState().Y, 10.0f);

nearPoint = GraphicsDevice.Viewport.Unproject(nearPlane, projection, view, world);
farPoint = GraphicsDevice.Viewport.Unproject(farPlane, projection, view, world);

direction = farPoint - nearPoint;
            direction.Normalize();
            ControlRay = new Ray(nearPoint, direction);
            if (spheres.Count != 0)
            {
                for (int i = 0; i < spheres.Count; i++)
                {
                    if (spheres[i].Intersects(ControlRay) != null)
                    {
                        Window.Title = spheres[i].Center.ToString();
                    }
                    else
                    {
                        Window.Title = "Empty";
                    }
                }

```

\`

The "spheres" list gets filled when the 3D object data gets loaded (I read it from a .txt file). For every object marked as switch (I use simple numbers to determine which object is to be drawn), a BoundingSphere is created (center is on the coordinates of the 3D object, and the diameter is always the same), and added to the list. The objects are drawn normally (and spheres.Count is not 0), I can see them on the screen, but the Window title always says "Empty" (of course this is just for testing purposes, I will add the real function when I get positive results) meaning that there is no intersection between the ControlRay and any of the bounding spheres. I think that my basic matrices (world, view and projection) are making some problems, but I cant figure out what. Please help.

# Answer
> 1 votes
Your mistake is hidden in this line:

```
farPlane = new Vector3((float)Mouse.GetState().X, (float)Mouse.GetState().Y, 10.0f);

```

this vector represents position in screen space. 0,0 is on upper left corner. `Z` here represents depth in range from `0` to `1`. So value 10 is not correct. You must use this:

```
farPlane = new Vector3((float)Mouse.GetState().X, (float)Mouse.GetState().Y, 0.99f);

```

Something more about ray picking can be found here: http://www.innovativegames.net/blog/blog/2009/03/17/picking/

---
Tags: collision-detection, xna-4.0
---


# Question
Title: Panning with the OpenGL Camera / View Matrix
I'm gonna try this again

I've been trying to setup a simple camera class with OpenGL but I'm completely lost and I've made zero progress creating anything useful. I'm using modern OpenGL and the glm library for matrix math. To get the most basic thing I can think of down, I'd like to pan an arbitrarily positioned camera around. That means move it along its own Up and Side axes. Here's a picture of a randomly positioned camera looking at an object:

It should be clear what the Up (Green) and Side (Red) vectors on the camera are. Even though the picture shows otherwise, assume that the Model matrix is just the identity matrix. Here's what I do to try and get it to work:

Step 1: Create my View/Camera matrix (going to refer to it as the View matrix from now on) using glm::lookAt().

Step 2: Capture mouse X and Y positions.

Step 3: Create a translation matrix mapping changes in the X mouse position to the camera's Side vector, and mapping changes in the Y mouse position to the camera's Up vector. I get the Side vector from the first column of the View matrix. I get the Up vector from the second column of the View matrix.

Step 4: Apply the translation: viewMatrix = glm::translate(viewMatrix,translationVector);

But this doesn't work. I see that the mouse movement is mapped to some kind of perpendicular axes, but they're definitely not moving as you'd expect with respect to the camera. Could someone please explain what I'm doing wrong and point me in the right direction with this camera stuff?

# Answer
Well how do you create the translationVector? How does the camera act?

The thing is that a World to Camera matrix is not a matrix that tells you the position and orientation of the Camera in world space. It's the inverse of that. You can't extract axii from it like you'd from a "regular" matrix. If you want to do this your way then try inversing the World to Camera matrix, then extracting the axii.

If you're concerned with performance, then you can either extract rows instead of columns (which is probably the fastest solution) or take the 3x3 rotation matrix and transpose it, then extract the vectors. The camera transformation is an affline transformation, so transposing the pure rotation matrix should give the same resaults as calculating the inverse (extracting rows instead of columns is effectively a transposition, it's just a shortcut).
> 2 votes

---
Tags: c++, opengl, camera
---


# Question
Title: Need to combine a color, mask, and sprite layer in a shader
My task: to display a sprite using different team colors. I have a sprte graphic, part of which has to be displayed as a team color. The color isn't 'flat', i.e. it shades from brighter to darker. I can't "pre-build" the graphics because there are just too many, so I have to generate them at runtime. I've decided to use a shader, and supply it with a texture consisting of the team color, a texture consisting of a mask (black=no color, white=full color, gray=progressively dimmed color), and the sprite grapic, with the areas where the team color shows being transparent.

So here's my shader code:

```
// Effect attempts to merge a color layer, a mask layer, and a sprite layer
// to produce a complete sprite

sampler UnitSampler : register(s0); // the unit
sampler MaskSampler : register(s1); // the mask
sampler ColorSampler : register(s2);    // the color

float4 main(float4 color : COLOR0, float2 texCoord : TEXCOORD0) : COLOR0
{
    float4 tex1 = tex2D(ColorSampler, texCoord);    // get the color
    float4 tex2 = tex2D(MaskSampler, texCoord); // get the mask
    float4 tex3 = tex2D(UnitSampler,texCoord);  // get the unit
    float4 tex4 = tex1 * tex2.r * tex3; // color * mask * unit

    return tex4;
}

```

My problem is the calculations involving tex1 through tex4. I don't really understand how the manipulations work, so I'm just thrashing around, producing lots of different incorrect effects. So given tex1 through tex3, what calcs do I do in order to take the color (tex1), mask it (tex2), and apply the result to the unit if it's not zero?

And would I be better off to make the mask just on/off (white/black) and put the color shading in the unit graphic?

# Answer
> 3 votes
Might I suggest that the simplest (and so probably the best) solution is not to use a custom shader at all. Simply have two sprites.

The first sprite can be your "base" layer containing parts of the unit common to all teams. This can be colour with an alpha channel.

And the second layer would contain only the team-coloured elements in grayscale with an alpha channel that then gets colour tinted by the default sprite batch shader.

```
spriteBatch.Draw(baseTexture, position, Color.White);
spriteBatch.Draw(teamOverlayTexture, position, teamColor);

```

---

However, if you have your heart set on using a multi-texture shader:

Your first issue seems to be that you're trying to have your mask texture provide two things at once - both **transparency** and **value**. My reading of your question is that you want the value of 0 on your mask texture to be fully transparent. But a value like 0.1 to be "fully opaque and almost black".

So the first thing to do would be to make your mask texture's black-and-white colour values provide the level of grayscale "shadowing". Then give your mask an alpha channel to provide the transparency values for what areas of the unit have colour applied.

Once you have done this, this pixel shader code (that I haven't tested) should give you the right result (I've renamed your variables for better clarity - you should do the same):

```
float4 outColor;
outColor.rgb = teamColor.rgb * mask.rgb + baseTexture.rgb;
outColor.a = mask.a + baseTexture.a;

```

Actually code like the following would be better, I wanted to show you how to access sub-elements. If you ensure the team colour is always opaque, then this works:

```
outColor = teamColor * maskColor + baseTexture;

```

Note #1: This assumes both your `mask` and `baseTexture` textures have premultiplied alpha, and you are using a premultiplied alpha output blend. This is the default in XNA 4.

Note #2: `teamColor` doesn't have to come from a texture. You should probably provide it via a shader parameter.

(Of course, the textures used and the result is identical to the sprite-batch code above. So I'd go with that unless you're going to do something fancier in the shader.)

---
Tags: xna-4.0, hlsl, fragment-shader
---


# Question
Title: Engine Start and Stop Show Abnormal Behaviour
In my game, when I pause the game using mEngine.stop() it works perfectly but when I press resume button that has code mEngine.start() it provide some movement to the physics body. So the created body does not stand at its desire position after the resuming the game. That fault I have found in other game developed by other developer also. So please provide some guidance for it. I also tried with mScene.onUpdate(0) and mScene.onUpdate(1) but I does not able to found anything new from it.

# Answer
I think it is caused by a spike in CPU usage when you resume the game. Box2D works on a best-effort basis so when the CPU is being overloaded momentarily, the Box2D execution drops to too small a number of steps per second. This causes problems.

There are two things you can do to improve the situation. a) Let the engine sleep for a while after the resume button is pressed. b) Implement MaxStepPhysicsWorld, you will find it on the AndEngine forums. It allows you to set a minimum steps the engine has to calculate each second and if it cannot keep up, the execution will slow down but it will not break down like this.
> 1 votes

---
Tags: andengine
---


# Question
Title: How can I track the frame rate on a mobile device?
I am trying to track the frame rate when performaing certain actions on my mobile device.

Scenario: I open my game via the device browser and run through specific actions. Preferably would like the frame rate stored somewhere, like a text file. Would settle for visual display if that is not possible.

# Answer
> 2 votes
Since you apparently don't want this for the end user, I'd suggest just running with the performance monitor.

With your device connected try running:

`Run -> Run With Performance Tool -> OpenGL ES.`

That'll give you Core Animation FPS, but also loads of other stats about your application, which is probably more helpful to you if you're trying to assess performance issues.

---
Tags: iphone, frame-rate
---


# Question
Title: Get all triangles that are < N dist from you?
Does anyone know of a way I could add a radius to this code for p? Like basically saying "this is true if the triangle is \< N dist from the point"

```
public boolean isPointInTriangle( Vector3f p, Vector3f a, Vector3f b, Vector3f c )
{
    return ( pointsAreOnSameSide(p, a, b, c) && pointsAreOnSameSide(p, b, a, c) && pointsAreOnSameSide(p, c, a, b) );
}

public boolean pointsAreOnSameSide( Vector3f p1, Vector3f p2, Vector3f a, Vector3f b )
{
    Vector3f diffba = new Vector3f(0,0,0);
    Vector3f.sub( b, a, diffba );
    Vector3f diffp1a = new Vector3f(0,0,0);
    Vector3f.sub( p1, a, diffp1a );
    Vector3f diffp2a = new Vector3f(0,0,0);
    Vector3f.sub( p2, a, diffp2a );

    Vector3f cross1 = Vector3f.cross(diffba, diffp1a);
    Vector3f cross2 = Vector3f.cross(diffba, diffp2a);

    return ( Vector3f.dot( cross1, cross2 ) >= 0 );
}

```

# Answer
First, calculate the centroid of your triangle:

```
// the centroid is the average of the three points and is always the
// point in which the triangle is balanced
Vector3f centroid = (a + b + c) / 3;

```

Then, put it in the formula:

```
public boolean checkDistanceToTriangle(Vector3f a_Centroid, Vector3f a_Point, float a_Distance)
{
    // i'm just guessing that the length function exists
    // .length returns the magnitude between a_Centroid and a_Point
    return (Vector3f.length(a_Centroid - a_Point) < a_Distance);
}

```
> 2 votes

# Answer
For completeness, there are plenty of situations that knight666's answer misses. For example testing just the center of the triangle would miss this case:

And this case:

And this case:

To test all the cases, you need to check:

* If the circle center is contained in the triangle
* Test each edge of the triangle to see if it passes through the circle
* Test each vertex of the triangle to see if it's contained within the circle

Those can all be short circuited, so you can return true as soon as one case is detected. So you can sort them by complexity.

You can find an excellent article about triangle circle intersection here.
> 2 votes

---
Tags: java, 3d, mathematics
---


title: SDL Bullet Movement

text:
# Question
Title: SDL Bullet Movement
I'm currently working on my first space shooter, and I'm in the process of making my ship shoot some bullets/lasers. Unfortunately, I'm having a hard time getting the bullets to fly vertically. I'm a total noob when it comes to this so you might have a hard time understanding my code :/

```
    // Position Bullet Function
    projectilex = x + 17;
    projectiley = y + -20;
    if(keystates[SDLK_SPACE])
    {
        alive = true;
    }

```

And here's my show function

```
    if(alive)
    {

        if(frame == 2)
        {
            frame = 0;
        }
        apply_surface(projectilex,projectiley,ShootStuff,screen,&lazers[frame]);
        frame++;
        projectiley + 1;
    }

```

I'm trying to get the bullet to fly vertically... and I have no clue how to do that. I've tried messing with the y coordinate but that makes things worse. The laser/bullet just follows the ship :(

How would I get it to fire at the starting position and keep going in a vertical line without it following the ship?

```
int main( int argc, char* args[] )
{
Player p;
Timer fps;
bool quit = false;
if( init() == false )
{
    return 1;
}

//Load the files
if( load_files() == false )
{
    return 1;
}

clip[ 0 ].x = 0;
clip[ 0 ].y = 0;
clip[ 0 ].w = 30;
clip[ 0 ].h = 36;

clip[ 1 ].x = 31;
clip[ 1 ].y = 0;
clip[ 1 ].w = 39;
clip[ 1 ].h = 36;

clip[ 2 ].x = 71;
clip[ 2 ].y = 0;
clip[ 2 ].w = 29;
clip[ 2 ].h = 36;

lazers [ 0 ].x = 0;
lazers [ 0 ].y = 0;
lazers [ 0 ].w = 3;
lazers [ 0 ].h = 9;

    lazers [ 1 ].x = 5;
lazers [ 1 ].y = 0;
lazers [ 1 ].w = 3;
lazers [ 1 ].h = 7;

while( quit == false )
{
    fps.start();
    //While there's an event to handle
    while( SDL_PollEvent( &event ) )
    {
        p.handle_input();
        //If a key was pressed

        //If the user has Xed out the window
        if( event.type == SDL_QUIT )
        {
            //Quit the program
    quit = true;
    }

    }

    //Scroll background
    bgX -= 8;

    //If the background has gone too far
    if( bgX <= -GameBackground->w )
    {
    //Reset the offset
    bgX = 0;
    }
    p.move();
    apply_surface( bgX, bgY,GameBackground, screen );
    apply_surface( bgX + GameBackground->w, bgY, GameBackground, screen );

    apply_surface(0,0, FullHealthBar,screen);

    p.shoot();
    p.show();
    //Apply the message
    //Update the screen
    if( SDL_Flip( screen ) == -1 )
    {
    return 1;
    }
    SDL_Flip(GameBackground);
    if( fps.get_ticks() < 1000 / FRAMES_PER_SECOND )
    {
    SDL_Delay( ( 1000 / FRAMES_PER_SECOND ) - fps.get_ticks() );
    }
    }
    //Clean up
    clean_up();
    return 0;
    }

```

# Answer
> 7 votes
Well i was about to write a formerly answer, but seeing your code, it appears that you dont have any **Entity system**. So it may complicate you, but lets try to solve this.

We need a class to follow what are those bullets, and where are they, dont we?

So lets create something!

```
class Bullet
{
    Vector2 position;
    Vector2 speed;
};

```

If you have entities, probably you already had something like this. So just adapt yourself (:

What must we do? Lets try to describe in plain english what will the code do to shoot bullets.

Every frame, check if the space bar is pressed. If it is pressed, and wasnt before, create a new bullet, going to where the player is faced. If the bullet hits something, delete it, make some nice explode animation and take hp of the object that took the hit. If the bullet just goes after the screen boundaries, just delete it.

Lets try to pass it to C++.

First of all, you have to have some kind of container to storage your bullets. Of course you'll have more than one, so thats why.

Some kind like this on your initialization should do:

```
std::list<Bullet*> bullets;

```

I dont recommend lists for a game, but they're easier to deal for now.

Now, the code to shoot:

```
if(event.type == SDL_KEYDOWN)
{
    if(event.key == SDLK_SPACE)
    {
        Bullet* toShoot = new Bullet();
        toShoot.speed = player.direction * 5;
        toShoot.position = player.position + toShoot.speed;
        bullets.add(toShoot);
    }

}

```

Adapt it to your needs and current usages.

The most tricky part here is the player.direction * 5; Well, probably, you have a vector pointing where the player is facing, if you dont have, you **SHOULD**! When you multiply a vector by a number, you can get a nice speed direction going to that direction! so you'll have a 5px going into that direction. That may not be too right, but should work as a basis for you. Study distance and the pitagoras's formula d = sqrt(x^2 + y^2); If you just want the bullet to go up, change `toShoot.speed = player.direction * 5;`with `toShoot.speed = Vector(0, 5);`

To update your code, try:

```
for(list<Bullet*>::iterator it = bullets.begin(); it != bullets.end();)
{
    (*it)->position += (*it)->speed;
    if(isOutOfBound((*it)->position))
    {
        delete (*it);
        bullets.erase(it++); //remove from the list and take next
    }
    else if(collideWithSomething((*it)->position))
    {
        Entity collisor = getCollisor((*it)->position);
        collisor.takeHit();
        playSound(Explosion);
        makeAnimation(Explosion);
        delete (*it);
        bullets.erase(it++);
    }
    else
    {
        ++it; //take next object
    }
}

```

This should do :D

Remembering, the most of these classes you maybe dont have, but you should think about creating something similar.

# Answer
> 2 votes
```
PBullet.XPos=XPos+Enterprise.LImageLength/2; //get bullet YX start ship location
PBullet.YPos=YPos+Enterprise.LImageHeight/2; //get bullet YX start ship location
PBullet.XVel= PBullet.ShipSpeed*cos(ShipFacing);  //work out angle of bullet
PBullet.YVel= PBullet.ShipSpeed*sin(ShipFacing);  //work out angle of bullet
PBullet.TimeOfEvent= SDL_GetTicks(); //start timer for duration of bullet alive

```

You also need somthing like

```
GameObject ::apply_surface(SDL_Surface* source, SDL_Surface* destination, SDL_Rect* clip)
{
    SDL_Rect sourceImage;
    sourceImage.x = ShipSpritesheetX; //position in image file left to right
    sourceImage.y = ShipSpritesheetY; //position in image file up and down
    sourceImage.w = LImageHeight; //width of sprite in image
    sourceImage.h = LImageLength; //height of sprite in image
    SDL_Rect offset; //Holds offsets
    offset.x = XPos;  //Get offsets
    offset.y = YPos;
    SDL_BlitSurface( source, &sourceImage, destination, &offset );  //Blit
}

 PBullet.apply_surfacing(PlayerBullet, screen,NULL ); //display bullet while firing

```

---
Tags: c++, sdl, projectile-physics
---


title: One single texture atlas?

text:
# Question
Title: One single texture atlas?
When I want to use texture atlasing, should I try to place all of my sprites into one single texture atlas? Or are there times when I should have multiple smaller texture atlases?

# Answer
> 6 votes
Like many things in software, it's a balancing act. Fewer texture swaps is good, but getting textures that are too large can also hurt performance. Additionally, sprite sheets with a large number of sprites can be difficult to manage logistically.

To help manage larger sprite sheets, it's recommended that you keep your sprites separate, then join them into a sprite sheet for use in your game. You can use tools (both of which have very clever names) like:

Using these tools will allow you to ensure that animations that belong together end up on the same sprite sheet. That way you're not switching between textures mid animation.

Unfortunately there's no universal standard for maximum texture size. Not only that, but it varies from hardware to hardware, not just between graphics platforms. There are maximums that the graphics platforms can support though, but it doesn't mean the hardware supports it. Be sure to create a check with your game to ensure that you won't load a texture that's too large.

# Answer
> 5 votes
The fewer textures the better. So one big one would be best. However, depending on your platform and language there is a size limit to an image. So if 2048 x 2048 px is the largest your image can be and your texture atlas is bigger than that, it would be best to have two smaller atlases.

---
Tags: textures
---


# Question
Title: How do I get FEATURE_LEVEL_9_3 to work with shaders in Direct3D11?
Currently I'm going through some tutorials and learning DX11 on a DX10 machine (though I just ordered a new DX11 compatible computer) by means of setting the D3D\_FEATURE\_LEVEL\_ setting to 10\_0 and switching the vertex and pixel shader versions in D3DX11CompileFromFile to "vs\_4\_0" and "ps\_4\_0" respectively. This works fine as I'm not using any DX11-only features yet.

I'd like to make it compatible with DX9.0c, which naively I thought I could do by changing the feature level setting to 9\_3 or something and taking the vertex/pixel shader versions down to 3 or 2. However, no matter what I change the vertex/pixel shader versions to, it always fails when I try to call D3DX11CompileFromFile to compile the vertex/pixel shader files when I have D3D\_FEATURE\_LEVEL\_9\_3 enabled.

Maybe this is due to the the vertex/pixel shader files themselves being incompatible for the lower vertex/pixel shader versions, but I'm not expert enough to say.

My shader files are listed below:

Vertex shader:

```
cbuffer MatrixBuffer
{
matrix worldMatrix;
matrix viewMatrix;
matrix projectionMatrix;
};

struct VertexInputType
{
float4 position : POSITION;
float2 tex : TEXCOORD0;
float3 normal : NORMAL;
};

struct PixelInputType
{
float4 position : SV_POSITION;
float2 tex : TEXCOORD0;
float3 normal : NORMAL;
};

PixelInputType LightVertexShader(VertexInputType input)
{
PixelInputType output;

// Change the position vector to be 4 units for proper matrix calculations.
input.position.w = 1.0f;

// Calculate the position of the vertex against the world, view, and projection matrices.
output.position = mul(input.position, worldMatrix);
output.position = mul(output.position, viewMatrix);
output.position = mul(output.position, projectionMatrix);

// Store the texture coordinates for the pixel shader.
output.tex = input.tex;
// Calculate the normal vector against the world matrix only.
output.normal = mul(input.normal, (float3x3)worldMatrix);

// Normalize the normal vector.
output.normal = normalize(output.normal);

return output;
}

```

Pixel Shader:

```
Texture2D shaderTexture;
SamplerState SampleType;

cbuffer LightBuffer
{
float4 ambientColor;
float4 diffuseColor;
float3 lightDirection;
float padding;
};

struct PixelInputType
{
float4 position : SV_POSITION;
float2 tex : TEXCOORD0;
float3 normal : NORMAL;
};

float4 LightPixelShader(PixelInputType input) : SV_TARGET
{
float4 textureColor;
float3 lightDir;
float lightIntensity;
float4 color;

// Sample the pixel color from the texture using the sampler at this texture coordinate location.
textureColor = shaderTexture.Sample(SampleType, input.tex);

 // Set the default output color to the ambient light value for all pixels.
color = ambientColor;

// Invert the light direction for calculations.
lightDir = -lightDirection;

// Calculate the amount of light on this pixel.
lightIntensity = saturate(dot(input.normal, lightDir));

if(lightIntensity > 0.0f)
{
    // Determine the final diffuse color based on the diffuse color and the amount of light intensity.
    color += (diffuseColor * lightIntensity);
}

// Saturate the final light color.
color = saturate(color);

// Multiply the texture pixel and the final diffuse color to get the final pixel color result.
color = color * textureColor;

return color;
}

```

# Answer
> 4 votes
When targeting the `9_1`, `9_2` and `9_3` feature levels, the shader profiles you should use are:

* `vs_4_0_level_9_1`/`ps_4_0_level_9_1` for levels `9_1` and `9_2`, and;
* `vs_4_0_level_9_3`/`ps_4_0_level_9_3` for the `9_3` level.

This is hidden quite deeply in the MSDN documentation at

---
Tags: directx, directx11, directx9
---


# Question
Title: How can I draw a "vision cone" (targetting element) into the game world?
I'm wanting to indicate various things using a "pie slice" sort of shape as below. Similar to vision cones in stealth game minimaps, or targetting indicators in RTS type games for frontal area attacks. Something generic enough to be used for both would be ideal.

I need to be able to procedurally (and efficiently) change things like the slice width and length, color, transparency, position in the world, etc. For my particular situation, there's no concern with elevation, funky terrain, or really any third axis at all as far as this element is concerned.

I have two first inclinations on how to accomplish this: 1) Manually generate the vertices for a main triangle, (possibly two, superimposed to get the border effect), a handful more to approximate the arc at the end, and roll it into a mesh.

2) Use some sort of 2D drawing library to create a circle and mask it off at the right angles, render to texture, and use that.

For reference, I have some experience with Ogre3D, but I'm not attached to it as this is a mostly academic pursuit at the moment. Other technologies that might be better at accomplishing this are more than welcome.

Finally, I'm kind of curious about how to do a "flashlight" or similar 3D effect that could produce the same result, but on all surfaces in the lit area.

# Answer
> 5 votes
I happen to have some of that code handy. I created this direct drawing code for some 2D HUD type stuff. However, you should be able to easily convert it to store vertices and/or extend it to 3D. It takes a `center` as the pointy end and a start degree and end degree for how wide to span. Additionally, there's a `sides` parameter that will set the number of steps, more steps means smoother arch. This code creates a wedge on the xy plane.

```
  public static void DrawWedge(int centerX, int centerY, int sides, Color color,
     float alpha, float radius, double startDegree, double endDegree) {
        GL11.glBegin(GL11.GL_TRIANGLE_FAN);
        GL11.glColor4f(color.getRed(), color.getGreen(), color.getBlue(), alpha);
        GL11.glVertex3f(centerX, centerY, 0);
        double degrees = endDegree - startDegree;
        for (int i = 0; i <= sides; i++) { //create triangles to fill the wedge
            GL11.glVertex3f((float) (centerX + (Math.sin(Math.toRadians(startDegree + (degrees * ((float) i / (float) sides)))) * radius)),
            (float) (centerY - (Math.cos(Math.toRadians(startDegree + (degrees * ((float) i / (float) sides)))) * radius)),
             0);
        }
        GL11.glColor4f(1, 1, 1, 1);
        GL11.glEnd();
    }

```

As a bonus, I also have some code that generates a loop segment.

```
public static void DrawLoopSegment(int centerX, int centerY, int sides, Color color, float alpha, int innerRadius, int outerRadius, double startDegree, double endDegree) {
        GL11.glColor4f(color.getRed(), color.getGreen(), color.getBlue(), alpha);
        GL11.glBegin(GL11.GL_QUAD_STRIP);
        double degrees = endDegree - startDegree;
        for (int i = 0; i <= sides; i++) {
            GL11.glVertex3f((float) (centerX + (Math.sin(Math.toRadians(startDegree + (degrees * ((float) i / (float) sides)))) * innerRadius)),
                    (float) (centerY - (Math.cos(Math.toRadians(startDegree + (degrees * ((float) i / (float) sides)))) * innerRadius)), 0);
            GL11.glVertex3f((float) (centerX + (Math.sin(Math.toRadians(startDegree + (degrees * ((float) i / (float) sides)))) * outerRadius)),
                    (float) (centerY - (Math.cos(Math.toRadians(startDegree + (degrees * ((float) i / (float) sides)))) * outerRadius)), 0);
        }
        GL11.glEnd();
        GL11.glColor4f(1, 1, 1, 1);
    }

```

That code could be used from something that had a minimum and maximum firing range.

The image below was not produced by this code, since I'm away from my dev machine. But it gives an idea of the two types of shapes produced.

Where the blue section would be produced by the `DrawLoopSegment()` code and the red by the `DrawWedge()` code.

---
Tags: rts
---


# Question
Title: What applications can I use to generate music?
In my cocos2d iPhone app I wanted to have in game music. But I don't want to use garageband! It is just dragging prewritten loops. I wanted to compose the music for my game. Is there software that I can use to write music, such as techno music? Not taking songs that were made by someone else and adding effects.

# Answer
> 5 votes
See my answer about doing game sound in general for a small/one-man team.

List of Digital Audio Workstation software:

List of tracker software:

By the way, you're doing it wrong. Garageband is only dragging prewritten loops if you use it that way. It comes with some virtual instruments that you can compose with using MIDI regions (or whatever they're called in Garageband). You can also take those prewritten loops, cut them up inside Garageband or Audacity into different notes and place those accordingly. This is called sampling.

Which one should you use? Whichever one gives you the best results. It's different for everyone. If you want me to recommend a starting point, try out both FL Studio and Renoise and see which one you like better, then you know which category of software to choose from.

Or just find a musician. Seriously. There are TONS of people who want to write game music. And they're usually pretty good, much better than you will be (assuming music composition and production is just a passive interest or hobby for you).

# Answer
> 2 votes
Try abelton live - http://www.ableton.com/

# Answer
> 2 votes
Actually, you can access the musical score in GarageBand and write your own music by positioning notes. There's no need to use only loops.

As of iLife '09, these are the steps for opening the score (they're needlessly complex in my opinion):

* Open a new Loops project.
* Create a new Software Instrument track.
* Command-click in the new track somewhere to get a new empty area, and drag the bottom-right corner of the area to expand it.
* Double-click in the green area. This should bring up a menu from the bottom of the screen.
* Click on Score.

Now you can pick which notes to use and Command-click on the staff to insert notes, rests etc. This seems to work for any Software Instrument, so you could get an entire orchestra going right in GarageBand!

# Answer
> 2 votes
I suggest you use FL Studio. I used it, and it's pretty powerful. A lot of professionals use it as well.

It's an app where you can arrange sounds in patterns, synthetize sounds, import your own, and do a lot more.

---
Tags: music
---


title: Manually updating HTML5 local storage?

text:
# Question
Title: Manually updating HTML5 local storage?
I'm just starting out HTML5 game developement (and game dev in general) and watching all the videos and tutorials available something has crossed my mind.

Everyone keep saying I should set the cookie's (or cached files) to be expired after a certain amount of time. So that when it reaches that time the browser automatically downloads all assets again, even if it's the same asset's.

Wouldn't it be possible to manually define the version of the game? For example the user has downloaded all the files for 1.01 of the game, when updating I change a simple variable to 1.02. When the user logs in it would compare his version to the current and if they are not equal only then it downloads the files?

This could even be improved to download only specific files depending on what needs to be updated?

Would this be possible or am I just dreaming? What are the possible downsides of this approach?

# Answer
For that to work you need to go online and check for a new version, when the user opens the game. It's just a simple ajax call to the server, that then returns the current version number an perhaps a releasedate. That's how programs i general do it, so you should be able to do the same.

All that is left is then to compare version number, that you might save in a static variable, and download the new one if a newer version is available.
> 1 votes

---
Tags: javascript, html5
---


title: Wall Jump for 2D Platformer

text:
# Question
Title: Wall Jump for 2D Platformer
I've been looking for a way to implement wall-jump in my xna game, but I can't find any information about it, can someone could someone please help me out ?

# Answer
> 21 votes
When a player collides with a wall while jumping (or, if you like, falling), turn on a flag for the next 100 milliseconds or so that causes an attempt to jump to successfully initiate a jump (ignoring any surface contact checks) with a fair amount of speed on the X axis in the direction away from the wall. Remember to turn the flag off early if a jump is in fact initiated.

# Answer
> 2 votes
I honestly would have just done a point check. So:

```
if (falling AND left_key_pressed AND !point_free(x-1,y))
    doWallJump

```

You may want to change the y to say y + sprite\_width/2 (or - depending on your coordinate system) so that it checks to the left of the middle your sprite instead of the top (or bottom). This is how N implements wall checks for wall jumping (last paragraph).

After that you must decide on how tight you want your wall jump. If the vertical velocity of your jump overcomes the horizontal before the player is able to reach that same wall again, you will not be able to wall jump up the same wall and will gradually fall back to the bottom (like in Mario games with wall jumping). If you do allow the horizontal to be weak enough for the player to get back to the wall, he/she will be able to progress up the wall (like in Meat Boy).

Another approach not mentioned is Super Metroid's. In that game when you are against a wall, if you move off that wall a very short "moving off wall" animation will play. If you jump during that animation, you will do a wall jump. (Super Metroid also allows a player to climb up a wall using wall jumps, but it requires a bit of skill (in fact everything about wall jumping in Super Metroid requires a fair bit of skill...).)

---
Tags: xna, 2d, c#, platformer
---


# Question
Title: What is a correct step by step logic of exporting scene with baked occlusion for loading it at runtime?
I wonder what is a correct step by step logic of exporting scene with baked occlusion (Culling data) for loading that scene at runtime (on fly from the internet for example))?

So currently my plan looks like this:

* I create prefabs
* Place them onto my scene (into Hierarchy) (say create 20 buffolows and some hourses and some buildings)
* Create empty prefab and drag all my scene objects from hierarchy onto it
* Export prefab

So generally I put all my scene objects into one large prefab and export it but it seems that all objects that were marked as static get this property turned off when loading them at runtime and so no Frustum Culling, and no Occlusion culling happens.

So I wonder what is a correct way of exporting Scene + Objects + Occlusion (and other culing) data for future load of such scene at runtime?

I wonder about current `3.5.2 Pro` and future `4 Pro` versions of U3D.

# Answer
I think the whole point of Static is that it only applies to objects that are placed in the scene and stay there throughout - not ones you load via `Resources.Load()`, for example.
> 1 votes

---
Tags: 3d, unity, scene
---


title: How to handle cutscenes in XNA?

text:
# Question
Title: How to handle cutscenes in XNA?
I am making a 2D RPG in XNA, and I want to be able to have basic cutscenes, kinda like those in the handheld Pokemon games.

What is the easiest way to do this? Sorry for the vagueness of my question, but I'm new to game development, and nothing I've found says how to do this.

# Answer
For in-game cutscenes scripting is usally used.

Take a look at Luainterface. The basic idea is that you expose functionality to Lua, and then use that to create cutscenes.

Here's a super basic sample where the camera moves over to a character, and then starts a script.

### C#

```
lua = ScriptManager.createLua();
this.luafile = luafile;
lua.DoFile("scripts/" + luafile + ".lua");

lua.RegisterFunction("MoveCamera", this, GetType().GetMethod("MoveCamera"));
lua.RegisterFunction("SpawnChat", this, GetType().GetMethod("SpawnChat"));

lua.GetFunction("runScript").call();

```

### Lua

```
function runScript()
{
    --pan camera to x100 and y 100
    MoveCamera(x, y, CameraComplete); --last parameter is an onComplete function
}

function CameraComplete()
{
    SpawnChat("this is our hero ryan, isn't her handsome?");
}

```

Be sure to also check out Godpatterns: Scripting with Lua in C#
> 6 votes

# Answer
An easy way would be to keyframe objects in the scene using a basic keyframe data structure which can then be serialized to file (xml just a few lines of C#) and opened in a custom scene editor or edited by hand.

Replay should be very straight-forward -just deserialize the file and loop through the objects, showing and moving them whenever the keyframe timestamps passes the current cut scene time. Increase the current cut scene time using the game time. This way the cut scene can easily be scrubbed back and fourth, automatically paused and it's very easy to implement various kick-ass interpolation algorithms between keyframes.

```
class CutScene
{
    List<ScriptableObject> Objects;
    TimeSpan SceneLength;
    TimeSpan CurrentPosition;
}

// Anything that should show up, disappear, move or otherwise
// be scripted in the scene, like NPCs, text bubbles, other sprites, camera position
class ScriptableObject
{
    List<Keyframe> Keyframes;
}

class Keyframe
{
    TimeSpan TimeFromSceneStart;
    Vector2 Position;
    int Rotation;
}

```

With such a basic setup, multiple cut scenes could be played back at any time and also made to overlap. There are of course several ways to attach keyframes to in-game objects/classes...
> 1 votes

# Answer
I would create a class with multiple stages the progression to the next stage would dependant on a number of events occurring

```
pseudo code

stage 1:
//NPC1 starts talking

show text dialog();

if(dialogcompleted)
{
 _stage = 2;
}

stage 2:
//NPC1 walks to desk

npc.pos = MathHelper.Lerp(startpos,endpos,time/totaltime)

if(npc.pos = endpos)
{
_stage = 3;
}

etc

```

I have never used Lua so do not know if that option would be better, but this is how i would do it in pure C#.
> 0 votes

# Answer
You could use timing and use your input classes.

Pseudocode:

```
int runTime = 0;
Control.Input = null;
curTime = DateTime.Now;
while( runTime <  5000 ) {
  if( runTime < 1000 ) {
    Control.Target = NpcStore[0];
    Control.Event(KeyPress.Left);
    NpcStore[0].Say("I'm moving");
  }
  if( runTime > 1000 && runTime < 4000 ) {
    NpcStore[0].Say("I stopped!");
  }
  if( runTime > 4000 ) {
    NpcStore[0].Say("Cutscene ends soon.");
  }
  runTime = (DateTime.Now - curTime).MilliSeconds;
}
Control.Target = PlayerCharacter;
Control.Input = Keyboard;

```

If it's a "simple" project without modding capabilities, including a scripting engine is often overkill.
> 0 votes

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


# Question
Title: Blender 2.6: How to Undo 3D Cursor Movement
I sometimes place the 3D cursor at the wrong location by a undesigned click on the left mouse button.

But when I'm trying to click `Control + Z` in order to undo the accidental 3D cursor movement, it doesn't revert.

So **my question** is: Is there an easy way to get Blender's (2.6) 3D cursor back to it's *previous location*? Thanks.

# Answer
> 1 votes
The editing tool state changes (including the cursor) are not placed on the undo stack. That's intended behavior. Some one tried to file a bug about it, not too long ago, and it was closed as intentional behavior.

You can brush up on cursor behavior here.

If you really want to keep the cursor in one place, you can create an object at the position, hide it, then you'll have something to snap-to the position if you ever lose cursor placement.

Additionally, there are plugins that you might like. Specifically for this situation:

Enhanced 3D Cursor

Which provides:

* Cursor location history
* Cursor location bookmarks

Enjoy!

---
Tags: graphics, blender
---


# Question
Title: Cocos2d: Tongue effect like in Munch Time
I'm wanting to do a tongue effect for my character like the one in Munch Time( shown in pic ). The player does some action and his tongue attaches to the nearest platform.

I'm thinking this is simply a get distance to platform and keep player at that distance as he moves back and forth giving him the swinging effect.

For the drawing, I'm wanting the same effect where the tongue sprite is the skinniest in the middle of the distance between the character and platform.

I know how to do this in a shader( I'm using cocos2d v2 btw ), but I'm wondering if there is some built-in functionality to allow me to do this.

First, is this the right approach using distance?

Second, is their an easy way to do the tongue sprite effect without a shader?

Third, I'm wanting to have the player spring up at will in the direction of the platform. I'm using Box2D. Would there be a way to do this using force's or would it be easier to write my own code?

# Answer
> 1 votes
If I were you I wouldn't use a physics engine, take a look at the maths for a pendulum motion:

http://en.wikipedia.org/wiki/Pendulum

It'll give you a much more natural looking swinging motion than just keeping him a certain distance from the platform as you'll be taking into account velocity.

Would it not be easier to draw a shape from the centre of the player to the platform, then bind a texture on that shape (like the texture on the tongue).

If you take the current speed and direction of the player I'm sure you'll be able to make it spring up in the right direction.

---
Tags: box2d, ios, cocos2d
---


# Question
Title: Drawing simple geometric figures with DrawUserPrimitives?
I'm trying to draw a simple triangle based on an array of vertex. I've been searching for a tutorial and I found a simple example on riemers but I couldn't get it to work. I think it was made for XNA 3 and it seems there were some changes to XNA 4?

Using this example:

http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series1/The\_first\_triangle.php

I get this error:

> Additional information: The current vertex declaration does not include all the elements required by the current vertex shader. TextureCoordinate0 is missing.

I'm not english so I'm having some trouble to understand everything.

For what I understand error is confusing because I'm trying to draw a triangle color based and not texture based and it shouldn't need a texture.

Also I saw some articles about dynamic shadows and lights and I would like to know if this is the kind of code used to do it with some tweaks like culling because I'm wondering if its heavy code for performance in real time.

```
    public void LoadContent()
    {
        effect = Game.Content.Load<Effect>("Effect1");
        playerVision = new VertexPositionColor[3];
        playerVision[0].Position = new Vector3(-0.5f, -0.5f, 0f);
        playerVision[0].Color = Color.Red;
        playerVision[1].Position = new Vector3(0, 0.5f, 0f);
        playerVision[1].Color = Color.Green;
        playerVision[2].Position = new Vector3(0.5f, -0.5f, 0f);
        playerVision[2].Color = Color.Yellow;
    }

    // comes from draw method
    private void drawPlayerVision(GameTime gameTime, SpriteBatch spriteBatch)
    {
        effect.CurrentTechnique = effect.Techniques["Pretransformed"];
        Game.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, playerVision, 0, 1, VertexPositionColor.VertexDeclaration);
    }

```

# Answer
Your problem is that effect is not sent into graphics card, you need to do this:

```
effect.CurrentTechnique = effect.Techniques["Pretransformed"];

foreach (EffectPass pass in effect.CurrentTechnique.Passes)
{
    pass.Apply();

    Game.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, playerVision, 0, 1, VertexPositionColor.VertexDeclaration);
}

```

On first line, you must select effect technique (effect file from Riemers have more of them), then send effect to graphics card and finally draw your primitive.
> 2 votes

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


# Question
Title: Understanding how to go from a scene to what's actually rendered to screen in OpenGL?
I want something that explains step by step how, after setting up a simple scene I can go from that 'world' space, to what's finally rendered on my screen (ie, actually implement something). I need the resource to clearly show how to derive and set up both orthographic and perspective projection matrices... basically I want to thoroughly understand what's going on behind the scenes and not plug in random things without knowing what they do.

I've found lots of half explanations, presentation slides, walls of text, etc that aren't really doing much for me. I have a basic understanding of linear algebra/matrix transforms, and a rough idea of what's going on when you go from model space -\> screen, but not enough to actually implement it in code.

# Answer
> 4 votes
It all starts here: thick enough to stun an ox and to steal a meme: "If you don't like a wall of text, you're gonna have a bad time."

Then since you're concerned with OpenGL, a side trip down Route 666 one of the classic OpenGL books

But if you want to short circuit understanding of a complete graphics pipeline and just want to focus on some math for the 3D stuff then maybe something like: just the 3D math bits or some similar book.

After all that you'll want to pore over GLSL references because modern pipelines are mostly shader driven, which should keep you occupied for a while.

# Answer
> 1 votes
I'd like to recommend a book I am currently reading: Real-Time Rendering, by Tomas Akenine-Möller, Eric Haines, and Naty Hoffman.

It has info on both OpenGL, DirectX, the rendering process that happens in the hardware and the architecture of the GPU itself. It's neat, to say the least.

# Answer
> 0 votes
An excellent place to start is the Wikipedia entry for rasterisation. This is the basic theory for going from a point to a screen coordinate.

## General Overview

### What You Need

* Create a list of points which have a position in 3D space (Vertex Buffer)
* Create a list of indices to state how these points are linked together (Index Buffer)
* Create a world matrix for each object so you can change an objects position, scale and orientation without having to recreate the object.
* Create a view matrix for your camera so you can translate a point from world space into the cameras space (keep in mind that moving the camera is just like moving everything in the world in the opposite direction, move the camera up the world moves down).
* Create a projection matrix which details how to translate something from view space into a 2D screen coordinate.

### What you do with it

* Take each point in the vertex list and multiply it by the world, then view and then projection matrix to translate the point from object, to world, to view to screen space. This is done in the vertex shader, although the vertex shader isn't limited to this process alone.
* Use the index buffer to work out the next three points used to make a triangle
* Scane across the screen, row by row, and for each pixel inside these edges run a pixel shader. The pixel shader will dictate how to calculate the color of the pixel and can be used to add lighting and textures.

---
Tags: camera, opengl-es2, projection
---


# Question
Title: Why does the player fall down when in between platforms? Tile based platformer
I've been working on a 2D platformer and have gotten the collision working, except for one tiny problem. My games a tile based platformer and whenever the player is in between two tiles, he falls down. Here is my code, it's fire off using an ENTER\_FRAME event. It's only for collision from the bottom for now.

```
        var i:int;
        var j:int;
        var platform:Platform;
        var playerX:int = player.x/20;
        var playerY:int = player.y/20;
        var xLoopStart:int = (player.x - player.width)/20;
        var yLoopStart:int = (player.y  - player.height)/20;
        var xLoopEnd:int = (player.x + player.width)/20;
        var yLoopEnd:int = (player.y + player.height)/20;
        var vy:Number = player.vy/20;
        var hitDirection:String;
        for(i = yLoopStart; i <= yLoopEnd; i++)
        {
            for(j = xLoopStart; j <= xLoopStart; j++)
            {
                if(platforms[i*36 + j] != null && platforms[i*36 + j] != 0)
                {
                    platform = platforms[i*36 + j];
                    if(player.hitTestObject(platform) && i >= playerY)
                    {
                        hitDirection = "bottom";
                    }
                }
            }
        }

```

This isn't the final version, going to replace hitTest with something more reliable , but this is an interesting problem and I'd like to know whats happening. Is my code just slow? Would firing off the code with a TIMER event fix it? Any information would be great.

# Answer
The initialiser and loop condition are both using xLoopStart

```
for(j = xLoopStart; j <= xLoopStart; j++)

```

Should be xLoopEnd for second parameter

```
for(j = xLoopStart; j <= xLoopEnd; j++)

```
> 2 votes

---
Tags: collision-detection, tiles, actionscript-3, flash-cs5
---


# Question
Title: A star algorithm implementation problems
I’m having some trouble implementing the A\* algorithm in a 2D tile based game.

The problem is basically that the algorithm gets stuck when something gets in its direct way (e.g. walls) Note that it only allows Horizontal and Vertical movement.

Here's a picture as it works fine across the map without something in its direct way: (Green tile = destination, Blue = In closed list, Green = in open list)

This is what happens if I try to walk 'around' a wall:

---

**EDIT**

Thanks DeadMG, I rewrote the algorithm last week and got it somewhat working.

But the heuristics are still some faulty.

As you can see here it prefers a uneven path on an straight way:

The heuristics function:

```
float c_astar::GetH(cTILEext TILEX)
{
    short a = 0; short b = 0;
    if(TILEX.Tile.Position.x > Destination.x) a = TILEX.Tile.Position.x - Destination.x;
    else a = Destination.x - TILEX.Tile.Position.x;
    if(TILEX.Tile.Position.y > Destination.y) b = TILEX.Tile.Position.y - Destination.y;
    else b = Destination.y - TILEX.Tile.Position.y;

    float h = a+b;

    //Tie-Breaker
    float dx1,dy1,dx2,dy2;
    dx1=dy1=dx2=dy2 = 0;

    if(TILEX.Tile.Position.x > Destination.x) dx1 = TILEX.Tile.Position.x - Destination.x;
    else dx1 = Destination.x - TILEX.Tile.Position.x;

    if(TILEX.Tile.Position.y > Destination.y) dy1 = TILEX.Tile.Position.y - Destination.y;
    else dy1 = Destination.y - TILEX.Tile.Position.y;

    if(Start.x > Destination.x) dx2 = Start.x - Destination.x;
    else dx2 = Destination.x - Start.x;

    if(Start.y > Destination.y) dy2 = Start.y - Destination.y;
    else dy2 = Destination.y - Start.y;
    float cross = abs(dx1*dy2 - dx2*dy1);

    h += cross*0.001;

    return h;
}

```

I used the Tie-Breaker as described here. What am I doing wrong?

Regards, bryan226

# Answer
> 4 votes
> Its always going after the cheapest F value, which seems to be wrong.

Is the *entire point of F*. Your heuristic is crackers. You should use something like Manhattan distance to target (ignoring obstacles) as the value of heuristic, (yours is pretty close but you need to ditch the \*10) and then 1 cost/step for G. Also, your G estimate does not actually give the length of the path, because it does not include the idea that you had to take a detour, giving you quite inaccurate results.

Fixing these two problems should give you actual results for A\*.

---
Tags: c++, path-finding
---


# Question
Title: How can I store all my level data in a single file instead of spread out over many files?
I am currently generating my level data, and saving to disk to ensure that any modifications done to the level are saved.

I am storing "chunks" of 2048x2048 pixels into a file. Whenever the player moves over a section that doesn't have a file associated with the position, a new file is created.

This works great, and is very fast. My issue, is that as you are playing the file count gets larger and larger.

I'm wondering what are techniques that can be used to alleviate the file count, without taking a performance hit. I am interested in how you would store/seek/update this data in a single file instead of multiple files efficiently.

# Answer
> 7 votes
The fastest way to do this is store everything in one file and jump the cursor to the chunk you want to read. Once you hit the disk reading a sequence from that his point is pretty fast.

The multiple hits to different INodes to find the location of the file on the physical volume its whats taking most of the time and also what scales poorly.

Also, since this is dynamic, you're also going to need a map that stores the offset in the file for each chunk.

**On Disk**

```
[Chunk 1][Chunk 2][Chunk 3][Chunk 4][Chunk 5][Chunk 6][Chunk 7][Chunk 8][Chunk 9]

```

**Visible**

```
[7][8][9]
[6][1][2]
[5][4][3]

```

Then you just need to open a stream that reads from the file but doesn't lock other streams/processes from accessing it. Then you need to read from the correct offset for the correct distance. I believe in C# it's the below.

```
var chunk = new byte[4194304];
using (var file = new FileStream (openFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    using (var reader = new StreamReader (file, Encoding.Unicode)) {
        reader.Read(chunk, offset * 4194304, 4194304);
    }
}

```

Now because of the fact that you opened the stream in readonly mode and allow others to Read/Write to it you can keep adding new chunks to the end. Just keep track of their offset number and don't try to read them before they are there.

P.S. you are not going to want to use the using block since you are going to want only 1 reading stream through the life of what ever level you are using. Also you'll probably have to save the chunk mapping to another file on exit but that is just one load when you load your level.

# Answer
> 1 votes
Depending on the time required to generate a chunk, you could just store diffs or a current state (enemy locations, etc). As the player moves back into a chunk, it generates again using a stored seed, then loads any changes that were made from the file.

If players are allowed to make significant changes, this might be slow and the diff file will still be fairly large, but for only small changes, should be an inexpensive operation. Multiple chunk diffs could be consolidated into a single file as well - something sized reasonably that could be loaded into memory.

You probably wouldn't want to move all the diffs into a single file though - that opens up a number of other issues with memory, or changing the middle of the file.

# Answer
> 1 votes
I know this is a pretty old thread - but I'd just like to chime in that I think a ZIP archive might be the best way to go here. You get compression with your data (if you're using raw bitmaps, especially), readability in the operating system, and you get the single file as you wanted.

# Answer
> 0 votes
What about a dir scan to check the time-stamp of the files in the level data directory vs the current active file and giving a grace of the previous file and the file going forward every 10 seconds or so, and whatever isn't being used just delete them.

Unless you require the player to go back. Then just cleanup the level data upon level completion or checkpoint? Could get large for sure, but I don't think there are many options available here

# Answer
> 0 votes
How about multiple chunks per file? You say your chunks are 2048 x 2048, how about putting 16384 x 16384 in a file. Flag which ones exist somehow so you know whether you need to create it.

# Answer
> 0 votes
If you can generate the chunks fast enough as the player explores anyway, then you don't need to cache them on disk at all; all you need to do is store the seed for the perlin noise functions you are using to generate your procedural content again on demand.

These can be stored in a single file, and can be written sequentially and sorted in RAM when loaded; there's no need for a complicated sorted structure in the file itself on disk. You can be reading from it only on startup, and writing to it as you generate new 'pages' (as they are termed) in the game-world.

---
Tags: xna, c#, level-design, data-structure
---


title: How do I do JavaScript Array Animation

text:
# Question
Title: How do I do JavaScript Array Animation
I'm making a game but don't know how to do Array Animation with the png Array and game Surface that I made below. I'm trying to make it so that when the Right arrow key is pressed, the character animates as if it is walking to the right and when the Left arrow key is pressed it animates as if it is walking to the left (kind of like Mario). I put everything on a surface instead of the canvas. Everything is explained in the code below. I couldn't find help on this anywhere. I hope what I got below makes sense. I'm basically a beginner with JavaScript. I'll be back if more is needed:

```
   <!doctype html5>

     <html>

    <head></head>
    <script src="graphics.js"></script>
    <script src="object.js"></script>

    <body onkeydown ="keyDown(event)" onkeyup ="keyUp(event)" ></body>

    <script>

    //"Surface" is where I want to display my animation. It's like the HTML
     // canvas but it's not that. It's just the surface to where everything in the
     //game and the game itself will be displayed.

    var Surface = new Graphics(600, 400, "skyblue");

    //here's the array that I want to use for animation

var player = new Array("StandsRight.png", "WalksRight.png", "StandsLeft.png","WalksLeft.png" );

 //Here is the X coordinate, Y coordinate, the beginning png for the animation,
 //and the object's name "player." I also turned the array into an object (but
 //I don't know if I was supposed to do that or not).

 var player = new Object(50, 100, 40, 115, "StandsRight.png","player");

//When doing animation I know that it requires a "loop", but I don't
// know how to connect it so that it works with the arrays so that
//it could animate.

    var loop = 0;

//this actually puts "player" on screen. It makes player visible and
//it is where I would like the animation to occur.

 Surface.drawObject(player);

//this would be the key that makes "player" animation in the righward direction
function keyDown(e) {

if (e.keyCode == 39);

 }

//this would be the key that makes "player" animation in the leftward direction
function keyUp(e){

if (e.keyCode == 39);

 }

 //this is the Mainloop where the game will function
 MainLoop();

 //the mainloop functionized
 function MainLoop(){

 //this is how fast or slow I could want the entire game to go
 setTimeout(MainLoop, 10);

   }

 </script>

  </html>

```

---

From here, are the "graphic.js" and the "object.js" files below. In this section is the graphics.js file. This graphics.js part below is linked to the: script src="graphics.js"\> html script section that I wrote above. Basically, below is a seperate file that I used for Graphics, and to run the code above, make this graphics.js code that I post below here, a separate filed called: graphics.js

```
function Graphics(w,h,c) {

   document.body.innerHTML += "<table style='position:absolute;font-
   size:0;top:0;left:0;border-spacing:0;border-
    width:0;width:"+w+";height:"+h+";background-color:"+c+";' border=1><tr><td>

    </table>\n";

  this.drawRectangle = function(x,y,w,h,c,n) {
  document.body.innerHTML += "<div style='position:absolute;font-size:0;left:" + x +
  ";top:" + y + ";width:" + w + ";height:" + h + ";background-color:" + c + ";' id='"
   + n + "'></div>\n";
     }

   this.drawTexture = function(x,y,w,h,t,n) {
  document.body.innerHTML += "<img style='position:absolute;font-size:0;left:" + x +
  ";top:" + y + ";width:" + w + ";height:" + h + ";' id='" + n + "' src='" + t + "'>
   </img>\n";
    }

   this.drawObject = function(o) {

    document.body.innerHTML += "<img style='position:absolute;font-size:0;left:" +
    o.X + ";top:" + o.Y + ";width:" + o.Width + ";height:" + o.Height + ";' id='" +
    o.Name + "' src='" + o.Sprite + "'></img>\n";
     }

    this.moveGraphic = function(x,y,n) {

    document.getElementById(n).style.left = x;
     document.getElementById(n).style.top = y;
      }

     this.removeGraphic = function(n){
     document.getElementById(n).parentNode.removeChild(document.getElementById(n));
      }

     }

```

Finally, is the object.js file linked to the script src="object.js"\>" in the html game file above the graphics.js part I just wrote. Basically, this is a separate file too, so thus, in order to run or test the html game code in the very first section I wrote, a person has to also make this code below a separate file called: object.js

I hope this helps:

```
  function Object(x,y,w,h,t,n) {
  this.X = x;
  this.Y = y;
  this.Velocity_X = 0;
  this.Velocity_Y = 0;
  this.Previous_X = 0;
  this.Previous_Y = 0;
  this.Width = w;
  this.Height = h;
  this.Sprite = t;
  this.Name = n;
  this.Exists = true;
                              }

```

In all, this game is made based on a tutorial on youtube at: http://www.youtube.com/watch?v=t2kUzgFM4lY&feature=relmfu

I'm just trying to learn how to add animations with it now. I hope the above helps. If not, let me know. Thanks

# Answer
> 1 votes
**Edit:** Don't do that "`Object`" thing! "`Object`" is the base constructor function for every object in Javascript! And you're overwriting it!

```
x = new Object(); //Is the same as
y = {}; //this.

```

You're going to mess things up if you overwrite `Object`. Find a new name, like simply "`Player`". Then, do `player = new Player(arguments)`. I'm not saying that `Object` gets executed each time you make an object, nor that the function actually does something important, but it's a generally bad idea to do things like these.

---

As I've said in the comment, your code makes little sense. What does the `object.js` file do? Anyway, here's your code, but with a bit of `sense` put into. I say "bit", because I still don't know how you are handling images or what `new Object()` does (or even better, what you **think** it does).

```
    <script>
        //For rendering (drawing), use window.requestAnimationFrame(nameOfRenderFunction). It's simple to setTimeout, only you don't need to worry about FPS, as the browser will do various optimizations for you.

        //You can ignore this. It just fixes the fact that different browser engines have different names for this function.
        window.requestAnimationFrame = (function(){
          return  window.requestAnimationFrame       ||
                  window.webkitRequestAnimationFrame ||
                  window.mozRequestAnimationFrame    ||
                  window.oRequestAnimationFrame      ||
                  window.msRequestAnimationFrame     ||
                  function( callback ){
                    window.setTimeout(callback, 1000 / 60);
                  };
        })();

        //This happens when ANY key on the keyboard is pressed.
        function keyDown(e)
        {
            //If the key is the right arrow
            if (e.keyCode == 39);
            {
                player.image = playerImages[1]; //This doesn't do any animation, though.
            }
        }

        function mainLoop() //Function names start with a lowercase letter.
        {
            timePassed = new Date().getTime() - timePassed; //new Date().getTime() returns the current time in milliseconds.

            //Do logic. (Check if key is pressed, then move the player accordingly by playerSpeed*timePassed, for example).
        }

        function render()
        {
            if (rendering)
            {
                window.requestAnimationFrame(render);
            }

            Surface.drawObject(player);
        }

        //This gets called once the page loads. It's a useful technique.
        var init = function()
        {
            //If you declare variables without the var prefix, they become global (which means that you can use them in any function).
            Surface = new Graphics(600, 400, "skyblue");

            playerImages = ["StandsRight.png", "WalksRight.png", "StandsLeft.png","WalksLeft.png"]; //These are only the sources, you'll want to load the images and put them here.
            player = new Object(50, 100, 40, 115, "StandsRight.png","player"); //I'm not sure what is this supposed to do... Object is a built-in Javascript "class", this doesn't do anything. But I guess that's changed in you "object.js" file, but you should definetivly avoid this.

            //It's good to separate logic from rendering.
            var LPS = 30; //Logic per second.

            setInterval(mainLoop, 1000/LPS);

            rendering = true; //Set to false when you want to stop rendering.
            window.requestAnimationFrame(render);
        }
    </script>
</head>

<body onload="init();" onkeydown ="keyDown(event);" onkeyup ="keyUp(event);">
</body>

```

If you want, I can write this through, completely. For that, I will use my Loader.js utility, which I recommend you use as well. I assure you that this code will not work, because you're working with *strings*, not *image objects*.

---
Tags: javascript
---