# Ball Moving Along the Screen Similar to the Game Pong

**URL:** <https://discourse.processing.org/t/ball-moving-along-the-screen-similar-to-the-game-pong/33388>\
**Category:** Coding Questions\
**Created:** [November 7, 2021, 8:45pm UTC](https://discourse.processing.org/t/ball-moving-along-the-screen-similar-to-the-game-pong/33388 "2021-11-07T20:45:08Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Chels](https://avatars.discourse-cdn.com/v4/letter/c/c68b51/32.png) [@Chels](https://discourse.processing.org/u/Chels)\
**Post date:** [November 7, 2021, 8:45pm UTC](https://discourse.processing.org/t/ball-moving-along-the-screen-similar-to-the-game-pong/33388/1 "2021-11-07T20:45:08Z")

</div>

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](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;  
}

}

---

<div class="post-metadata">

**Author:** ![Chrisir](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/chrisir/32/45_2.png) [@Chrisir](https://discourse.processing.org/u/Chrisir)\
**Post date:** [November 7, 2021, 9:25pm UTC](https://discourse.processing.org/t/ball-moving-along-the-screen-similar-to-the-game-pong/33388/2 "2021-11-07T21:25:21Z")

</div>

> [@Chels](#):
>
> window at a random angle

For example

```auto

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

```

put this in setup()

---

<div class="post-metadata">

**Author:** ![Chrisir](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/chrisir/32/45_2.png) [@Chrisir](https://discourse.processing.org/u/Chrisir)\
**Post date:** [November 7, 2021, 9:36pm UTC](https://discourse.processing.org/t/ball-moving-along-the-screen-similar-to-the-game-pong/33388/3 "2021-11-07T21:36:59Z")

</div>

> [@Chels](#):
>
> once it hits the right side, it restarts on the left side

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

```auto

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

```
