We are about to switch to a new forum software. Until then we have removed the registration on this forum.
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;
}
}
Answers
https://Forum.Processing.org/two/discussion/24061/the-variable-does-not-exist
Speed is only used in move(). As it is, it is initialized as a local variable with a value of 5. You use it and then you change it. As soon as the function ends, this variable stops existing and any changes you do (as in line 31) are completely lost. If you make the variable global, the error will not get solve. You are still redefining the value of speed at the beginning of move(). The solution is to convert the variable so for it to have a global scope and also move line 27 to setup().
Kf
Ok got it. Thank you.