Reading:
The best way to learn programming is to program, and one good way to do this is to play with the examples shown in the text. You can download the sample code and run it in your own environment. Here are some ideas of what you can try.
Consider the following code segment, taken directly from the last example in Section 4.2.1:
int ballX, ballY; // the location of the ball void setup() { size(200, 100); // Start the ball in the upper left. ballX = 25; ballY = 25; } void draw() { // Erase the ball at the previous location. background(220); // Draw the ball at the current location. stroke(0); fill(255); ellipse(ballX, ballY, 25, 25); // Move the ball to the right. // Note that this is the same as saying ballX = ballX + 2. ballX += 2; }
background(220)
statement from the draw()
method up
to the end of the setup()
method (i.e., right after the ballY = 25;
before the closing }
)?
Why does this happen? Can you move any of the other statements in draw()
to setup()
without messing up the animation? Why or why not?
ballX += 1
? Why?
void setup() { size(200, 200); background(220); } void draw() { } void keyPressed() { ellipse(100, 100, 25, 25); }
print()
command useful, which works like println()
without including a new-line
character.
final float FOLLOW_FACTOR = 0.1; int ballX, ballY; void setup() { size(200, 200); background(220); ballX = 100; ballY = 100; } void draw() { ellipse(ballX, ballY, 25, 25); } void mouseDragged() { ballX += (mouseX - ballX) * FOLLOW_FACTOR; ballY += (mouseY - ballY) * FOLLOW_FACTOR; } void mouseReleased() { stop(); }