Global and local scoped variables.

Hi I'm new. Could someone please explain why if I declare my 'speed' variable locally inside my 'move' method the condition for the ball to bounce off the width of the window does not work. The x = x + speed obviously works to start the ball rolling but the speed = speed * -1 does not seem to be recognised when I declare the 'speed' variable locally. If I declare the 'speed' variable globally everything works as expected. I was under the impression declaring local variables was better than declaring globally wherever possible and seeing the 'speed' variable is only used in the one method I can't see why the ball doesn't bounce back when I declare it inside the 'move' method.

float x, y;
float dia;

void setup() {
  size(800, 800);
  smooth(4);
  background(0);

  dia = 50;
  x = 50;
  y = height/2;
}

void draw() {
  background(0);
  display();
  move();
}

void display() {
  noStroke();
  rectMode(CENTER);
  ellipse(x, y, dia, dia);
}

void move() {
  float speed = 5;  
  x = x + speed;

  if (x > width - dia/2 || x < 0) {
    speed = speed * -1;
  }
}
Tagged:

Answers

Sign In or Register to comment.