Screen Shake in PICO-8

 

Here is a simple screen shake function which can easily be added to your PICO-8 projects.

The principle uses the camera which is well explained here.  In essence, the camera moves a window around the draw area resulting in everything on screen being shifted by a certain amount (importantly, although not for this, the camera offset is subtracted to any draw coordinates).

Initially we set a variable (offset) which represent the multiple of camera offset (bigger is more shake).  This variable should be declared at the very beginning of your program (either in _init or before).  What is important is offset is global in scope.

offset=0

Next we need the function that will do the shaking.  I call this function screen_shake() and it works by slowly decreasing the offset value towards 0.  Every time this function is called (once per draw cycle) two random offsets are generated (offset_x, offset_y) and these values is multiplied by offset (which is decreasing, remember) and applied to the camera.

function screen_shake()
  local fade = 0.95
  local offset_x=16-rnd(32)
  local offset_y=16-rnd(32)

  offset_x*=offset
  offset_y*=offset
  
  camera(offset_x,offset_y)

  offset*=fade
  if offset<0.05 then
    offset=0
  end
end

In order for the shake to work, the screen_shake() function is placed at the start of any _draw() calls your program may have.

function _draw()
  screen_shake()

  --
  -- stuff is drawn here, but by a slowly decreasing offset
  --
 end

To create a screen shake all that is needed is to set the offset variable in the _update() function.

offset=1.5

Play around with the various variables to get just the shake you are looking for.

Happy programming!

You May Also Like

About the Author: Doc Robs

Leave a Reply

Your email address will not be published. Required fields are marked *