Handmade Web Games

Chapter 10

Game feel and juice

How to make your game feel good.

Juice?

Juice is the feedback that makes a game feel alive and satisfying to play. It's often a variety of techniques, like visual cues, sound effects, and haptic feedback. Done well, juice makes your game more immersive, interesting, and intuitive. Remember to not overdo it.

Camera shake is like salt.

In this chapter, we'll introduce particle effects, screen shake, and hit stop—all parts of our juiced pong demo above.

Visual feedback

Anticipation

(todo)

Squash and stretch on impact

Squash & stretch is the first of Disney's 12 principles of animation [Wikipedia], and it's an effective way to breathe some life into otherwise lifeless objects. Despite our "character" here being nothing but a blue square, a very simple squash & stretch effect gives it a physical presence and liveliness. We'll expand on the technique introduced in Chapter 4 below.

Click to focus. WASD / arrows to move and squash.

Code for squash and stretch

To apply squash and stretch we'll extend the player state with scale factors:

const  = {
  : {
    : 200, // center of player X coord
    : 0, // x velocity
    : 1, 
    : 1, 
  },
  : [22, 354],
};

On impact, set the scale from the impact speed, then ease back toward 1 each tick with the exponential decay function from Chapter 4:

function (: number) {
  const {  } = ;
  const  = ();

  if ( > 0) {
    const  = ();
    . = 1 - ;
    . = 1 + ;
  }

  const  = 8;
  . = (., 1, , );
  . = (., 1, , );
}

Finally, draw using the scaled size and ensure that the player stays flush against each wall while squashed.

function (: CanvasRenderingContext2D) {
  ();
  (, .);
  (, );
}

function (: CanvasRenderingContext2D, : ) {
  const { ,  } = ;
  const [, ] = ;
  const  =  * .;
  const  =  * .;

  // compute whether the player is pressed against a wall
  const  =  / 2;
  const  = . ===  + ;
  const  = . ===  - ;

  // offset the draw so that the player hugs the wall
  let  = 0;
  if ()  = ( - ) / 2;
  if ()  = ( - ) / 2;

  const  = . -  / 2 + ;
  .(,  - , ,  + 1);
}

Screen shake

In Chapter 6, we showed that adding screen shake is as simple as adding a few transforms when rendering your game. There are two main techniques for screen shake.

One is to bump the camera in a single direction, then ease back to its true position.

Click to focus. WASD / arrows to move.

Strength5.0
Code for camera bump

To do this we'll extend our camera state to include x/y offsets for the camera bump:

const  = {
  : {
    : 0,
    : 0,
    : 1,
    : { : 0, : 0 }, 
  },
};

Then bumping the camera is as simple as incrementing those offsets:

function (: number, : number) {
  ... += ;
  ... += ;
}

Each tick, we will ease the camera back to its starting position using the exponential decay function from Chapter 4.

function (: number) {
  const  = 8; // (you can tune this)
  ... = (..., 0, , );
  ... = (..., 0, , );
  //                        from ^                 to ^
}

Finally, actually apply the offset when handling the camera position translation:

function (
  : CanvasRenderingContext2D,
  : { : number; : number },
  : {
    : number;
    : number;
    : number;
    : { : number; : number };
  },
  : () => void,
) {
  .();
  .(. / 2, . / 2);
  .(., .);
  .(
    -(. + ..),
    -(. + ..),
  );
  ();
  .();
}

That's it for the first type of screen shake!

That first type of screen shake works well for directional impacts, but lacks heaviness. We can add more weight to it. The other type we'll look at rumbles the entire view over a period of time. For things like explosions where directionality matters less than the overall impact, it's a great way to add juice. (The two approaches can of course be combined for a directional bump with some aftershock rumbling.)

Click to focus. WASD / arrows to move.

Strength10.0
Code for rumble shake

Like before, we'll start by defining the state for this screen shake:

const  = {
  : 0, 
  : {
    : 0,
    : 0,
    : 1,
    : {
      : 0, 
    }, 
  },
};

Then increment the state.camera.shake.factor whenever you want to trigger screen shake, and decay each tick like before.

function (: number) {
  ... += ;
}

function (: number) {
  const  = 8;
  . += ;
  ... = (..., 0, , );
}

state.time will be the clock we use as the input for the sine and cosine waves that create the shake effect—just like you saw in Chapter 5.

