In the alternative display function (see below), a variable “y” is used. This variable would have to be declared in the main program in order for the sketch to function properly. A working sketch would look like:
// Declare all global variables (stays the same)
int x = 0;
int y = 100;  // y needs to be declared!
int speed = 1;

// Setup does not change
void setup() {
  size(200,200);
  smooth();
}

void draw() {
  background(255);
  move();
  bounce();
  display();
}

// A function to move the ball
void move() {
  // Change the x location by speed
  x = x + speed;
}

// A function to bounce the ball
void bounce() {
  // If we've reached an edge, reverse speed
  if ((x > width) || (x < 0)) {
    speed = speed * -1;
  }
}

void display() {
  background(255);
  rectMode(CENTER);
  noFill();
  stroke(0);
  rect(x,y,32,32);
  fill(255);
  rect(x-4,y-4,4,4);
  rect(x+4,y-4,4,4);
  line(x-4,y+4,x+4,y+4);
}


»

No comments yet.

Leave a comment