These advertisements helps me to keep writing articles on this website

Create a gameloop with an update function in P5.js

Would you like to see smooth animation in P5? If you update your game object positions in the draw function, you have to know how many time has passed since the last frame. After reading this article, you know how to use the system variable deltaTime to create smooth animations.


The example you see here is an animated gif and does not do the animation justice. I recommend trying the code on your machine to see how smooth the animation is.

Update and render

A game engine like Unity has two major functions in game objects:

  1. Update
  2. Render

The update function is called for you by the framework with the argument dateTime. DateTime is the time that has past since drawing the last frame. This magic value will help you to calculate exactly where you game objects are supposed to be.

P5 has no update function

In the P5 examples, position updating happens in the draw-function. In the example below, I create an update function and call it from draw. In the update function, I update the angle (which is used to calculate my game object positions) and use deltaTime:

let angle = 0;
function update() {
  angle += deltaTime * .008;

function draw() {

You can also update the game object positions in the draw function of course. I created an update function to mimic other game engines and to create a clear separation for updating and rendering.

Try the code

You can find the code on github.

Written by Loek van den Ouweland on February 14, 2021. Questions regarding this artice? You can send them to the address below.
By using this site, you acknowledge that you have read and understand our Cookie and Privacy Policy.