# How to bounce a ball off a randomly generated line?

**URL:** <https://discourse.processing.org/t/how-to-bounce-a-ball-off-a-randomly-generated-line/26379>\
**Category:** Coding Questions\
**Created:** [December 19, 2020, 11:01am UTC](https://discourse.processing.org/t/how-to-bounce-a-ball-off-a-randomly-generated-line/26379 "2020-12-19T11:01:20Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![CodeMasterX](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/codemasterx/32/2942_2.png) [@CodeMasterX](https://discourse.processing.org/u/CodeMasterX)\
**Post date:** [December 19, 2020, 11:01am UTC](https://discourse.processing.org/t/how-to-bounce-a-ball-off-a-randomly-generated-line/26379/1 "2020-12-19T11:01:20Z")

</div>

Hi! I recently made a bouncing ball program

```auto
float x = 300, y = 300, r = 30, xs = 10, ys = 8, friction = 0.9;

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

void draw() {
  background(0);
  circle(x,y,r*2);
  x+=xs;
  y+=ys;
  
  if(x + r > width || x - r < 0) {
    xs *= -1;
  }
  if(y + r > height || y - r < 0) {
    ys *= -1;
  }
}

```

and want to create a program where you can create lines to add ways to reflect the ball

![image](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/2X/3/3f6e884d505227d9eb300ade46768e9081edc5ce.png)

I can use the [LINE / CIRCLE DETECTION](http://jeffreythompson.org/collision-detection/line-circle.php) to get the information if they bounce but I don’t know how to determine what to multiply the x speed and y speed with. Could it be

xs\*=cos(reflect angle)  
ys\*=sin(reflect angle)

?

---

<div class="post-metadata">

**Author:** ![MiguelSanches](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/miguelsanches/32/11172_2.png) [@MiguelSanches](https://discourse.processing.org/u/MiguelSanches)\
**Post date:** [December 19, 2020, 11:13am UTC](https://discourse.processing.org/t/how-to-bounce-a-ball-off-a-randomly-generated-line/26379/2 "2020-12-19T11:13:39Z")

</div>

Hi @CodeMasterX,

In general terms, the angle of reflection is the same as the angle of incidence. This angle is measured in relation to the wall’s normal. Here’s a picture that should make it clear:

![enter image description here](https://i.stack.imgur.com/QGuay.png)

In case you ever need to handle this for arbitrary walls, you’ll need to look into how to reflect a vector. It’s really just a small formula that takes the wall’s normal and the incidence vector, and returns the reflected vector for you.

You can find the mathematic formulas in:  
[http://www.3dkingdoms.com/weekly/weekly.php?a=2](http://www.3dkingdoms.com/weekly/weekly.php?a=2)

I also find the following video that implements the bouncing ball and it explains the code.

> **Bouncing ball**
>
> [https://www.youtube.com/watch?v=Ep2N0N6SB6U&ab\_channel=LongNguyen](https://www.youtube.com/watch?v=Ep2N0N6SB6U&ab_channel=LongNguyen)

Hope it helps! 🙂
