onEachFrame is used for creating a 'mainloop'. This is a section of code which will repeat, at approximately 60 frames per second, forever. This loop is where you place your game update and drawing code, which is run on every frame.
You need to use this function for a main loop instead of a while loop because a while loop will block the browser from rendering. This also performs some internal book keeping, and other background magic, such as pausing.
// update my game
// draw my game
A circle is drawn underneath the mouse, and follows it around the screen.
// The code inside this do block is run each frame
fill( :black )
controls = getControls()
setColor( :green )
fillCircle( controls.getMouseX(), controls.getMouseY(),
64, 64, true )
There are two optional parameters that your main game can take.
First is the 'delta' time, this is a multiplier for normalizing a game's speed across multiple systems. On different PC's your game will run at a different frame rate, and delta time is a multiplier which accounts for this. Just multiple any speed values by this, and it will correct for speed differences for you.
The second, 'millis', is the number of milliseconds that the previous frame took to execute.
// Moves a square across the screen,
// using delta time to help normalize it's speed.
x = 0
speed = 6
onEachFrame() do |delta|
fill( :black )
x = x + speed*delta
x = x % getScreenWidth()
setColor( :yellow )
fillRect( x, 100, 18, 18, true )