title: SDL Parallax Scrolling along two axis

text:
# Question
Title: SDL Parallax Scrolling along two axis
I'm trying to implement Parallax scrolling in two dimensions using SDL, but I've run into an issue using `SDL_BlitSurface()` to blit my layer images to the screen buffer. The images I'm using for this are borrowed from http://en.wikipedia.org/wiki/Parallax\_scrolling, and I was able to get it working fine just scrolling along the X axis, using the following code:

```
void Parallax::Draw(SDL_Surface* buffer) {

    //draw each layer starting with the bottom
    std::vector<ParallaxLayer*>::iterator it;

    for(it=layers.begin(); it != layers.end(); it++){

        ParallaxLayer* layer = (*it);
        layer->x_offset %= buffer->w;
        int draw_x = layer->x_offset - layer->image->w;

        SDL_Rect blitrect = buffer->clip_rect;

        while(draw_x <= buffer->w) {
            blitrect.x = draw_x;
            SDL_BlitSurface(layer->image, &(layer->image->clip_rect), buffer, &blitrect);
            draw_x += layer->image->w;
        }
    }
}

```

*This works.*

Now, I've tried to adapt this into two dimensions. Here's the draw method I'm using now:

```
void Parallax::Draw(SDL_Surface* buffer) {

    //draw each layer starting with the bottom
    std::vector<ParallaxLayer*>::iterator it;

    for(it=layers.begin(); it != layers.end(); it++){

        ParallaxLayer* layer = (*it);

        //resize offset so as not to overflow ints or whatever
        layer->x_offset %= buffer->w;
        layer->y_offset %= buffer->h;

        int draw_x = layer->x_offset - layer->image->w;
        int draw_y = layer->y_offset - layer->image->h;

        SDL_Rect blitrect = buffer->clip_rect;

        while(draw_x <= buffer->w && draw_y <= buffer->h) {

            blitrect.x = draw_x;
            blitrect.y = draw_y;

            SDL_BlitSurface(layer->image, &(layer->image->clip_rect), buffer, &blitrect);

            if(draw_x <= buffer->w)
                draw_x += layer->image->w;
            if(draw_y <= buffer->h)
                draw_y += layer->image->h;
        }
    }
}

```

I've added the logic for blitting a layer that's moving in the vertical axis, but when I tested it, this just doesn't play nice. Areas of the screen end up not being blitted, which causes a lovely un-drawn effect:

Link to image as I can't post them directly (new user): SDL blitting bug example

Just to be clear, the images themselves are pushed around in another method. The front two layers are moving along the horizontal axis with varying velocity, and the background is moving vertically with a fixed velocity and horizontal with a variable velocity, but that's largely irrelevant as it's my blit function which is bugged.

It looks like I'm not re-drawing the area of the screen that has the repeating image on it, but I'm lost as to how to go about this.

# Answer
> 1 votes
The code example I was working from was fine for scrolling in one dimension, but in two dimensions it does not tile the image to cover the whole screen. This was producing the artifacts seen in the linked image. So once I thought about it and really understood what that code actually does, I was 75% nearer to figuring out a solution.

To render properly, the image must be tiled as many times as nescessary to cover the screen size. *Programming Linux Games*, by John R. Hall, gives a similar example on pages 143-147, which I was able to adapt to solve the problem. The final method is as follows:

```
void Parallax::Draw(SDL_Surface* buffer) {

    int start_x, start_y = NULL;
    int draw_x, draw_y = NULL;

    std::vector<ParallaxLayer*>::iterator it;

    //draw each layer starting with the bottom
    for(it=layers.begin(); it != layers.end(); it++) {

        ParallaxLayer* layer = (*it);

        //resize offset so as not to overflow ints or whatever
        layer->x_offset %= layer->image->w;
        layer->y_offset %= layer->image->h;

        // start_x, start_y - initial position of rectangle to tile.
        start_x = layer->x_offset - layer->image->w;
        start_y = layer->y_offset - layer->image->h;

        SDL_Rect blitrect = buffer->clip_rect;

        // Use nested loops to scan down the screen, drawing rows of tiles:
        draw_y = start_y;
        while(draw_y <= buffer->h) {

            draw_x = start_x;
            while(draw_x <= buffer->w) {

                SDL_Rect destrect;

                blitrect.x = draw_x;
                blitrect.y = draw_y;

                SDL_BlitSurface(layer->image, &(layer->image->clip_rect), buffer, &blitrect);

                draw_x += layer->image->w;
            }

            draw_y += layer->image->h;
        }
    }
}

```

The inner while loops in this example iterate while the image is inside the screen, and cover the entire surface with blitted images of each layer.

The only real optimisation I made over the version in the book was to use `->clip_rect` to retrieve the drawable portion of the image, as seen in the original 1d method used.

Again, just thinking about the problem was the solution... ;)

---
Tags: c++, sdl
---


# Question
Title: How to properly simulate object aproximation towards camera in 2D?
I'm trying to make some objects come towards the camera but it just doesn't feel right... you can check the progress here:

http://testing.fyrastudio.com/lab/tweetOlympics/v0.005/

You run by repeateadly hitting the letter Q, and around position 700 the first hurdle appears. But it just doesn't look right. I think that on real life, the hurdle would go slower when it's further away, and when it's closer to the camera, it would go real fast... and now it's doing it the other way around...

Here's the code handling the hurdle movement:

```
hurdle.scaleX = hurdle.scaleY = (athlete.position - hurdle.position_initial) / 1000;
hurdle.y = bg.image.y + (athlete.position - hurdle.position_initial) * 0.4;

```

Any ideas?? Thanks!!

# Answer
> 1 votes
What you're trying to do is perspective projection. In the simplest terms, converting a `(x, y, z)` world point to an `(x, y)` screen point involves dividing it by `z`. In your case, you should divide your **scale** by `z`, where `z` is the distance between the athlete and the hurdle:

```
var z:Number = athlete.position - hurdle.position_initial;

```

So, your scaling code should be something like:

```
hurdle.scaleX = hurdle.scaleY = HURDLE_WIDTH / z;

```

As for the `y` coordinate, it should follow the same (inverse) progression, so you'll be dividing by `z` as well:

```
hurdle.y = bg.image.y + (bg.image.height / 2) / z;

```

Explanation:

* When the athlete is *infinitely* far from the hurdle (`z` tends towards infinity),the hurdle will be rendered at the center of the screen (`bg.image.y` = `bg.image.y`) scaled by zero.
* When they are at the same position (`z` equals zero), it will be rendered at the base of the screen (`(bg.image.y + (bg.image.height / 2)`) scaled by `HURDLE_WIDTH`.

I'm not sure if that's exactly what you needed to do, but you can adjust the formula based on the hurdle's dimensions and center.

---
Tags: 2d, physics, algorithm, animation
---


# Question
Title: How to deal with variable size font in XNA 4.0
After searching for a while, I found no way to draw vector/scalable fonts in XNA 4.0 (which would be perfect...) and I am currently in a bind about how to render fonts for my game.
In the game I use fonts of variable size, ranging from very small to quite large, and I have no idea how to efficiently deal with this.

The only way I can currently accomplish what I want is to load a large number of SpriteFonts different sizes, manually pick the font closest to the size I want, and then fine-tune the size with a scale close to 1. (A scale too large or too small will make the font look horrible.) I've also started using the Nuclex font processor which makes the fonts looks somewhat better, but it's obviously not the answer to my problem.

**Is there really no other way to deal with this?**
It seems very strange to me that something as elaborate and well done as XNA 4.0 has such a profound lack of tools to deal with font rendering.

This is quite a big problem for me currently, so any help and ideas on possible ways to deal with this or even to ease the pain are very welcome.

# Answer
> 3 votes
This is not an easy problem to solve. If the "multiple sprite fonts" technique doesn't work for you, there's no other built-in way in XNA to get what you want. So you have to do some custom development.

One method is to use Valve's technique, as described in the paper: Improved Alpha-Tested Magniﬁcation for Vector Textures and Special Effects. This involves specially encoded textures and a special pixel shader. I've implemented this before and it's not too difficult. The results are reasonable, although not perfect.

Another method that is worth considering is to offload font rendering to Windows (rendering fonts to a texture - just like the content pipeline does to produce bitmap fonts). This has the added benefit of allowing you to use any character from your font, rather than only what you have available in the bitmap font. If you render entire strings at once, you'll get reasonable performance and this will solve many internationalisation issues that sprite fonts have.

Another method is to simply use vector fonts (at least above a certain size threshold). This is probably the easiest to get working - on the basis that you could just use Nuclex.Fonts.

Finally, this post might be worth reading for some additional ideas.

# Answer
> 0 votes
`public void DrawString (
 SpriteFont spriteFont,
 string text,
 Vector2 position,
 Color color,
 float rotation,
 Vector2 origin,
 Vector2 scale,
 SpriteEffects effects,
 float layerDepth
)`

Unless I'm missing something, there is a scale overload on DrawString.

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


title: Question about timing in XNA

text:
# Question
Title: Question about timing in XNA
I'm looking for a simple way to display minutes, seconds and milli seconds for timing the elapsed time in a game. Do I have to do the calculation myself with gameTime and display a variable for each part like a variable for minutes, secounds and milli seconds? Preciates some help! Thanks!

# Answer
You can already get all these three from GameTime: `gameTime.TotalGameTime` offers Minutes, Seconds and Milliseconds for units to measure how long the game has been going for.

```
int milliseconds = gameTime.TotalGameTime.Milliseconds;
int seconds = gameTime.TotalGameTime.Seconds;
etc

```

If you just want the time since the last update, use `gameTime.ElapsedGameTime`.
> 5 votes

---
Tags: xna
---


title: Hover Craft Algorithm

text:
# Question
Title: Hover Craft Algorithm
I have a hover craft and I would like to implement it but I don't know what the algorithm or equation of how the physics work is. The variables I think would be the falling speed, the aircraft position and the distance from the ground. Based on that I need it to return the velocity. What makes it so hard is that it needs to work regardless of the situation like falling off a big cliff. Lets say it falls from a very high altitude. Once the craft is at a certain position from the ground the jets should gradually bring the craft down to speed and shoot it up from the ground a little depending on the height. Here is a picture illustrating what I'm talking about.

Could I get some help on what the algorithm would be determining the hover craft's vertical velocity?

Thanks.

# Answer
> 20 votes
Use physics. First you'll need to establish this:

**1. Hovercraft physics principles**

The hovercraft's engines will produce an upwards force of magnitude `F`, that is opposite in direction to the gravitational force `G`. The vertical component of the sum of all forces acting on the hovercraft at any given time will be:

```
sum_of_forces.y = G - F

```