The 52 and 56 below are arbitrary frequency multipliers that tune how fast the view jitters on each axis. The numbers need to be close enough that the motion isn't noticeably faster in one direction, but not so close that they start forming circles.

function (
  : CanvasRenderingContext2D,
  : { : number; : number },
  : {
    : number;
    : number;
    : number;
    : { : number };
  },
  : number,
  : () => void,
) {
  const  = .( * 52) * ..;
  const  = .( * 56) * ..;

  .();
  .(. / 2, . / 2);
  .(., .);
  .(
    -(. + ),
    -(. + ),
  );
  ();
  .();
}

More impact juice

In addition to screen shake there are a variety of other ways to make in-game impacts juicier.

  1. Hit stop (freeze on impact)

(todo: example code adding simulated pause time to the accumulator)

  1. Hit marks (eg. flash on impact, blood/damage, etc)
  2. Knockback
  3. Slow motion

(todo)

Particles

Particle effects are another great way to add juice to your games. Impact sparks, smoke, tire dust, muzzle flashes, blood splats, water spray, jump clouds, explosions, fire, vehicle exhaust, and ambient weather like rain or snowfall can all be implemented with particle emitters. So can fire and smoke emissions from a rocket:

Click to focus. WASD or arrow keys to move.

This is the code that got me excited about particle effects and how simple they can be to create. It's adapted from The Transmitter, a submission to the Ludum Dare 59 game jam by @onsclom, who helped with this guide.

The basic technique is to start with some state similar to our bouncing ball from Chapter 4.

const particle = {
  x: 0,
  y: 0,
  vx: 0,
  vy: 0,
  age: 0,
  life: 0,
  // plus any other properties you want...
  color: "orange",
  fromSize: 10,
  toSize: 0,
  fromOpacity: 1,
  toOpacity: 0,
};

The main new concepts here are age and life.

  • age ticks up with dt once per update
  • life is how long the particle lasts
  • when age >= life we skip updating and rendering
  • any from* and to* values are lerped using t = age / life

The state from this particle provides settings for size and opacity changes over the particle's life, but you can add anything you want to it. Maybe you want to be able to transition the colors, add rotation speed, use a non-linear easing curve—when you define your own particle system, you decide exactly what goes into it.

Using this state, let's spawn some particles.

A single particle

We'll start by emitting just one particle on an interval from the center of the canvas. This code should look familiar if you followed Chapter 4's bouncing ball demo.

You'll notice we're using the variable frame-rate update function rather than fixedUpdate since particles tend to be used for visual flair rather than for game logic that requires fixed time steps. This means we can avoid updating the particles' positions more frequently than they're rendered.

const state = {
  emitter: {
    x: bounds.width / 2,
    y: bounds.height / 2,
  },
  interval: 1.3, // seconds
  time: 0,
  particle: {
    x: 0,
    y: 0,
    vx: 0,
    vy: 0,
    age: 0,
    life: 0,
  },
};

Lerp size and opacity

Next we'll add a few properties to allow us to transition the size and opacity of the particle over the course of its life. Here we're animating the size and opacity, but you can update any properties you want or even derive them without adding state.

const state = {
  emitter: {
    x: bounds.width / 2,
    y: bounds.height / 2,
  },
  interval: 1.3, // seconds
  time: 0,
  particle: {
    x: 0,
    y: 0,
    vx: 0,
    vy: 0,
    age: 0,
    life: 0,
    fromSize: 8, 
    toSize: 0, 
    fromOpacity: 1, 
    toOpacity: 0, 
  },
};

Lots of particles

To support more than one particle, we'll first change our state to expect an array of particle objects rather than just one object.

const state = {
...
particle: { ... },
particles: [],
};

From there you could push objects to add particles and filter or splice the array to remove them, but we have a better option.

Because they're small and ubiquitous, it's easy to end up with thousands of particles on screen. Assuming updates run at 120fps, that could involve hundreds of thousands of object allocations and dynamic array resizes per second. That can be a problem when the browser decides it is time to run the garbage collector [Wikipedia] (GC). If it takes too long to collect and free unused objects, you may drop a frame or two periodically.

