trail following the mouse
in
Programming Questions
•
1 year ago
Hi,
I'm currently having a hard time understanding an array example from the book "Learning Procesing: A Beginner's Guide to Programming" by Daniel Shiffman.
The task is to make a programm so that the mouse will leave a trail of 50 circles behind. Here is the example code from the book:
I'm currently having a hard time understanding an array example from the book "Learning Procesing: A Beginner's Guide to Programming" by Daniel Shiffman.
The task is to make a programm so that the mouse will leave a trail of 50 circles behind. Here is the example code from the book:
- // Daniel Shiffman
// http://www.learningprocessing.com
// Example 9-8: A snake following the mouse
// Declare two arrays with 50 elements.
int[] xpos = new int[50];
int[] ypos = new int[50];
void setup() {
size(200,200);
frameRate(1);
smooth();
// Initialize all elements of each array to zero.
for (int i = 0; i < xpos.length; i ++ ) {
xpos[i] = 0;
ypos[i] = 0;
}
}
void draw() {
background(255);
// Shift array values
for (int i = 0; i < xpos.length-1; i ++ ) {
// Shift all elements down one spot.
// xpos[0] = xpos[1], xpos[1] = xpos = [2], and so on. Stop at the second to last element.
xpos[i] = xpos[i+1];
ypos[i] = ypos[i+1];
}
// New location
xpos[xpos.length-1] = mouseX; // Update the last spot in the array with the mouse location.
ypos[ypos.length-1] = mouseY;
// Draw everything
for (int i = 0; i < xpos.length; i ++ ) {
// Draw an ellipse for each element in the arrays.
// Color and size are tied to the loop's counter: i.
noStroke();
fill(255-i*5);
ellipse(xpos[i],ypos[i],i,i);
}
println(xpos[48]);
}
In the book it says that you have to shift the array down one step, which makes sense, so the last mouse location on xpos[49] becomes xpos[48] each time it loops through draw().
But the code does otherwhise, shifting from xpos[48] to xpos[49] (xpos[i] = xpos[i+1];). It counts up not down.This way all elements except xpos[49]=mousex would have the value 0 as initialised in the loop inside setup(), wouldn't it? Probably not, because the code works.
But the code does otherwhise, shifting from xpos[48] to xpos[49] (xpos[i] = xpos[i+1];). It counts up not down.This way all elements except xpos[49]=mousex would have the value 0 as initialised in the loop inside setup(), wouldn't it? Probably not, because the code works.
1