The First Law of Newton says that force equals mass times acceleration. If the hovercraft's mass is `m` and the gravitational acceleration is 9.8 \[m/s2\], then `G = 9.8 * m`. As for `F`, its acceleration will be variable, so we'll call it `f`. Therefore, `F = f * m`. Replacing `G` and `F` in the equation above, we have:

```
sum_of_forces.y = 9.8 * m - f * m;
sum_of_forces.y = (9.8 - f) * m;

```

All you care about is the acceleration, which we'll name `a`:

```
a.y = sum_of_forces.y / m
a.y = 9.8 - f

```

The value of `a.y` should be recalculated every time `f` changes, or to make things simpler, it should be recalculated on every frame.

The `y` component of the hovercraft's velocity will be called `v.y`. Speed changes based on acceleration, and since you're recalculating the acceleration on every frame, you'll do the same with the velocity:

```
v.y = v.y + a.y;

```

And consequently the position. But you probably knew that already:

```
y = y + v.y;

```

**2. Accelerating based on distance to the ground**

Now let's get to the fun part. The hovercraft's vertical acceleration must vary according to its distance from the ground, right? So if `h` is the distance from the hovercraft to the ground, both `F` (the upwards force opposed to gravity) and `f` (the upwards acceleration) are **functions** of it. Therefore, our previous equation `F = f * m` is now:

```
F (h) = f (h) * m

```

In order to keep the hovercraft floating at a constant height `IDEAL_HEIGHT` from the ground, `F` must be **equal or greater** to the magnitude of the gravitational force. Therefore, this must be true:

```
F (IDEAL_HEIGHT) = 9.8 * m

```

and since `F = f * m`, this must be true:

```
f (IDEAL_HEIGHT) = 9.8

```

As the hovercraft nears the ground, `f` should increase. But to be realistic, we'll want to cap `f` at a maximum value of `f_max`. And as the hovercraft gets farther away from the ground, it should push less. With that in mind, `f(h)` must fulfill these two conditions:

```
f (0)                = f_max;
f (IDEAL_HEIGHT)     = 9.8;
f (h > IDEAL_HEIGHT) < 9.8;

```

The simplest possible solution here is to make `f (h)` a **linear function** of the form:

```
f (h) = m * h + b

```

To find the `m` and `b` factors, we do:

```
m = (9.8 - f_max) / (IDEAL_HEIGHT - 0) = (9.8 - f_max) / IDEAL_HEIGHT
b = f (0) = f_max

```

Therefore `f(h)` looks like this:

```
f (h) = h * (9.8 - f_max) / IDEAL_HEIGHT + f_max

```

In pseudocode:

```
function f ( h ) {
    return max ( 0, h * (9.8 - f_max) / IDEAL_HEIGHT + f_max );
}

```