We'll mitigate this issue by creating our particles up front. The idea is to preallocate one big array for all the particles you could ever need, and generate the objects in it just once. We'll then recycle any no-longer-visible objects for new particles rather than allocating new ones. This approach, called a ring buffer or circular buffer [Wikipedia], is an optimization. So far in this guide we've been fairly oblivious to performance concerns, but when you might be spawning thousands of particles 120 times per second, particle emitter code is likely to be the hottest loop in your game logic. The ring buffer reduces potential dropped frames that can happen during garbage collection by preventing said "garbage" from being created in the first place. Operations like .filter or .map and building new objects all allocate new memory that needs to be cleaned up by the GC. By making a fixed-size array with all the particle objects in it up front we eliminate that work for the GC entirely.

Is this premature optimization?

Our benchmark aims to answer that question.

In my browser, the benchmark shows that a ring buffer ensures relatively stable update times whereas a push + filter approach occasionally slows down during GC—at least, for very high particle counts. Most small games don't need the number of particles required to really see the difference here, though. That being said, the more memory your game uses, the slower garbage collection gets. So what might be negligible GC time when you're starting out your project could result in many dropped frames as your code grows in complexity later on. Tracing sources of slow GC is arguably way harder than using a ring buffer, so I'd say that this is a worthwhile optimization to include.

I will note two minor inconveniences with the ring buffer approach, though: (1) you need to estimate a reasonable upper bound on the total particles up-front, and (2) you need to clear out stale properties when you initialize a new particle.

If you'd like to learn more about how V8's Orinoco garbage collector works, Playing with Garbage [YouTube] by SimonDev provides a great rundown.

Even better performance with packed object pools

One problem with using a ring buffer for particle systems is that you have to iterate through the entire buffer every frame, even if you aren't displaying any particles. That's wasteful.

Slots checked every frame

Another option is to keep the fixed-size array, but partition it so that all of the "alive" particles stay packed together. Then when you update and render the particles, you only need to iterate over the ones actually being shown. All of the dead particles to the right of the moving partition can be ignored.

Slots checked every frame

This is known as a packed object pool. The implementation is fairly simple:

  1. Keep a count of the live particles. That count is also the index of the first free slot when there's room to emit.
  2. When you emit a particle, reset the particle in the first free slot and increment the count.
  3. When a particle dies, swap it with the last live particle and decrement the count.
Ring buffer
function () {
  const { ,  } = ;
  ([]);
  . = ( + 1) % .;
}
Packed object pool
function () {
  const { ,  } = ;

  if ( === .) {
    return;
  }

  ([]);
  .++;
}
const state = {
  emitter: {
    x: bounds.width / 2,
    y: bounds.height / 2,
  },
  interval: 0.06, // seconds
  time: 0,
  particles: Array.from({ length: 50 }, () => ({
    x: 0, 
    y: 0, 
    vx: 0, 
    vy: 0, 
    age: 0, 
    life: 0, 
    fromSize: 0, 
    toSize: 0, 
    fromOpacity: 0, 
    toOpacity: 0, 
  })), 
  next: 0, // index of next particle to use
};

Blend modes

Additive blend modes, like "lighter", are often used for fire and sparks since they make overlapping particles brighter. We'll increase the number of particles on screen to highlight the effect.

(This is one of those tricks to use in moderation. Overuse of additive blend modes for effects can look unrefined. A chapter on juice must also be a chapter on restraint.)

const state = {
  emitter: {
    x: bounds.width / 2,
    y: bounds.height / 2,
  },
  interval: 0.005, // seconds
  time: 0,
  particles: Array.from({ length: 300 }, () => ({
    x: 0,
    y: 0,
    vx: 0,
    vy: 0,
    age: 0,
    life: 0,
    fromSize: 0,
    toSize: 0,
    fromOpacity: 0,
    toOpacity: 0,
  })),
  next: 0, // index of next particle to use
};

Smoke, steam, and gasses

Taking additive blending further, if you soften the edges of each particle you can make simple particle systems look like gasses and other fluids without complex simulations.

For example, to create a soft-edged particle we can create a radial gradient like this:

function (
  : CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,
  : string,
   = 32,
) {
  const  = .(, , 0, , , );
  .(0, );
  .(1, `rgb(from ${} r g b / 0)`); // a 0%-opacity version of our input color
  . = ;
  .(0, 0,  * 2,  * 2);
}
Aside: why rgb(from...) instead of transparent?

Because transparent means transparent black. If we use it as a color stop then our gradient's colors will also shift towards black.

Thankfully there is a new relative color syntax that allows us to take any input color, convert it to rgb, and then change only its opacity.

