Make Your Game Smooth

Smoothing is probably the single easiest way to add a layer of polish to almost any game. In practice, it's so simple to apply that it's sad to see when game developers leave it out. I've used this technique in one form or another in almost every game I've written. Take a look at the video below. We are doing the same kind of game logic, a snake following a point, only on the right hand side we are easing the position of the snake's head making the movement smoother.

So how does this work? First we need a filter function. The filter function can blend two values together. It blends them using a filter factor; a value from 0 to 1 that balances the influence of the two values we are blending. For instance, a 0 will make the function return the first value, a 1 will return the second value, and 0.5 will return the average of the two values. This is what our filter function looks like:

float filterf (float a, float b, float filterFactor)
    return (a * (1-filterFactor)) + b * filterFactor;

Now we just have to add this in our game. The easiest way to do this is at a fixed time step. The target position can be calculated at any interval, such as based on user input. Instead of immediately applying the new target position we first blend the value with the old position of our object. In SpriteBuilder this would look something like this:

// The new position we've calculated before blending
CGPoint target = [self calcNewPosition];

// The filter factor
float filterFactor = 0.1;

// Save the old position
CGPoint oldPosition = mySprite.position;

// Filter the target with the old position
float newPosX = filterf(oldPosition.x, target.x, filterFactor);
float newPosY = filterf(oldPosition.y, target.y, filterFactor);

mySprite.position = ccp(newPosX, newPosY);

There really isn't anything more to this neat little trick! The challenge is finding out where it's good to use. Typically, it's great to use when converting user input to game play. One example is if you want to move a space ship to the point where the player touched. Another is when you scroll the screen to follow an object and want it to feel really smooth.

Viktor Lidholt1 Comment