(Note that I'm using the `max()` function to prevent `f` from becoming negative.)

**3. Putting it all together**

So to put it simply, you should just do this on every frame:

```
// calculate the distance from the hovercraft to the ground
h = hovercraft.y - ground.y;

// calculate the acceleration
a.y = (9.8 - f(h)) * m; // see definition of f() above

// calculate the speed
v.y = v.y + a.y;

// and the position
y = y + v.y;

```

---
Tags: algorithm, movement
---


title: Xna winform scaling and mouse position

text:
# Question
Title: Xna winform scaling and mouse position
I am attempting to create a simple 2d level editor using xna and winforms.

I have used the app hub win form samples as a starting point. At first I was having trouble with the mouse coordinates but after setting the mouse handle to the control, it is working fine.

But now I want to implement scaling into the editor. I want the level editor to always be 720p. I have accomplished this by rendering to a render target set to 720 and then draw this using sprite batch to the back buffer. This also works great with letter boxing to keep the right ratio. I used the technique detailed here https://stackoverflow.com/questions/7591466/xna-resize-window-without-increasing-resolution.

However because of the letting boxing my mouse coordinates are now wrong again. Can someone help work out how to solve this? I tried getting the size of the letter box and subtracting that from the mouse coordinates but that didn't work.

Has anyone got any suggestions?

# Answer
This is almost exactly the same method I implemented for my games, and the way I'm solving this problem is by encapsulating both the offset and the scaling in a matrix. I added this method to my resolution independence class:

```
public Matrix GetResolutionMatrix()
{
    float ratio = (float) virtualWidth / physicalWidth;
    return Matrix.CreateTranslation(-area.X, -area.Y, 0) *
           Matrix.CreateScale(ratio, ratio, 1f);
}

```

And I use that matrix to calculate the mouse position inside my input manager, by doing something like:

```
Vector2.Transform(mousePosition, resolution.GetResolutionMatrix())

```

For comparison here's my complete implementation:

http://pastie.org/4265585

And the relevant portion of the input module:

http://pastie.org/4265592

Also, check this answer in case you're having trouble getting the correct "raw" mouse position in relation to the xna control.
> 1 votes

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


# Question
Title: Roughly how many rigid bodies can I expect to have interacting in Bullet?
On my Phenom II desktop machine (about 3 years old) with 8GB of RAM, it seems that I can only throw around a hundred or two boxes before it starts to go slow. I'm using the built-in `DbvtBroadphase`.

Is this about right, or am I missing something?

One thing that can't possibly be right though is that it takes several minutes to delete all the bodies (the RigidBodies, to be exact), spending nearly all of its time in `HeapFree`.

By the way I'm using BulletSharp, but I'm only making one call to the native API each frame -- which suggests that it's not the fault of the wrapper that it's so slow, unless there's something really weird going on with it.

Edit: It seems that there's a threshold point after which the program's memory consumption just starts skyrocketing. Something's leaking. Still, I'd be interested to know what to expect in a normal situation.

# Answer
Look at the benchmark demo in the bullet installation folder: `bullet/Demos/Benchmarks`. I just checked benchmark 4, it creates 960 bodies and collides them, you can adjust the numbers in the demo of course. All timings and statistics are rendered on the screen in the demo, answering all your questions.

Just run a quick test using that demo on my machine: **400 bodies** colliding with less than **6ms per simulation call**, change this function in BenchmarkDemo.cpp to get 400 bodies:

```
void    BenchmarkDemo::createTest4()
{
    setCameraDistance(btScalar(50.));

    int size = 8;
    const float cubeSize = 1.5f;
    float spacing = cubeSize;
    btVector3 pos(0.0f, cubeSize * 2, 0.0f);
    float offset = -size * (cubeSize * 2.0f + spacing) * 0.5f;

    btConvexHullShape* convexHullShape = new btConvexHullShape();

    btScalar scaling(1);

    convexHullShape->setLocalScaling(btVector3(scaling,scaling,scaling));

    for (int i=0;i<TaruVtxCount;i++)
    {
        btVector3 vtx(TaruVtx[i*3],TaruVtx[i*3+1],TaruVtx[i*3+2]);
        convexHullShape->addPoint(vtx*btScalar(1./scaling));
    }

    //this will enable polyhedral contact clipping, better quality, slightly slower
    //convexHullShape->initializePolyhedralFeatures();

    btTransform trans;
    trans.setIdentity();

    float mass = 1.f;
    btVector3 localInertia(0,0,0);
    convexHullShape->calculateLocalInertia(mass,localInertia);
    int counter = 0;
    for(int k=0;k<25;k++) {
        for(int j=0;j<2;j++) {
            pos[2] = offset + (float)j * (cubeSize * 2.0f + spacing);
            for(int i=0;i<size;i++) {
                pos[0] = offset + (float)i * (cubeSize * 2.0f + spacing);
                trans.setOrigin(pos);
                localCreateRigidBody(mass,trans,convexHullShape);
                ++counter;
            }
        }
        offset -= 0.05f * spacing * (size-1);
        spacing *= 1.01f;
        pos[1] += (cubeSize * 2.0f + spacing);
    }
}

```
> 1 votes

---
Tags: bullet-physics
---


# Question
Title: How can I develop a Lights Out solving algorithm?
I am programming the game that named Lights Out. The purpose of this game is turning all the lights out. There's a flash version of the game here. I want to develop a way of solving the game. How can I do this?

# Answer
> 1 votes
You can use a tree. There are lots of ways to employ these and you will need to think carefully about which method will work best for your particular game - so some research should be done first.

To give a basic overview.

Start with the root node which will be your level's starting state. Create a branch for every possible action that can be performed at that point and have the node be the new game state after that action is performed. Repeat this for each node that's created.

Then what you need to do is find a node (which you can be looking for while building the tree) in which the game state is the level completed. Then walk back up the tree to the root node to get a list of actions that need to be performed to get to this "complete" state.

This may not be the best solution to your particular problem but it might steer you towards a solution. You might want to look into decision trees and path finding techniques for general interest, but also the reading might give you some ideas.

---
Tags: algorithm
---


title: How to begin stylising a game

text:
# Question
Title: How to begin stylising a game
I'm currently in the late stages of development for a platform-esque iPhone game and am beginning to look into the graphics. Being a developer through-and-through, I have limited design skills and my budget can't stretch too far to pay a designer to build all the assets.

I've noticed a few games recently that are heavily styled which helps with the look of the game (consistency etc...) and keep the graphics required down to a minimum. The best example of this I can find is the iOS game "Contre Jour".

So, I'm wondering how I can go about a) picking & designing a style that will work with the game and b) implementing it within the Cocos2d environment.

Thanks, Andy

# Answer
> 3 votes
If you are a developer "through and through" reconsider hiring an artist, and don't be afraid to look in non-traditional places.

I know when it comes time for me to throw away the place holder graphics and get more serious, I will be going to the Art Departments of colleges in my area. I know a few Art Students who would love to help with the design of a video game, and build their portfolio at the same time.

Also, talk with a Graphic Design Teacher. They might use your game as a project for their students. You get art, the students build portfolios, and the professor gets a final exam.

---
Tags: graphics, cocos2d-iphone, assets
---


# Question
Title: Html5 games, what is the standard dimension to use?
I am trying to make html5 games to be played on the browser(not offline apps), and I am trying to support the maximum number of platforms, hence I need to know what dimension should I use for the game canvas so that it works in the most number of places.

Also is there anyway to "scale" a large game to fit in the tiny size of iphone(around 320x356px I think). By "scale" I don't mean to actually resize just the canvas, as because that can mess up the coordinate based calculations, and for a large number of objects, re-positioning based on canvas size can be a real hassle.

# Answer
> 4 votes
Google collects data on the average size of the browser window people use when visiting their website:

http://browsersize.googlelabs.com/

As you can see 98% of the people browsing have a window size of at least 800x400 so I suppose that is a good start. Of course if you think your game will be played mostly on phones the statistics may be slightly different since these statistics are desktop+mobile.

# Answer
> 1 votes
I think this question cannot be answered with a number for the and for the height. There are just too much different display formats. I think that the discussion of the games dimensions should be based on the game. What I mean is: Tetris in landscape format might not be that cool as in portrait. I prefer setting an fix aspect ratio, which always can be scaled safely into the available space.

# Answer
> 0 votes
iPhones (and most smartphones I believe) automatically scale web pages to fit the width of the device, thus you can actually make your game in a different scale and as long as the page isn't too tall relative to its width it will automatically fit on the screen.

As far as I have quickly read you can also use a viewport tag to get more precise control of this process. It's not something I have experience with, but it seems worth looking into.

# Answer
> 0 votes
check this awesome tutorial for scaling:

http://www.html5rocks.com/en/tutorials/casestudies/gopherwoord-studios-resizing-html5-games/

EDIT: an idea for object placement and scaling, not sure if its correct / practically doable. I am yet to try this:

* have some base dimension like (960 x 640)
* while writing game logic, handle positions / scale as if you are developing only for 960x640.
* at the time of rendering, multiply the position and scales with these factors `screenWidth / 960` for x-axis and `screenHeight / 640` for y-axis, where `screenWidth` and `screenHeight` are actual screen dimenstions.

# Answer
> 0 votes
i used ImpactJS, a game engine that automatically resizes a game to a required dimension, taking into account retina displays from the iPhone4. The coordinate systems are not screwed this way.

---
Tags: html5
---


# Question
Title: Separation of axis theorem implementation
I have been following the this guide to implement this. My current implementation is the following:

```
class SAT {

  SAT();

  bool collides(Rectangle rect1, Rectangle rect2){
    var axises = [
                  rect1.topRight-rect1.topLeft,
                  rect1.topRight-rect1.bottomRight,
                  rect2.topLeft-rect2.bottomLeft,
                  rect2.topLeft-rect2.topRight
                  ];

    for(var axis in axises){
      Projection p1 = project(axis,rect1);
      Projection p2 = project(axis,rect2);
      if(!overlap(p1,p2)){
        return false;
      }
    }
    return true;
  }

  Projection project(Position axis, Rectangle rect){
    Position projection = getProjectionPosition(axis,rect);
    Collection<Position> corners = [rect.topLeft,rect.topRight,rect.bottomRight,rect.bottomLeft];
    num min = dot(projection,corners[0]);
    num max = min;
    for(var i = 1; i < corners.length; i++){
      num p = dot(projection,corners[i]);
      if(p < min){
        min = p;
      }else if(p > max){
        max = p;
      }
    }
    return new Projection(min,max);
  }

  bool overlap(Projection p1, Projection p2){
    return p1.max >= p2.min && p1.min <= p2.max;
  }

  num dot(Position projection, Position point){
    return projection.x*point.x + projection.y*point.y;
  }

  Position getProjectionPosition(Position axis, Rectangle rect){
    num p = (rect.topRight.x*axis.x+rect.topRight.y*axis.y)/(Math.pow(axis.x, 2)+Math.pow(axis.y, 2));
    Position projected = new Position(p*axis.x,p*axis.y);
    return projected;
  }
}

```

However this doesn't seem to work. I think I might be a bit confused about the `getProjectionPosition` algorithm, as you can see I always use `rect.topRight`. But maybe I am supposed to loop trough all the corners of the rectangle? or should it just be the corner belonging to this axis? The guide wasn't very clear on this.

Any ideas on whats wrong? Or is there a reference implementation I could look at to see how my implementation differs?

# Answer
> 1 votes
I'm not sure what `getProjectionPosition` is trying to accomplish at all. To project a set of points on an axis, you can just dot them with the axis vector. (It implicitly uses the origin of coordinates as the origin of the axis, which is fine.) So I think you can leave out the whole `getProjectionPosition` function and just do `dot(axis,corners[i])` in your `project` function.

On the other hand, I don't think that's where your problem is, since `getProjectionPosition` is just rescaling the axis vector by a number `p`, which shouldn't change the results of the overlap test; all the dot products will just be scaled by `p` as well. The rest of your code looks OK to me, though, so I'm not sure what's causing your test not to work correctly.

# Answer
> 0 votes
Solved it by changing the code a bit.

```
class SAT {

  SAT();

  bool collides(Rectangle a, Rectangle b){
    var axises = [
        a.topRight - a.topLeft,
        a.topRight - a.bottomRight,
        b.topLeft - b.bottomLeft,
        b.topLeft - b.topRight
    ];

    for(var axis in axises){
      Projection p1 = _project(axis,a);
      Projection p2 = _project(axis,b);
      if(!_overlap(p1,p2)){
        return false;
      }
    }
    return true;
  }

  Projection _project(Point axis, Rectangle rect){
      Collection<Point> corners = [rect.topLeft, rect.topRight, rect.bottomRight, rect.bottomLeft];
      Point projection = _projectionPoint(axis, corners[0]);
      num min = _dot(projection, corners[0]);
      num max = min;
      for (var i = 1; i < corners.length; i++) {
          projection = _projectionPoint(axis, corners[i]);
          num p = _dot(projection, corners[i]);
          if (p < min) {
              min = p;
          } else if (p > max) {
              max = p;
          }
      }
      return new Projection(min, max);
  }

  bool _overlap(Projection p1, Projection p2){
    return p1.max >= p2.min && p1.min <= p2.max;
  }

  num _dot(Point projection, Point point){
    return projection.x*point.x + projection.y*point.y;
  }

  Point _projectionPoint(Point axis, Point vertice){
    num p = (vertice.x+vertice.y)/(axis.x+axis.y);
    return new Point(p*axis.x,p*axis.y);
  }
}

```

Basically i needed to change the implementation to check against the correct vertice of the rectangle. in my code above i only checked against the upper right corner of the first rectangle.

---
Tags: collision-detection, game-mechanics, geometry, separating-axis-theorem
---


# Question
Title: Will the same Flash game business model work for HTML5 games?
One of the best ways to earn money with Flash games is by making sponsorship deals. The developer puts the sponsor's logo and a link to their site in the game and lets the game spread around the web. The sponsor gains money from the ads and the extra traffic to their website. Alternatively, they site-lock their game to their website (usually for a short period of time) so that people who want to play the game go to their website. It's true that one can remove the site-lock with some effort by decompiling the swf, but it's usually not done as it's not worth the effort and not legitimate. Another significant part of the Flash business model is to put advertisements in-game. There are other ways of earning money with Flash games, but from what I know, these two are the most prevalent ones.

Since HTML5 is necessarily open source, it makes me wonder if this model would still work for HTML5. Even if you obfuscate your js, it's much easier than Flash to copy the game, so maybe it's worth the effort for someone to copy the game to their (illegitimate) site. If you add your sponsor's logo and link or advertisements, it might be worth the effort to remove them for their site, something that I think is much harder to do with Flash games. Perhaps even the illegitimate site could claim that their site is better because there are no in-game ads. There's still the legitimacy barrier, but I wonder if it's strong enough.

Let's put aside all game development technical restrictions regarding HTML5 for this question (suppose for a moment that HTML5 works just as well as Flash for games). I have two very similar (pair of) questions. The first is, would the Flash business model work with HTML5? What changes to it would be helpful for HTML5 games? The second question is, what about the big picture for HTML5 games? Is adapting the Flash model really the best solution, or is there a better model for the HTML5 games world to "turn"?

# Answer
I don't think a lot will change, actually. SWF files are easy to decompile. Yes, the ActionScript will have made some irreversible changes that will make the decompiled code harder to figure out (destroying variable names, inlining functions or whatever) but a Javascript obfuscator could do that as well.

Hacking client software to remove ads is probably always possible, whatever language you use. So you have two options:

* Make it as hard as possible so it's not worth the effort
* Fight it the legal way, if there is one

One possible issue might be that browser extension like AdBlock or Greasemonkey can more easily change the game at runtime.
> 6 votes

# Answer
HTML5 games face a lot of hurdles:

* uncertain browser compatibility
* stability
* poor audio support
* slow JavaScript execution speed
* slow rendering speed
* no designer tooling
* source and assets are easily viewable / copyable
* game is easily hackable while running
* games embedded into other portals could run malicious code on the host portal
* lack of in-game advertising infrastructure
* game cannot be distributed to portals as a single file
* games could potentially "leak out" of their frames onto the page if not embedded correctly

So in summary, I don't think the current Flash game portal model will work for HTML5. I think where HTML5 might be successful is Facebook/Farmville style games.
> 7 votes

# Answer
You could tie users into using only your implementation by having part of your game logic on a server (hosted by AppEngine etc) which is accessed from the HTML, and check on the server that the caller is in fact yours.
> 2 votes

# Answer
## The Flash virality

Flash games are viral in nature because it's *extremely easy* for anyone to *copy and paste* an SWF into their own website, and stick ads around it. They're selling the dream of **"hey, take a game that somebody else made, and make money from it"**. Developers make money, portals make money, and the copycats make money. Everybody's happy.

## HTML5 != Virality (yet)

The exact same thing can be done with HTML5 (albeit not in a packaged way because of the way assets are placed on a web server). The problem is **getting people** who want to copy and paste your game.

Let's say **nobody** wants to do this, because they don't understand HTML5 well enough. Fine, we don't get to experience the *copycat-virality* effect.

That doesn't mean sponsorship model dies. You can still maintain the developer-portal relationship, cutting out the copycats in the process (isn't this better?).

As a developer, nothing changes except you're building games in javascript/css. The publisher works a bit harder because they need to find other distribution channels to compensate for not experiencing the "Flash virality". So far, they're doing quite okay, because they're paying good money for HTML5 games. Demand exists.
> 0 votes

---
Tags: flash, monetization, html5
---


# Question
Title: How long till HTML5 canvas becomes a viable game development platform?
So I have been working on web application. So invariably what it boils down to is making simple games which were previously based on flash or openGL. Now I know apple was moving away from flash because its proprietary unlike their stance that its got "pathetic performance"! Not true, try playing a canvas game, I can assure you at any point of time (including when its idle) it will use up a fair bit of processing power just to redraw the UI. Now I do understand that this is my fault because when the game is not active I should not be redrawing the canvas, but honestly its a lot of work and I suppose there should be libraries which should be able to assist me with that! So, how much will it be before I see a decent canvas library which handles these "tiny" issues for me? I can't honestly expect Steve Jobs to be doing anything more for HTML5! I someone knows of a good library, I am all ears...! :)

PS: I use mootools and am presently using Mootools Canvas Library.

# Answer
I think the title of your question could be better stated as "How long until we see solid HTML5 game development frameworks?".

The answer is: soon. There are several immature or WIP frameworks that I can think of off the top of my head. My guess is we'll start to see some pretty decent frameworks in the next 6 months or so.

Some frameworks to keep an eye on:

I'm sure there are at least a few other HTML5 game engines in the works. (If anyone knows of more, add a comment.)

