Ball Moving Along the Screen Similar to the Game Pong

I’m fairly new to processing. So I searched up the Coding Train channel on YouTube and changed a bit of a code to not have the bouncing ball get cut out the window when it runs.

Source: https://www.youtube.com/watch?v=YcbcfkLzgvs&list=PLRqwX-V7Uu6bb7z2IJaTlzwzIg_5yvL4i&index=1

Anyway, I need some help with making the ball start from the left side, have the ball move to the right side of the window at a random angle, and once it hits the right side, it restarts on the left side and starts moving at a different random angle.

Here’s my code:

float x = 10;
float y = 10;
float xspeed =4;
float yspeed = 1.5;

void setup () {
size(600, 600);

}

void draw() {
background(0);
stroke(0);
fill(255);
ellipse(x +10, y +10, 20, 20);

x = x+ xspeed;
y = y+yspeed;

if (x > width - 20 || x < 0) {
xspeed = xspeed * - 1;
}

if (y > height - 20 || y < 0){
yspeed = yspeed * - 1;
}

}

For example


 xspeed = random(1.3, 4);
 yspeed = random(0.3, 4);

put this in setup()

3 Likes

Here you need to check the xpos against the width and
then reset the values


if (x > width - 20) {
 x=10;
 y=10;
 xspeed=…;
 yspeed=…;
}
3 Likes