How to bounce a ball off a randomly generated line?

Hi! I recently made a bouncing ball program

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

I can use the LINE / CIRCLE DETECTION 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)

?

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

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

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

Hope it helps! :slight_smile:

3 Likes