There are some tricky problems with HTML5 game dev at the moment, for sure. It's kind of the wild west right now.

My co-founder and I have been developing our own HTML5 game engine that solves the kinds of issues you're mentioning (suspend on blur and things of that nature). It's developed for our own games currently, but we may open source it once it matures.

It's either that or wait until a solid framework emerges, and we're impatient. :)
> 6 votes

# Answer
i'm a HTML5 game developer working solely with the ImpactJS engine. It landed me a couple good contracts. By that definition, yes the canvas is a viable development platform.
> 3 votes

# Answer
The HTML5 games currently running are about where Flash was 5 years ago, just basic 2D/3D graphics with hardly any interactivity to be considered games (oh yes, you can contradict that by linking me to 10 HTML games, but that doesn't outweight the 10 thousand+ flash games in existence).

And by the time browsers that support Canvas become a de-facto standard (and I mean 90%+ usage across the world), Flash apps will have upgraded to supporting 3D rendering via DirectX and OpenGL, and dynamic sound generation via byte stream.
> 2 votes

# Answer
I'll give you two examples of games that I believe use the canvas element.

Quake II (webGL, chrome-only)
JZNES

I don't know what exactly you mean, or what you're looking for but this looks to be the next in up and coming technology. Games developed for should run on mobile devices as well as laptops and cross-platform without much to-do.

Granted, it won't ever be as powerful as dedicated hardware like an alienware machine or console, but it will probably fill the same role as Flash is performing now.
> 2 votes

# Answer
Rovio just announced web version of Angry Birds at Google I/O 2011. Built on GWT, it uses WebGL with fallback to Canvas2D. The only thing it uses Flash is the sound effect playing. So I think it is fair to say the technology starts to be ready.
> 2 votes

# Answer
My favorite JS engines built on top of canvas, in personal order:

* github.com/oberhamsi/gamejs - (my lib) port of PyGame; CommonJs compatible
* github.com/kesiev/akihabara - arcade game centric
* github.com/biilly/doodle-js - scene graph
* github.com/batiste/sprite.js - simplistic but fast sprite handling
* github.com/fairfieldt/xcjs - coffeescript
* easeljs.com/
> 0 votes

# Answer
Infinite, because IE8 currently supports only HTML \< 5, and IE 9 won't be available for Windows \< Vista, while many people will be going to wait for Windows 8 until they upgrade.
> -2 votes

---
Tags: web, javascript, html5
---


title: Vertex data from a buffer

text:
# Question
Title: Vertex data from a buffer
I'm using a geometry shader to generate polygons for my voxel terrain (marching cubes). The data is output into a buffer using the method shown in the article I link to below.

http://msdn.microsoft.com/en-us/library/bb205122%28v=vs.85%29.aspx

Is there any way to somehow extract the vertex data from the buffer, sort of like the inverse operation of this?

```
struct Vertex
{
    float x, y, z;
    float tu, tv;
}

Vertex[] data = new[] // this is what I want to get
{
    ...
};

DataStream stream = new DataStream(bufferSize, true, true);
stream.Write(data);
stream.Position = 0;
buffer = new Buffer(device, stream, description);

```

# Answer
You should be able to get CPU access to the data by using MapSubresource on the buffer (don't forget to unmap it when you're done). Be aware that this will cause a CPU/GPU sync, though: the CPU has to sit and wait for the GPU to finish all previous rendering before it can access the data. This is bad for performance if you're trying to do stuff in real-time.
> 1 votes

---
Tags: c#, slimdx
---


title: How do I render .dae models?

text:
# Question
Title: How do I render .dae models?
I'm building a game for iOS. I'm quite new to OpenGL but what I want is to take a 3D model I have made in Google SketchUp and use it in my 3d game. The problem is I don't know how to proceed. I have built 3d graphics in OpenGL before by specifying the vertices, but the 3D shape I have made is too complex. Is there a way .dae files can be broken down and re-formed as an OpenGL 3D model?

# Answer
Look into the (horribly named) AssImp asset importer library (http://assimp.sourceforge.net/). It allows loading a variety of 3D file formats into memory, which you can then use to generate your preferred in-memory format for rendering models.

You might consider using AssImp as a preprocessor pipeline stage. That is, have a separate tool to covert the Collada format into a custom format designed for your game needs. This is a production level thing, and not strictly necessary in early development or for personal projects.
> 7 votes

# Answer
How you handle vertex buffers, that's up to you. The .dae extension means that you're dealing with a COLLADA file. COLLADA reads like any XML file you've come across and can be parsed with the same tools. There are plenty of tutorials on both COLLADA and parsing XML, there are also plenty of XML parsers availible already, which means that most of the work has been done for you. I suggest you just try searching via Google, now that you know what you're dealing with.
> 3 votes

# Answer
The ".dae" format is the Collada format. A format specifically developed as exchange format. It's not recommended to use it for games, because the data is not setup in a way it could be easily used, also Collada has a absolutly huge overhead.

Google Sketch Up isn't a suitable for making game assets either. The geometry it generates is not optimized enough for games and it doesn't give the "artist" control about that eater.

Neither were made with games or other low level applications in mind.

Well, about Collada, its XML, so you should be able to load the parts you need from it with a simple XML reader. More in-depth informations about Collada can be found at the official website: http://www.khronos.org/collada/
> 1 votes

---
Tags: opengl, 3d, ios, opengl-es, collada
---


# Question
Title: Handling Latency in Multiplayer Shoot-em-ups
I had an idea for an architecture, and I was wondering if anyone has implemented something like this or has used AWS or some other service to help?

I thought about using NodeJS + SocketIO to handle a server side for this cooperative shmup (think Raiden or Galaga) we are just starting to work on. We started to think about latency issues.

The solution I came up with was to spin-up/down servers at the mid-point of the 2 users playing with some epsilon value (say 300miles or something). Perhaps the server would allow up to 50 users to play simultaneously and after that it would deny requests, which would then spring up another server. This should cause latency to be about equal for the 2 users playing. Furthermore, if we are matching making users then we always pair the 2 closest users together.

I suppose there are other factors to consider like user skill level, but I think right now we are most concerned about latency since it directly affects gameplay. Actually our game does require fairly precise timing. Also we want users to be able to see each other shoot since cool animations happen when they are in sync with each other.

I suppose this is similar to how a fighting game might operate in terms of timing/precision.

Ideas? Thoughts? How have others approached this problem? Where can I start looking for examples?

# Answer
Latency is not only about distance but about the player's connection speed, and the quality of their ISP's infrastructure, and that of the host of the server, and the traffic on the network. So, you could theoretically balance things out by locating a server at the midpoint, but I expect the benefit from that would be dwarved by other factors. You're usually better off just providing a selection of servers at various geographical locations and allowing players to find out for themselves which ones work best for them. eg. In the UK I may get a better ping going across the Atlantic to the USA than over to mainland Europe if it's 9am GMT and 4am EST, so you may as well let me make that choice.

Another factor would be that AWS and similar cloud services are optimised for throughput and reliability through redundancy, not for minimising latency. This makes them great for web sites or streaming data but often very poor for real-time games. Your experience may vary but generally speaking if you want predictable server performance you're usually going to want a dedicated or colocated server at best, though you might be ok with a virtual server if the hardware is powerful enough and you get good guarantees on the resource allocation available to you.
> 1 votes

---
Tags: architecture, multiplayer, node.js, latency
---


title: Optimizing isometric drawing function

text:
# Question
Title: Optimizing isometric drawing function
I need help optimizing my `Draw();` function to draw only what is visible in the viewport. Currently I'm drawing the whole Map array in a diamond shape. How can I make my function store only what is visible?

Here is an image explaining it better: ***Black tiles are X axis, White tiles Y axis. Green tiles are what I would like the function to store, and the Orange rectangle is the viewport.***

I'll include the relevant part of my code aswell:

```
for(i=0;i<Map.length;i++) {
for (j=0;j<Map[i].length;j++) {
tileX = (i - j) * (tile.width / 2);
tileX += (canvas.width /* 2*/) - (tile.width / 2);
tileY = (i + j) * (tile.height / 2);
tileY -= (canvas.height /* 2*/);

    c.drawImage(tile, tileX, tileY);
}
}

```

I've been trying to figure out how to solve this, but since I'm no genius I can't. Help appreciated.

# Answer
> 5 votes
(migrated from comments) This is kind of a duplicate of a previous answer I gave to How do I find which isometric tiles are inside the camera's current View.

The way I handle this is by iterating over horizontal/vertical rows and columns. I'll call these axes A/B instead of X/Y (which you're already using for the diagonal axes in your isometric view).

Translating X,Y to A,B is as simple as A = X+Y, B = X-Y. The reverse transformation is X = (A+B)/2, Y = (A-B)/2. If you choose a rectangle such that `min<A<max`, and `min'<b<max'`, then it corresponds to a particular rectangular viewpoint.

Here is the jsfiddle: http://jsfiddle.net/kAFVB/3/

Here are a couple examples of how different choices of A and B change the dimensions of the viewable area (the shaded rectangle is the same rectangle in both pictures)

# Answer
> 1 votes
This may not be the optimal solution, but a simple optimization would be just to figure out the span of X and Y values and draw everything in between that range.

As in, find the max and min for X and Y in your orange area, and then draw the space if it's X and Y are within the area.

If drawing areas not in your viewport is not an issue, than this should work fine. You may want to increase the max/min boundaries by one \[tile size\], depending on how you determine the X/Y of you tiles.

The shaded area is the area drawn.

Edit: A slightly more complicated (and computationally heavy) method would be to useout the distance from the center of your viewport to the location you want to draw it \[tileX,tileY\]. If your viewport's ratio is fixed to what it is now, you could just check if it's within 3 tile widths and 3 tile heights lengths (so if abs(tileX-viewportCenter.X )/tile.width \<=3 and abs(tileY-viewportCenter.Y)/tile.height \<=3), then draw).

If it isn't fixed, you can figure out the distance from the center to a corner (or use the diagonal distance of the viewport and divide by 2). Then check each tile location's distance the the middle of the screen. This will draw all the required tiles, plus a few extra on the sides (making a circular shape).

---
Tags: javascript, html5, isometric
---


title: 2D maps, how to structure?

text:
# Question
Title: 2D maps, how to structure?
I'm new to this. And I don't really understand 2D tile maps.

The tutorials I've read use arrays, but doesn't this get really difficult to manage when they get big?

And what if I want different floors, like going up/down stairs, do I need an array for every "level" of the game world?

Could anyone explain tile based maps as simple as possible please? If you include code, please make it Javascript or pseudo code since it's all i know.

# Answer
2D tile maps are exactly how they sound, imagine something like this:

