Watch Variables in p5.js (Make your own)
You can create your own variables!
- Up to now we have only written function calls. To declare a variable we write a new kind of statement – an assignment operator.
- var circleX = 10;
- This means declare a variable named circleX and assign it the value of 10.
- If you place this statement at the top of the page it will be available to all of the functions that follow. That make it a global variable.
- If you place this statement within a function, it will only be available to that function. That makes it a local variable.
We declared and initialized the variable but it doesn’t do anything yet.
We substitute the hard coded 10 with the variable name. But it still doesn’t do anything. We need to find a way to change it with each call to draw().
Example 2.2.1: How can we change the variable? We change it by assigning the variable a new value – the old value + 1. That is, we increment the variable. Now it moves to the right!
Example 2.2.2: We can change the color and position at the same time.
Example 2.2.3: or the color,position, and size at the same time.
Example 2.2.4: We can make any object move - like rectangles.
Exercise 2.2a: Use mousePressed() to draw as set of circles.
Exercise 2.2b: Use draw() to dynamically draw the function.
Exercise 2.2c: The following lines intersect at the rectangle and should follow the mouse coordinates.
Exercise 2.2d: The following lines intersect at the rectangle and should follow the mouse coordinates.
Exercise 2.2e: The ellipse should follow the mouse coordinates and show those coordinates.