# Bouncing off surfaces

This is a discussion on Bouncing off surfaces within the Game Programming forums, part of the General Programming Boards category; I'm looking to make a simple game/demonstration of a ball infinitely bouncing around in a box. I'm unsure of what ...

1. ## Bouncing off surfaces

I'm looking to make a simple game/demonstration of a ball infinitely bouncing around in a box. I'm unsure of what formulas I should be using to get an acurate representation of a ball bouncing with a constant speed off of surfaces. If anybody can direct me to any resources I'd appreciate it.

Thanks.

2. You say box, so I assume you want the ball to bounce off a plane. A plane has a normal direction N (usually unit length, but we don't care for this discussion). You can write the velocity of the ball v as v1 + v2, where v1 is the velocity "with" the normal, or against the plane (which you get by doing a projection) and v2 is the velocity "with" the plane itself, or along the wall (the rest of the velocity). After the bounce, v2 will be the same (the ball will "slide" along the wall in this direction), but v1 will be replaced by -v1 (bouncing straight off the wall).

3. Code:
```..
if (ball.x < box.left || ball.x > box.right)
{
ball.vx = -ball.vx;
}

if (ball.y < box.top || ball.y > box.bottom)
{
ball.vy = -ball.vy;
}
...
...
ball.x += ball.vx * speed * frameDelta;
ball.y += ball.vy * speed * frameDelta;
...```
This is a simple non-physics based collision.

4. Only for perpendicular surfaces though.

5. I'm looking to make a simple game/demonstration of a ball infinitely bouncing around in a box.
A box is composed of surfaces that are perpendicular.

Popular pages Recent additions