```
1,1,1,1,1
1,0,0,0,1
1,0,2,0,1
1,0,0,0,1
1,1,0,1,1

```

This the design of our map and if we take

```
0 = floor
1 = wall
2 = chest

```

Then you can see that our map is a room with an entrance and a chest in the middle of the room our data structure for this could be like @georgeK said an Array of arrays ie.

```
var map =[ [1,1,1,1,1],
           [1,0,0,0,1],
           [1,0,2,0,1],
           [1,0,0,0,1],
           [1,1,0,1,1]];

```

We would then load each of our tiles into a look up just the once and draw our room by putting that tile in place of the number on the grid.

```
for row in map
   for each cell in row
      draw tile offset by the x, y position in the array multiplied by tile width.
   end inner loop
end outer loop

```

Now you may not wish to draw this to the canvas directly and instead draw to a off DOM canvas and then transfer the entire image at once.

As a side note a 2d map based in html 5 has been done by google as proof of concept for a multiplayer game which could give you a few ideas on optimization. video here

Hope this helps
> 6 votes

# Answer
Many games do use an array of arrays to represent a level.

It's possible that you could have poor performance with massive or infinite maps of open worlds if the entire map is in memory; a solution for that is to keep only some portion of the map in memory and load/unload map portions as the player(s) move around. If you're just beginning to write small 2D games you don't need to worry about this problem right now.

Usually you represent different levels with different array-of-arrays.
> 6 votes

# Answer
Other answers are quite fine, I just want to suggest that you transfer the actual maps via JSON, the Javascript object notation format, that lets you turn objects into strings. You can have a level editor that produces a JSON string, and then you can trasfer it that way, instead of using the hardcoded array literal notation.

Also, levels are, yes, just maps ontop of maps. The maps are actually represented as matrices, so you would use arrays of matrices, or an object where properties correspond with the name of the level and contain matrices.

I also suggest that you look into client-side databases. They allow you to store your level on your victims hard-drive and then you can load them into memory.
> 1 votes

---
Tags: html5, maps, html-canvas
---


# Question
Title: Help understanding HLSL - newbie questions
Just starting out with HLSL, please bare with me :)

There are times I'm a little confused by the syntax for instance in the pixel shader of an example I am following we have the following input and output:

```
struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 Depth : TEXCOORD0;
    float3 Normal : TEXCOORD1;
};

struct PixelShaderOutput
{
    float4 Normal : COLOR0;
    float4 Depth : COLOR1;
};

PixelShaderOutput PixelShaderFunction(VertexShaderOutput input)
{
    PixelShaderOutput output;

    // Depth is stored as distance from camera / far plane distance
    // to get value between 0 and 1
    output.Depth = input.Depth.x / input.Depth.y;

    // Normal map simply stores X, Y and Z components of normal
    // shifted from (-1 to 1) range to (0 to 1) range
    output.Normal.xyz = (normalize(input.Normal).xyz / 2) + .5;

    // Other components must be initialized to compile
    output.Depth.a = 1;
    output.Normal.a = 1;
    return output;
}

```

Now one of the parts that confuses me is

```
output.Depth = input.Depth.x / input.Depth.y;

```

I'm confused because I thought Depth is a float4, which to my understanding is a 4-component vector. Doesn't input.Depth.x / input.Depth.y return a scalar value? What is happening in this assignment?

Secondly, and similarly

```
output.Normal.xyz = (normalize(input.Normal).xyz / 2) + .5;

```

Wouldn't normalize(input.Normal).xyz / 2 return a 3-component vector, with each element divided by 2? What does it mean then to add that 3-component vector to a scalar .5?

I feel like I'm missing something obvious here that I'll probably slap my forehead when someone points it out.

Also one more question - by the time the float4 Position arrives at the pixel shader from the vertex shader output, at this point are the coordinates in clip-space \[-1,1\] or are they still in camera-coordinates but with the homogeneous w-component (eg before the perspective divide) ? Is the w-component usually equal to the z-component?

# Answer
HLSL lets you compress a vector with the same value down to a scalar. When you do `output.Depth = input.Depth.x / input.Depth.y` what you're actually doing is:

```
float x = input.Depth.x / input.Depth.y;
output.Depth = float4( x, x, x, x );

```

And the same with the normal example above.

To your second question: Pixel shader inputs depend on the shader semantic you access. Shader semantics are the extra bit after the colon in variable definitions that specify where the data comes from for the input, or where the output goes.

In the above shader you don't define a position semantic so you won't get one. If you added `SV_Position` to your pixel shader input (D3D10 and higher), the position is in screenspace. You can read more about the available shader semantics here.
> 5 votes

---
Tags: xna, hlsl
---


title: Why is the MaskBit maxed out

text:
# Question
Title: Why is the MaskBit maxed out
Hi there for some reason the maskbit of my b2FixtureDef is being maxxed out and im not sure why

Here is the declaration of the items that are used in the game

```
enum PhysicBits {
    PB_NONE = 0x0000,
    PB_PLAYER = 0x0001,
    PB_PLATFORM = 0x0002
};

```

Basically what i want is the player to run along a surface is not slow down (i set platform & player friction to 0.0f)

I then setup my Contact Listener to print out the connections (currently only have 1 platform and 1 player)

Player Fixture Def

```
b2FixtureDef fixtureDef;
fixtureDef.shape = &groundBox;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.0f;
fixtureDef.filter.categoryBits = PB_PLAYER;
fixtureDef.filter.maskBits = PB_PLATFORM;

```

Platform Fixture Def

```
b2FixtureDef fixtureDef;
fixtureDef.shape = &groundBox;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.0f;
fixtureDef.filter.categoryBits = PB_PLATFORM;
fixtureDef.filter.maskBits = PB_PLAYER;

```

Now correct me if im wrong but these are saying the following:

* Player Collides with Platform
* Platform Collides with Player

Here is the printout of the fixtures colliding with each other

```
********    <-- Indicates new Contact
Platform
ContactA: 2
MaskA: 1
------
Player
ContactB: 1
MaskB: 2
********    <-- Indicates new Contact
Platform
ContactA: 2
MaskA: 1
------
Player
ContactB: 1
MaskB: 65535
********    <-- Indicates new Contact
Platform
ContactA: 1
MaskA: 65535
------
Player
ContactB: 1
MaskB: 65535

```

Here is where i am confused. On the second & third contact the player maskBit is set to 65535 when it should be 2 and there are 3 contacts when i am sure at most there should only be 2.

I've been trying to figure this out for hours and i can't understand why it is doing this. I would be very grateful is someone could shine some light on this for me

UPDATE: \**I printed out the class of the contacting objects. For some reason it seems to do the following:

First Contact: Correct Result.

Second Contact: Player b2Fixture Obtains a new maskBit.

Third Contact: Platform b2Fixture appears to be set to the same as the Player b2Fixture. It would seem I have a memory race condition i think\**

# Answer
> 0 votes
Ok so it seems I've figured it out.

***Firstly, the multiple BeginContact Calls:***

From what i can gather this is from the fact that i was checking against two Edges Colliding, and during the velocity steps of Box2d (which i had set to 8) it kept pushing the Edges apart which would cause them to overlap again and fire off another BeginContact.

It resolved my multiple BeginContact calls by switching the player & platform to Boxes (with out custom edges, using setAsBox).

***Secondly, the change maskBits:***

I don't know if it is a Cocos2d+Box2d related issue, but i was checking the wrong filterData.

**What i was doing:**

```
contact->GetFixtureA()->GetFilterData();

```

**What i am now doing:**

```
contact->GetFixtureA()->GetBody()->GetFixtureList()->GetFilterData();

```

Now i don't know why the filterData is stored twice in the `b2Fixture` object, but it seems a little redundant to me. Or if i am even supposed to use the `b2Body` `filterData`.

But my collision detection works perfectly now

---
Tags: physics, cocos2d-iphone, box2d
---


# Question
Title: Tile engine Texture not updating when numbers in array change
I draw my map from a txt file. I am using java with slick2d library. When I print the array the number changes in the array, but the texture doesn't change.

```
public class Tiles {

public Image[] tiles = new Image[5];

public int[][] map = new int[64][64];

public Image grass, dirt, fence, mound;

private SpriteSheet tileSheet;

public int tileWidth = 32;
public int tileHeight = 32;

public void init() throws IOException, SlickException {
    tileSheet = new SpriteSheet("assets/tiles.png", tileWidth, tileHeight);

    grass = tileSheet.getSprite(0, 0);
    dirt = tileSheet.getSprite(7, 7);
    fence = tileSheet.getSprite(2, 0);
    mound = tileSheet.getSprite(2, 6);
    tiles[0] = grass;
    tiles[1] = dirt;
    tiles[2] = fence;
    tiles[3] = mound;

    int x=0, y=0;
BufferedReader in = new BufferedReader(new FileReader("assets/map.dat"));
String line;
while ((line = in.readLine()) != null) {
        String[] values = line.split(",");
        x = 0;
    for (String str : values) {
            int str_int = Integer.parseInt(str);
            map[x][y]=str_int;
            //System.out.print(map[x][y] + " ");
            x++;
        }
//System.out.println("");
y++;
}
    in.close();
}

public void update(GameContainer gc) {

}

public void render(GameContainer gc) {
    for(int y = 0; y < map.length; y++) {
        for(int x = 0; x < map[0].length; x ++) {
            int textureIndex = map[x][y];
            Image texture = tiles[textureIndex];
            texture.draw(x*tileWidth,y*tileHeight);
        }
    }
}

```

}

**Mouse Picking Where I change the number in the array**

```
Input input = gc.getInput();

    gc.getInput().setOffset(cameraX-400, cameraY-300);
    float mouseX = input.getMouseX();
    float mouseY = input.getMouseY();

    double mousetileX = Math.floor((double)mouseX/tiles.tileWidth);
    double mousetileY = Math.floor((double)mouseY/tiles.tileHeight);

    double playertileX = Math.floor(playerX/tiles.tileWidth);
    double playertileY = Math.floor(playerY/tiles.tileHeight);

    double lengthX = Math.abs((float)playertileX - mousetileX);
    double lengthY = Math.abs((float)playertileY - mousetileY);
    double distance = Math.sqrt((lengthX*lengthX)+(lengthY*lengthY));

    if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON) && distance < 4) {
        System.out.println("Clicked");
        if(tiles.map[(int)mousetileX][(int)mousetileY] == 1) {
            tiles.map[(int)mousetileX][(int)mousetileY] = 0;
        }
    }

```

I don't know what is wrong: all my textures work when I render them, it just doesn't update when the number in the array changes. I am obviously debugging when I say that I was printing the array and the number is changing like it should, so it's not a problem with my mouse picking code. It is a problem with my textures, but I don't know what because they all render correctly.

# Answer
> 0 votes
The problem could be in your render logic you have hardcoded to look at map\[0\]

