let circleX = 0

let circleY = 200

let circleD = 100

function setup() {

createCanvas(400, 400);

}

function draw() {

background(220);

circle(circleX,circleY,circleD)

circleX = circleX + 1

if(circleX == 400){

circleX = circleX - 1

}

}

let circleX = 0

let circleY = 200

let circleD = 100

function setup() {

createCanvas(400, 400);

}

function draw() {

background(220);

circle(circleX,circleY,circleD)

circleX = circleX + 1

if(circleX == 400){

circleX = circleX - 1

}

}

Because you only decrement `circleX`

when it is exactly 400 this code will result in the circle oscillating between 399 and 400 forever once it reaches 400.

What you probably want to do is store the horizontal velocity in a variable:

```
let xVelocity = 1;
```

Then use that instead of the constant when updating `circleX`

, and in your if block, change the sign of that variable:

```
circleX = circleX + xVelocity;
if (circleX >= 400) {
xVelocity = xVelocity * -1;
}
```

However, there are numerous additional cases to handle in order to simulate a bouncing ball. I’ve written a detailed tutorial on the topic:

4 Likes

thanks for the help but that’s not what I exactly needed. i don’t really understand these stuff I tried to make it add 1 to the x until it reaches 400 or 375 and then remove -1 so that It can go back to the starting point

I realize the tutorial I provided covers so more advanced stuff and it may take some time to understand. But for your very simple use case I did provide a solution in my initial code blocks.

2 Likes