Remember, in the last section, how we created new variables and then used them to print out numbers and change colors? What else can we do? The better question is, why?
Let’s look at this example.
var redColor = 123;
var greenColor = 39;
var blueColor = 21;
var x = 100;
var y = 200;
var diameter = 50;
// this function is called only once
function setup()
{
createCanvas(800,600);
}
/* this function is called continuously
while the sketch is open in the browser
*/
function draw()
{
background(redColor,greenColor,blueColor);
circle(x,y,diameter);
}
Do you see your background with a circle? I hope so!
All the background color variables are interesting, but you are probably saying, “How is this any different from before?”;
Glad you asked! Let’s make a small change and see what happens.
var redColor = 123;
var greenColor = 39;
var blueColor = 21;
var x = 100;
var y = 200;
var diameter = 50;
// this function is called only once
function setup()
{
createCanvas(800,600);
}
/* this function is called continuously
while the sketch is open in the browser
*/
function draw()
{
background(redColor,greenColor,blueColor);
circle(x,y,diameter);
x++;
}
Run the above code and see what happens.
Did the circle move? Which way? Why?
What if we did the same to y? Which way would it go?
That is crazy! We just made a simple shape move. What if we added a second one?
var redColor = 123;
var greenColor = 39;
var blueColor = 21;
var x = 100;
var y = 200;
var diameter = 50;
// this function is called only once
function setup()
{
createCanvas(800,600);
}
/* this function is called continuously
while the sketch is open in the browser
*/
function draw()
{
background(redColor,greenColor,blueColor);
circle(x,y,diameter);
circle(x,y,diameter);
x++;
}
Do you get two circles? Oh dang! You don’t. You see only one.
Well, technically, you do, but you only get to see one because the other one is on top of the first one because they are at the same x,y coordinate, and the same diameter. How can I prove it to you? I know you are skeptics.
var redColor = 123;
var greenColor = 39;
var blueColor = 21;
var x = 100;
var y = 200;
var diameter = 50;
// this function is called only once
function setup()
{
createCanvas(800,600);
}
/* this function is called continuously
while the sketch is open in the browser
*/
function draw()
{
background(redColor,greenColor,blueColor);
fill(255);
circle(x,y,diameter);
fill(redColor,greenColor,blueColor);
circle(x,y,25);
x++;
}
What do you see? I kept the second circle in the same location, reduced the size, and gave it a color - that is what the fill does.
There you go! Okay, so if you let it run long enough, they should cruise right off the screen. But what if we don’t want that? What if I say, make it so that it stops at the edge. What are you doing to do?
Let’s go to the next section and find out!
See the Pen p5.js moving shapes by Michael Cassens (@retrog4m3r) on CodePen.