Change to

```
    for(int y = 0; y < map.length; y++) {
        for(int x = 0; x < map[y].length; x ++) {
            int textureIndex = map[x][y];
            Image texture = tiles[textureIndex];
            texture.draw(x*tileWidth,y*tileHeight);
        }
    }

```

**EDIT** I as the comment below suggests map\[0\].length would be fine if the map is guaranteed to be same width each row. (this is what I for posting before morning coffee)

**EDIT 2**

It dawned on me that you have no option to update back to 1 if 0 in your click handler so you could never change a 0 to a 1 in the first place, so the number never changed

```
if(tiles.map[(int)mousetileX][(int)mousetileY] == 1) {
  tiles.map[(int)mousetileX][(int)mousetileY] = 0;
}

```

you could add an else statement like so

```
if(tiles.map[(int)mousetileX][(int)mousetileY] == 1) {
  tiles.map[(int)mousetileX][(int)mousetileY] = 0;
}
else {
   tiles.map[(int)mousetileX][(int)mousetileY] = 1;
}

```

---
Tags: java, textures, tiles
---


title: XNA and Draw rotation

text:
# Question
Title: XNA and Draw rotation
From Wikipedia the (image) conversion degrees / radians shows the quadrants so that the increase of radians causes a counter-clockwise rotation but when using the following code the sprite is rotated clockwise:

```
rotation = (rotation + 0.5f) % MathHelper.ToRadians(360);
...
spriteBatch.Draw(sprite, sprite_center_other_sprite, new Rectangle(0, 0, 50, 50), Color.White, rotation, new Vector2(width/2, height/2),1.0f, SpriteEffects.None, 0.0f);

```

Why? The direction is a convention or XNA is different?

# Answer
> 5 votes
As posted in this question on SO:

> The XNA SpriteBatch works in **Client Space**. Where "up" is Y-, not Y+ (as in Cartesian space, projection space, and what most people usually select for their world space). This makes the rotation appear as clockwise (not counter-clockwise as it would in Cartesian space).

So, that said, if this code is intended to prevent the angle from getting too large, consider using the `MathHelper.WrapAngle()` method. This method wraps the angle you give it (in radians) to between π (180°) and -π(-180°).

```
rotation = MathHelper.WrapAngle(rotation + 0.5f);

```

Note: If it is in your `Update` statement, you may also want to multiply the 0.5f against the elapsed game time so that your rotation speed is per second and not per `Update`. The final line would be:

```
rotation = MathHelper.WrapAngle(rotation + 0.5f * (float)gameTime.ElapsedGameTime.TotalSeconds);

```

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


