[SOLVED] Code not working for a strange reason

i have wrote a simple code that supposed to make a ball bounce aroud the screen so what`s happening is that the if,elseif and else statment are getting followed in the case of the width but not the heigth

if someone can copy the code into processing an figure out the problem it would be appreciated
the code:

float circleX = 0;
float circleY = 180;
float xChanger = 0;
float yChanger = 0;

void setup() {
  size(640, 360);
}

void draw() {
  background(50);
  fill(250);
  ellipse(circleX, circleY, 24, 24);
  if (circleX == width) {
    xChanger = -5;
    yChanger = -2.8;
    println("x = 640");
  } else if (circleY == 0) {
    xChanger = -5;
    yChanger = 2.8;
    println("y = 0");
  } else if (circleX == 0) {
    xChanger = 5;
    yChanger = 2.8;
    println("x = 0");
  } else if (circleY == height) {
    xChanger = 5;
    yChanger = -2.8;
    println("y = 360");
  }

  circleX = circleX + xChanger;
  circleY = circleY + yChanger;
}
1 Like

The problem is the statements inside of your if statements.

For example, let’s look at if (circleY == height) ... and what it does as circleY changes over time.
So, let’s assume that yChanger is 2.8.

The last statement inside draw() changes circleY every single time. So, it sets it from 0 to 2.8, then to 5.6, then to 8.3, 11.2, 14.0, …, 355.6, 358.4, 361.2

In other words, with 2.8 added to circleY, it jumps from 358.4 to 361.2 and then grows ever bigger, and is never equal to exactly 360.

The solution for this is to use “less than or equal” or “more than or equal” comparisons, instead of just equal, i.e. >= and <= instead of just ==.

Here’s your code with that solution in place:

float circleX = 0;
float circleY = 180;
float xChanger = 0;
float yChanger = 0;

void setup() {
size(640, 360);
}

void draw() {
background(50);
fill(250);
ellipse(circleX, circleY, 24, 24);
if (circleX >= width) {
xChanger = -5;
yChanger = -2.8;
println(“x = 640”);
} else if (circleY <= 0) {
xChanger = -5;
yChanger = 2.8;
println(“y = 0”);
} else if (circleX <= 0) {
xChanger = 5;
yChanger = 2.8;
println(“x = 0”);
} else if (circleY >= height) {
xChanger = 5;
yChanger = -2.8;
println(“y = 360”);
}

circleX = circleX + xChanger;
circleY = circleY + yChanger;
}
1 Like

oh yeah i got it thank you for your help <3