3:2 Using a variable to do something in p5.js

We can make things move, change size and do much more with variables. Instead of putting in set values for a circles position, we might use variables to hold that value. Then we can modify the variable.

Storing the x position

We will modify the x position of our circle we made in a previous tutorial. So lets think of a useful name for the variable.

I could be called anything, but as its modifying the x position lets call it xPosition. So put this at the very top of your code:

let xPosition = 0;

Moving the circle

By changing the variable we can move the circle.

The draw function runs the code inside it 60 times per second so lets add something to the variable there to change it repeatedly and animate the circle:

This code will add 1 to xPosition:

xPosition = xPosition + 1;

However we can do exaclty the same thing with more consise code (this does the same thing:

xPosition += 1

See it in action in the example.