# Question
Title: Why are my triangles not being drawn in the color I define?
I render a simple mash structure with `Tao` (don't think this is relevant) using *DisplayList*.

Following code appears between

```
int displayList = Gl.glGenLists(1);
Gl.glNewList(displayList, Gl.GL_COMPILE);

```

and

```
Gl.glEndList();

```

Simplified version of the code, with removed unrelevant parts:

```
Gl.glBegin(Gl.GL_TRIANGLES);

for (int i = 0; i < triangles.Count; i++)
{
    var triangle = triangles[i];

    bool ok = false;
    var normal = triangle.GetNormal(out ok); //get normal of TRIANGLE

  //this method just retrives correct color information here
    var visualData = GetVisualData(visual,
                      visual.RenderSettings, triangle,null, false);

    //Set the color for the vertex here. Color is always the same in THIS case
    Gl.glColor4f(m_colors[visualData.color.R],
                     m_colors[visualData.color.G],
                             m_colors[visualData.color.B],
                                 visualData.transparency);

    //for every vertex in triangle
    for (int vtx = 0; vtx < triangle.Vertices.Length; vtx++)
    {
         var v = triangles[i].Vertices[vtx];
         Vertex3 v3 = v.Coord;
         Gl.glVertex3d(v3.x, v3.y, v3.z); //set vertex
         Gl.glNormal3d(normal.x, normal.y, normal.z);  //set normal

    }

}

Gl.glEnd();

```

Accoring to documentation if I set the **same** color for all 3 vertices of the triangle it must have the solid color. But what I get is:

As you see the colors are not uniform across different triangles, but I'm pretty sure that in *this* loop the color is not changed, it remains static (I even tried to set constant `int` values as color , but result is always the same)

**Q**:

What can be possible reason of this rendering behaviour?

# Answer
> 3 votes
In immediate mode rendering in OpenGL, you open up a sequence of primitives by `Begin`, emit a bunch of elements in that sequence, and terminate it with `End`.

There's two choices on how OpenGL could have handled the emission of the elements. One way would be that a `Vertex` call would create an element and that subsequent calls to functions like `Color`, `Normal`, `TexCoord` would modify those attributes of that vertex.

That is not the case, however. The approach that OpenGL uses is that first you set all the attributes you want with those functions (`Color`, `Normal`, etc.), and *then* emit an immutable element with the `Vertex` function.

In your code, you do this correctly for `Color`, but your `Normal` changes are lagged by one vertex, resulting in inconsistent normals for a face.

In essence, set all the changed vertex attributes first, then invoke `Vertex` to emit a vertex with those attributes.

---
Tags: c#, opengl, 3d-meshes
---


title: Add value to XNA Vector2

text:
# Question
Title: Add value to XNA Vector2
I wonder if it's possibel to add a value to X and Y in a Vector2? I have this code that creates a missile that use the position from the spaceship as a start position. But I would like to add some pixels so that the missile starts a little bit away from the spaceship. can I do that?

```
objectManager.AddNewMissileToList(new Missile(textureMissile, spaceship.spaceshipPosition, spaceship.spaceshipDirection));

```

# Answer
> 3 votes
You mean something like

```
Vector2 offset = new Vector2(2,1);
objectManager.AddNewMissileToList(new Missile(textureMissile, spaceship.spaceshipPosition + offset, spaceship.spaceshipDirection));

```

if the spaceShipDirection is directional vector

```
Vector2 offset = spaceship.spaceshipDirection * 1.5f;
objectManager.AddNewMissileToList(new Missile(textureMissile, spaceship.spaceshipPosition + offset, spaceship.spaceshipDirection));

```

or if the spaceShipDirection is float angle

```
Vector2 offset = new Vector2((float)Math.Sin(spaceship.spaceshipDirection),
                             (float)Math.Cos(spaceship.spaceshipDirection))
                 * 1.5f;

objectManager.AddNewMissileToList(new Missile(textureMissile, spaceship.spaceshipPosition + offset, spaceship.spaceshipDirection));

```

---
Tags: xna
---


# Question
Title: Best practices for communication between game designer and artist
I'm having big troubles to sharing ideas and communicating my ideas to artists. They're friends who don't get a dime helping me so I don't want to waste their time trying to figure out what I have in mind. And my crappy sketches don't seem to be enough.

How do you communicate with the artist to create the assets? What kind of templates are commonly used? I'm looking for best practices and templates to define characters, assets, backgrounds.

# Answer
> 12 votes
Ultimately this depends on how much of the project has been taken care of by you or other 'non artists.' Meaning that the answer if you've already built a game and need art to replace your temp graphics is different than if you've already created an engine and now wish to have someone help you write the story, create the characters and setting, and create art assets for those things inside the confines of your engine; is different than if you don't have anything created and only have a vague idea of how the gameplay should work and what kind of game you are making.

## I have a completed game, but need replacement art assets.

Start by collecting a complete registry of the needed assets, organized by type: character sprites, interface components, tooltip icons, so on. And then sub-organized by other groupings as makes sense, UI elements can be ordered by what interface they are a part of, character sprite animations for all the motions can go under the character itself.

Being organized like this makes it very easy to track what has been completed percentage wise, and it also makes it very easy for an artist to swoop in and work on a section of the project and complete all the parts needed.

If tom'kin the barbarian needs walk, run, slide, jump, bash, big-bash, and super-bash animations; the artist will see all of this and be able to use the temp-art as a starting point to complete all of his animations.

## I have an engine but nothing more.

Since you have an understanding of what kind of game you are making, be it a Shmup or RPG or RTS, you can write that down. Take stock of example game design documents around the web and use those as a starting point to detail the needed components of your game. RPGs will need items and characters and quests and such, for example. You know what items are in your engine, you know that they need a name, a description, an icon, and whatever else they need and the specifications of each. Write that down.

If you have an idea for the plot of the game, write that into the design doc. If you have an idea for the art, provide example images in the design doc.

Turn this document over to your artist/writer and let them have time with it. Then start working on a story and art bible. The story bible should ultimately contain the entire major plot of the game, including any branches. The art bible will start with concept art and eventually feature completed sketches of all the characters and settings in the game. It isn't required to put everything in these bibles, but the more the better.

After you are happy with these three documents, produce your game with temp art as the artist/writer starts putting together the assets. Create a list like in the sections above and replace the temp art as you go.

## I have nothing, what first?

Play lots of games in the style/genre you want. Collect screenshots and videos if you can. Meet with your game designer and discuss what kind of game you want to make and the kinds of technology you have available. Do you know how to program 3D games? 2D? Have you made mostly RPGs? Roguelikes? Shmups? Puzzle games?

Before long an idea will gel between you. Then the game designer can go off and put together a design document shell. Discuss again what your options are, show some demonstration code you put together since the last time you met, and make sure you are both on the same page. Iterate. Eventually you'll be able to pick up with the section above, and then move on to the top section and you are done.

---
Tags: art
---


title: Reset timer in XNA

text:
# Question
Title: Reset timer in XNA
I use a simple timer to count the time the player has to play the game. After 60 seconds the game is terminated. But if the player whants to play again, the timer continue and not resets! How can I reset the timing?

```
 seconds = gameTime.TotalGameTime.Seconds;
 if (seconds == 60)
    {
        currentGameState = GameState.GameOver;
        seconds = 0;
    }

```

# Answer
Since you're using XNA, I think the ideal (and typical) solution is to use your own timer variable. You're almost there, but you can't use `TotalGameTime` because of the comments in the other answers and because you can't be sure that the level would start exactly on the first second of a minute since the game started. Sure, it's possible if you have no menus and your game runs immediately and restarts every 60 seconds. But going forward I'm sure you're going to want to make it a little bit more robust.

So, what you want to do is create a field variable `float seconds;` at the top of your class. Then, in your update, you want to do this:

```
seconds += (float)gameTime.ElapsedGameTime.TotalSeconds; //Add the elapsed seconds so far
if (seconds >= 60) { //Check if 60s have elapsed
    seconds = 0; //Restart the seconds counter
    //End or restart the game
}

```

This way, all you have to do to reset the counter is set the `seconds` variable to `0` and it will start counting up again.
> 3 votes

# Answer
Your first problem is that Seconds can only be 59, it resets to 0 every minute and will never hit 60.

Either check if it's 59 - or write your own routine that uses TotalSeconds instead (which will continue to increase over 59 but never reset to 0) or some other way to detect the transition from 59 to 0.

```
if (seconds == 59)
{
    ...handle end round....
}

```

There are many ways to handle the issue now that it's pin-pointed, here's one

```
// When round starts
TimeSpan roundStartTime = gameTime.TotalGameTime;

// In update loop
if (roundStartTime.TotalSeconds.Add(60) >= gameTime.TotalGameTime.TotalSeconds
{
     ....handle end round...
}

```
> 2 votes

# Answer
The problem you have is that TotalGameTime.Seconds goes from 59 to 0 instead of 60, so it never actually hits 60, so that's the first thing to consider. You cannot simply check for TotalGameTime.Seconds == 0 either, because your game would terminate in the very first game loop when no time has really passed.

So what you really have to check for is the transition from gametime 59 to 0.

Therefore, what you could do is something like:

```
int seconds = 0;   //a field outside the game loop
...
if(gameTime.TotalGameTime.Seconds == 0 && seconds == 59)
{
    //60 seconds have passed, terminate the game now
}
else
{
    seconds = gameTime.TotalGameTime.Seconds;
}

```

Note however the following remark:

> Fixed-step clocks update by a fixed time span upon every clock step. This results in uniform clock steps that may not actually track the wall clock time. Fixed step clocks were popular on console systems where one had tight control over code and a fixed system performance. Fixed-step clocks are also useful when trying to achieve deterministic updates for debugging, offline rendering, or other such scenarios.

That means that even if your TotalGameTime says 60 seconds have passed, it may not be real world 60 seconds. In the worst case, if a player slows down his system, it might even be a possible exploit/cheat, so you should explore other ways of tracking time as well.
> 0 votes

---
Tags: xna
---


# Question
Title: How to obtain "annealing" effect via particle system
In this video demonstration, there is the *annealing effect*, where particles seems to loose their hue and converge into pure white, and then gradually disappear via alpha channel. And in parallel to all of this: particles are gradually becoming thicker.

I tried with my particle system and it is giving different results. How to obtain the "annealing"?

# Answer
Luckily, the project is opensource. That includes the demos used to create the videos. So we can see from the demo source:

```
particleModel->setParam(PARAM_ALPHA,5.0f,0.0f); // the particles will fade as they die
particleModel->setParam(PARAM_SIZE,1.0f,15.0f); // the particles will enlarge over time
particleModel->setLifeTime(5.0f,6.0f);

```

The particles are set to fade and grow. Then in the update loop:

```
// Changes the color of the model over time
step += deltaTime * 0.0005f;
particleModel->setParam(PARAM_RED,0.6f + 0.4f * sin(step));
particleModel->setParam(PARAM_GREEN,0.6f + 0.4f * sin(step + PI * 2.0f / 3.0f));
particleModel->setParam(PARAM_BLUE,0.6f + 0.4f * sin(step + PI * 4.0f / 3.0f));

```

The three color channels are increased over time, leading to a white color. It looks like some of the particles don't have a chance to change color before they disappear, making the edges colored. The writing demo source is available here. And the entire source here.
> 3 votes

# Answer
It just looks like the blending mode between particles is additive, ie the color channels are added (perhaps with an adjustable factor) together so when there are enough particles (or bright enough parts of particles) covering a particular spot that spot will be white (each color channel is capped at its maximum value) unless the alpha has become too low.

Not sure about the scaling, to me that's simply setting the size of each individual particle sprite slightly larger over each time period.
> 3 votes

---
Tags: graphic-effects, particles
---


# Question
Title: Content loading, Content processing and add processed file to a DataContainer?
I'm trying to create some kind of editor in Windows Forms for XNA and I was wondering if there's anyway to do this:

Load content (known types, like Model/SpriteFont/Effect/Texture) through OpenFileDialog, then Process it to an \*.xnb file and finally be able to add it to a datacontainer, so you can use it in an editor.

Is this possible, and since I only want to use known types that already have Importers/Processors - what is the best way to go about doing this?

Because for me, to just manually have to add content when later creating the game logic and having everything set up in the editor feels very static.

So simply put, I want to be able to load content and process it and later be able to store it so when I create a game using this I can add a DataContainer that I can change and add to in the editor as well as use in the game.

Doing Content.Load() 2000 times later in the game feels like a time waster.

# Answer
Yes, this is possible. The starting point for this is the XNA WinForms 2 sample.

The documentation with that sample will explain how to process content within your application and load it. It is also the starting point for writing that content out as an XNB file (IIRC, the sample *almost* does this - you just have to modify it to write the output somewhere useful).
> 1 votes

---
Tags: xna, c#, xna-content-pipeline, editors, importing
---


title: Blender: How to merge two faces?

text:
# Question
Title: Blender: How to merge two faces?
## Initial Situation

Using Blender 2.6, I often come to the same problematic setting: There are two faces on one straight line.

## My Aim

I want to keep just one of the two selected faces, which you can see above. And all of the vertices adjoining the one face should be merged \[`Alt + M` in Vertex Select Mode\] with the apt vertex adjoining the other face.

## Summary

I just simply need a tool working like Vertex Merging \[`Alt + M` in Vertex Select Mode\] for faces.

How can I do that easily?

# Answer
> 2 votes
Vertex merging is for vertices only, hence the name. You can do what you want by selecting each of the 4 sets of vertices separately and merging them with their appropriate counterpart one pair at time. Alternatively, you can select the lower face and move it to overlap the second, then delete the second.

# Answer
> 2 votes
There's no built-in tool because this isn't a commonly occurring situation for most people. In particular, how did you get 3 faces, two of them connected directly aligned along a shared normal axis? To even get into this situation, it might be easier to extrude one face to get the other, and if you have an extra loop you can delete the edge loop easily. Or alternatively, you could be using the "bridge/loft" tool to connect pre-existing faces.

---
Tags: models, 3d-meshes, blender
---


# Question
Title: Map with 20 million tiles makes game run out of memory, how do I avoid it?
While loading extra huge maps, the loading method throws out of memory exception where a new instance of map tile is created. I'd like to have whole map processed at least on server app (and on client if possible). How should I solve this problem?

**UPD:** the question here is how to make the game stop crashing when there's still free memory for it to use. As for splitting map in chunks, it's a good approach, but not what I want in my case.

**UPD2:** At first I went and assigned a texture to every new instance of tile class and that's what took so much memory (also loading time). Now it takes about four times less space. Thanks to everybody, now I can run huge maps without thinking of breaking them up in chunks just yet.

**UPD3:** After rewriting the code to see if arrays of tile properties work faster or consume less memory (than said properties in their respective tiles as object properties), I found out that not only it took me a lot of time to try that, it didn't bring any performance improvement, and made the game terribly difficult to debug.

# Answer
> 60 votes
> the app crashes when it reaches 1.5Gb.

This strongly suggests that you're not representing your tiles correctly, as this would mean that each tile is ~80 bytes in size.

What you need to understand is that there needs to be a separation between the *gameplay* concept of a tile, and the *visual tile* that the user sees. These two concepts are *not the same thing*.

Take Terraria for example. The smallest Terraria world takes up 4200x1200 tiles, which is 5 million tiles. Now, how much memory does it take to *represent* that world?

Well, each tile has a foreground layer, a background layer (the background walls), a "wire layer" where wires go, and a "furniture layer" where furniture items go. How much memory does each tile take up? Again, we're just talking conceptually, not visually.

A foreground tile could easily be stored in an unsigned short. There aren't more than 65536 foreground tile types, so there's no point in using more memory than this. The background tiles could easily be in an unsigned byte, as there are fewer than 256 different types of background tiles. The wire layer is purely binary: either a tile has a wire in it or it does not. So that's one bit per tile. And the furniture layer could again be an unsigned byte, depending on how many possible different pieces of furniture there are.

Total memory size per tile: 2 bytes + 1 byte + 1 bit + 1 byte: 4 bytes + 1 bit. Thus, the total size for a small Terraria map is 20790000 bytes, or ~20MB. (note: these calculations are based on Terraria 1.1. The game has expanded a lot since then, but even modern Terraria could fit within 8 bytes per tile location, or ~40MB. Still quite tolerable).

You should *never* have this representation stored as arrays of C# classes. They should be arrays of integers or something similar. A C# struct would work as well.

Now, when it comes time to draw *part* of a map (note the emphasis), Terraria needs to convert these conceptual tiles into *actual* tiles. Each tile needs to actually pick a foreground image, background image, an optional furniture image, and have a wire image. This is where XNA comes in with its various sprite sheets and such.

What you need to do is to convert the visible part of your conceptual map into actual XNA sprite sheet tiles. You should not be trying to convert the *entire thing at once*. Each tile you store should just be an index saying that "I'm tile type X," where X is an integer. You use that integer index to fetch which *sprite* you use to display it. And you use XNA's sprite sheets to make this faster than just drawing individual quads.

Now the visible region of tiles needs to be broken up into various chunks, so that you're not constantly building sprite sheets whenever the camera moves. So you might have 64x64 chunks of the world as sprite sheets. Whichever 64x64 chunks of the world are visible from the player's current camera position are the chunks you draw. Any other chunks don't even have sprite sheets; if a chunk falls off the screen, you throw that sheet out (note: you don't really delete it; you keep it around and respecify it for a new chunk that may become visible later).

> I'd like to have whole map processed at least on server app (and on client if possible).

Your *server* does not need to know or care about the visual representation of tiles. All it needs to care about is the conceptual representation. The user adds a tile here, so it changes that tile index.

# Answer
> 22 votes
Split the terrain into regions or chunks. Then only load the chunks that are visible to the players and unload the ones that are not. You can think of it like a conveyor belt, where you're loading chunks at one end and unloading them at the other as the player moves along. Always staying ahead of the player.

You can also use tricks like instancing. Where if all the tiles of one type just have one instance in memory and are drawn multiple times in all the locations where it's needed.

You can find more ideas like this here:

How'd they do it: Millions of tiles in Terraria

'Zoning' up areas on a large tile map, as well as dungeons

# Answer
> 5 votes
Byte56's answer is good, and I started writing this as a comment to that but it got too long and contains some tips that might be more helpful in an answer.

The approach is absolutely just as good for server as it is for a client. In fact it's probably **more** appropriate, given that the server will be asked to care about far more areas than a client will. The server has a different idea about what needs to be loaded than a client would (it cares about all the regions that all the connected clients care about), but it is equally capable of managing a working set of regions.