transparent
rgb(from …)
.(1, "transparent");
.(1, `rgb(from ${} r g b / 0)`);

And since we might be rendering it thousands of times per second, we can cache our gradient texture in an OffscreenCanvas for better performance.

function (: string,  = 64) {
  const  = new (, );
  const  = .("2d")!;
  (, ,  / 2);
  return ;
}

Then the only change we need to make to our particle emitter is to draw our texture instead of a square:

function () {
  // ...
  .(, , , );
  .(, , , , );
}

(I've also halved the speed and increased the size per particle in this demo.)

const texture = createParticleTexture("#ffaa3c"); // create once to reuse for every particle

const state = {
  emitter: {
    x: bounds.width / 2,
    y: bounds.height / 2,
  },
  interval: 0.005, // seconds
  time: 0,
  particles: Array.from({ length: 300 }, () => ({
    x: 0,
    y: 0,
    vx: 0,
    vy: 0,
    age: 0,
    life: 0,
    fromSize: 0,
    toSize: 0,
    fromOpacity: 0,
    toOpacity: 0,
  })),
  next: 0, // index of next particle to use
};

Particle playground

Particle settings
Color

Game feel

Variable jump height

{Placeholder}

Click or press space to jump. (Hold to jump higher.)

function (: number) {
  if ( && .) {
    . = -500;
    . = false;
    . = true;
  }

  if (. && ! && . < 0) {
    . *= 0.5;
    . = false;
  }

  ();
}

Input buffering

Imagine you're playing a platformer and you're about to land on a platform. If you press Space to jump even just a millisecond before landing, without input buffering your character will not jump—frustrating! Input buffering allows us to queue up an input to replay as soon as the player is eligible for it, within some window of time.

Jumping without input buffering

We'll start with a jump demo similar to the one from Chapter 7.

Try timing your jumps to the exact moment you hit the ground. Without the little bit grace provided by input buffering, if you ever undershoot the timing it will feel like the game ignored your input.

const size = 30;
const groundY = bounds.height - 20;

const state = {
  justPressed: new Set<string>(),
  box: {
    x: 50,
    y: groundY - size,
    vy: 0, // y velocity in px/s
  },
};

Buffering jump input

Now we'll add an 80ms jump buffer. It should feel a little more forgiving.

const size = 30;
const groundY = bounds.height - 20;
const jumpBufferTime = 0.08; 

const state = {
  justPressed: new Set<string>(),
  jumpBuffer: 0, 
  box: {
    x: 50,
    y: groundY - size,
    vy: 0, // y velocity in px/s
  },
};

Coyote time

Input buffering adds forgiveness when entering a location that's eligible for an input. Coyote time adds forgiveness when exiting. So, back to our platformer example: if you run off a platform and try to jump, you should still be able to jump even if that jump is triggered a few pixels off the edge of the platform.

Without coyote time

function (: number) {
  if ( && .) {
    . = -500;
    . = false;
  }
}

With coyote time

function (: number) {
  . -= ;
  if (.) . = 0.1;

  if ( && . > 0) {
    . = -500;
    . = false;
    . = 0;
  }
}

These are just a few of many techniques that can improve game feel, especially for platforming games. I highly recommend Celeste & Forgiveness and the interactive Platformer Toolkit for more.

Haptic feedback

If you've added controller support, then you can deliver touch feedback through controller haptics. (And if you haven't yet added controller support, you should! It's fun and easy—see Chapter 8.) Haptics provide a low-effort way to increase the immersiveness of your game through tactile feedback.

Audio feedback

Some basic tips when providing audio feedback in games:

  • Randomize the pitch or speed of repetitive sounds, or loop through several audio samples. (Or both!)
  • If you have overlapping sounds, run them through a compressor so the total volume doesn't grow too high.
  • Play sounds for state changes and collisions, especially when triggered by the player. Even hover effects deserve subtle audio cues.

See also

https://garden.bradwoods.io/notes/design/juice

https://www.youtube.com/watch?v=Fy0aCDmgnxg - juice it or lose it

https://www.youtube.com/watch?v=AJdEqssNZ-U - the art of screen shake

in some other chapter—tile maps: https://developer.mozilla.org/en-US/docs/Games/Techniques/Tilemaps

Masahiro Sakurai on screen shake, animation, explosions, hit marks, sfx volume, and hit stop.

On this page