Even if you could fit such a gigantic map (and you most likely can't) in memory, *you don't want to*. There is absolutely zero point in having data loaded which you don't immediately have to use, it's inefficient and slow. Even if you could fit it in memory, you most likely wouldn't be able to process it all in any sensible length of time.

I suspect your objection to having certain regions be unloaded is because your world update is iterating over all the tiles and processing them? That's certainly valid, but it doesn't preclude having only certain parts loaded. Instead, when a region is loaded, apply any updates that were missed, to bring it up to date. That's far more efficient processing-wise as well (concentrating a big burst of effort on a small area of memory). If there are any processing effects which might cross region boundaries (e.g. a lava flow or a water flow which will carry over into another region), then bind those two regions together so that when one is loaded, so is the other. Ideally those situations would be minimised, otherwise you'll find yourself quickly back at the 'all regions must be loaded at all times' case.

# Answer
> 3 votes
An efficient way I've used in a XNA game was:

* use spritesheets, not an image for each tile/object, and just load what you will need on that map;
* split the map in smaller parts, say chunk maps of 500 x 200 tiles if your map is 4 times this size, or something you can haldle;
* load this chunk in memory and paint only the visible parts of the map (say, the visible tiles plus 1 tile for each direction the player is moving) in a offscreen buffer;
* clear the viewport and copy the pixels from the buffer over (this is called double buffer and smooths the moviment);
* when you char moves, track the bouds of the map and load the next chunk when it gets near it and append to the current one;
* once the player is entirelly in this new map, you can unload the last one.

You could also use a single big map in this way if it is not SO big and use the logic presented.

Off course the size of your textures have to be balanced and the resolution pays a great price in this. Try working at a lower resolution and, if you need, make a high res pack to load if a config setting is set to.

You will have to loop only the relevant parts of this map each time and render only what is needed. This way you will improve the performance a lot.

A server can process a huge map faster because it don't have to render (one of the slowest operations) the game, so the logic for it can be the use off a bigger chunks or even the entire map, but process only the logic around players, like in a 2 times the player viewport of area around the player.

An advice here is that I'm by no ways an expert in game dev and my game was made for my graduation's final project (which I had the best score), so I may be not so right in every point, but I've researched the web and sites like http://www.gamasutra.com and the XNA creators site creators.xna.com (at this time http://create.msdn.com) to gather knowledge and skills and it worked fine for me.

# Answer
> 1 votes
Either

* buy more memory
* represent your data structures more compactly
* don't hold all data in memory at once.

# Answer
> 1 votes
> the question here is how to make the game stop crashing when there's still free memory for it to use. As for splitting map in chunks, it's a good approach, but not what I want in my case.

In reply to your update, you cannot allocate arrays over `Int32.MaxValue` in size. You have to split it into chunks. You could even encapsulate it in a wrapper class that exposes an array-like facade:

---
Tags: xna, 2d, memory-efficiency
---


# Question
Title: What would be the problems with using a singleton design pattern for my engine?
I'm desiging an HTML5 2D game engine in JavaScript, and currently, I use the singleton pattern.

There is only one global object in the namespace called simply Engine. All other objects are instantiated through this one, for example:

```
var scene = new Engine.Scene();
var renderer = new Engine.Renderer();

```

This works great, but I started expanding and actually adding methods to the Engine object, not just classes (on a conceptual level, I know that they're technically different).

Now, the Engine object has an `update()` method, which should be called by the user (game) each loop, and some other properties such as *updates per second*, etc. Different objects (scenes etc) register some of their own update methods to the `Engine.update()` method, which just serves to call them.

What are the dangers of a such design? I've heard many people badmouthing the singleton design pattern, does it apply here?

# Answer
> 4 votes
Unless you plan on running two separate games in the same page then a singleton naturally makes sense.

With that being said, it does introduce the issue of constantly referencing global variables. For a minor course on why this is an issue you might check out this article but I would really suggest reading Nicholas C. Zakas's *High Performance Javascript.*

The basic rundown goes a little something like this: say you've got some arbitrary function

```
function RunGame() {
    var player = new Player();

    alert(player.position.x);

    for(var i = 0; i < 5; i++)
         document.write(Engine.ToString() + "<br />");
}

```

Obviously the function is nonsense but pay attention to the scoping here. Whenever JS is looking for a variable, it starts with the inner-most scope first before heading outward. So getting the player is no big deal, the JS engine just says `Hey, the player is right here, I don't need to look any farther.` But when you're referencing things out of scope, like the `Engine` or even `document`, it still has to see if those are local variables.

If you look at that horrible for loop that you should never consider doing ;) it references `document` five different times and each of those times it has to check the local scope, any outer scope (say if this function was a part of some larger object), so on and so forth until finally getting to the global scope. All of a sudden, referencing the same object takes a lot more operations. This effect can be lessened by making references in the local scope (which I suggest you always do if a variable is used more than once)

```
function RunGame() {
    var player = new Player(),
        doc = document;

    alert(player.position.x);

    for(var i = 0; i < 5; i++)
        doc.write(Engine.ToString() + "<br />");
}

```

But this still means you have to make that extra leap to global scope every time you generate your local variables. So it really depends on how intense you believe your game will be and how lazy you feel like being ;)

# Answer
> 0 votes
This answer provides many problems that are often a result of using global state, as well as some alternatives. Since a singleton has the same problems as global state, it applies here. The biggest issues caused are:

* **Bugs from mutable global state** (It can be hard to track down who changed what, if everyone can change anything).
* **Poor testability** (In your example, you have to rely on monkey-patching Engine in order to test that code).
* **Unmanageable code** (Refactoring can be difficult when you have a hundred dependencies)

If you use a technique like Dependency Injection, making your singleton immutable, or passing dependencies by function parameter, you can reduce the dependency and make things easier to test, refactor, and manage.

---
Tags: javascript, game-loop
---


# Question
Title: What is the optimal way to update different entities in an engine?
**EDIT**: half of my question seemed to disappear, but thankfully, it was still in the clipboard.

*When I say entities, I mean instantiations of various classes in my engine (example class: `Engine.Animation`, or `Engine.Scene`). The language in question is Javascript.*

# The situation:

---

The current structure of my engine goes something like this:

```
// The single engine object that only stores constructor functions,
// aka classes (or at least it used to only store those).
Engine = {};

Engine.Scene = function()
{
    ...
}

```

Lets take the `Scene` class as an example... It basically stores all the information needed to render the visual part of the game state, which is done by the `Renderer` class (`renderer.render(scene, camera)`).

# The problem:

---

All worked well, but then I realized that the entities sometimes needed to be updated! The best (and, for now, the only) example of this is the `scene.AlphaDown()` method, which makes the scene transparent, "shuts it down", in a way.

I implemented this with the use of `setInterval` (the interval would call a function that used to lower the scene's alpha depending on how much time passed. This is the kind of "update method" I am talking about: the one that needs to be called iteratively, usually at 60FPS.) But, I was told that it was a bad practice (here and here). It was suggested to me that I use alternative ways of updating entities (without the use of `setInterval`).

# The possible solution:

---

I meant to have an array in `Engine`, called `toUpdate`, in which different entities would push their update methods. Then, the Engine would have a central `update()` method, which would calculate the time since last updated, and call the entities' registered update methods, giving that time as an argument. In the previous example with a `scene`, `AlphaDown()` would register an update method by pushing it into the `Engine.toUpdate` array. When the task of an update method (ie `scene.alpha = 0`) was completed, it would be removed from the `toUpdate` array.

# The problem with the solution:

---

This method has it's flaws, though. First, it would require the user to call `Engine.update()` on each of his game loop iterations. Then, it would make the global `Engine` object have methods, but I just want to keep it a namespace of some sort, a collection of useful classes. I don't want to dictate how a loop should be structured!

# The question:

---

Is my solution an acceptable way of updating entities? Are there some other, more standard ways? Should I strive to have my entities *not* have update methods that need to be iteratively called, and let the user implement them?

# Answer
Most of the time I've implemented two update types:

* A fixed update, which the entity could specify the update interval. (e.g. Once per second, or 5 times per second, etc...)
* A per-frame update.

The entity could register for either method, and if it did then the engine would put that entity into a list of entities to update, otherwise it was never updated. My entity manager class would then have the list of all entities, and a list of entities that receive updates, which is always a sub-set of the full list of entities.

It is certainly the case that many engines will have entities that can update every frame. This can be expensive, but only if you let it get out of hand. I've easily had a couple hundred entities updating every frame with no performance problems in some cases, but it will depend on how optimized your solution is and the platform you're running on.

How to architect a system to update entities (bear with me, I don't know Javascript, this is based on what I could learn in about 5 minutes, just now...):

```
Entity = {}

Entity = function() {
    var m_updateable = false;
    var m_updates_per_second = 0;  // Set to -1 if it should update per-frame
    var m_time_elapsed = 0.0;

    function set_updates( updates_per_second ) {
        m_updateable = true;
        m_updates_per_second = updates_per_second;
        notify_scene_mgr_updateable( self, true ); // Tell Scene Manager this entity is updateable now.
    }

    function set_not_updateable() {
        m_updateable = false;
        m_updates_per_second = 0;
        notify_scene_mgr_updateable( self, false ); // Tell Scene Manager this entity is no longer updateable.
    }

    // Returns 'true' if an update is needed.
    function needs_update( time_elapsed ) {
        if ( m_updates_per_second == -1 ) return true;

        m_time_elapsed = m_time_elapsed + time_elapsed;

        return ( m_time_elapsed > (1 / m_updates_per_second) );
    }

    // Called every frame if this entity is registered for per-frame updates
    function update( time_elapsed ) {
        // Do stuff here
    }

    // Called on an interval set by 'm_updates_per_second'
    function fixed_update( time_elapsed ) {
        m_time_elapsed = m_time_elapsed - time_elapsed;

        // Do stuff here
    }
}

SceneManager = {}

SceneManager = function() {
    var m_entities = [];
    var m_updateable_entities = [];

    function notify_scene_mgr_updateable( entity, is_updateable ) {
        if ( is_updateable ) {
            // If entity is not in m_updateable_entities, put them in that list
            m_updateable_entities.push(entity);
        } else {
            // If entity is in m_updateable_entities, remove them from that list
            m_updateable_entities.remove(entity);
        }
    }

    // Call this every frame
    function update_entities( time_elapsed ) {
        for(var i = 0; i < m_updateable_entities.length; i++){
            // Check if this entity needs an update
            if ( m_updateable_entities[i].needs_update( time_elapsed ) ) {
                // Does this entity get a per-frame update?
                if ( m_updateable_entities[i].m_updates_per_second == -1 ) {
                    // Do the per-frame update
                    m_updateable_entities[i].update( time_elapsed );
                } else {
                    // Do the fixed-interval update
                    m_updateable_entities[i].fixed_update( time_elapsed );
                }
            }

        }
    }
}

```
> 2 votes

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