## Ball Bouncing off Line Calculation

June 29, 2009 by jobemakar

I’m working on a new game that requires me to dig into some physics and math that I haven’t touched in a while. The Vector3D class was introduced with Flash Player 10. I used this as an opportunity to get familiar with that class and see if it could make life a little easier, and it does!

The Vector3D class keeps track of x and y (and z if you want it to) values. It uses the sign on the value to imply direction. You can then perform cross products or dot products and a few other basic vector actions via its methods.

Conceptually, here is how to make a ball (or sphere) bounce off of a line (assuming you can calculate that the collision is occurring).

- Use a vector for the ball velocity
- Use a vector to represent the line normal (perpendicular to line)
- Do simple vector algebra to get new velocity

**Step 1**

Represent the ball velocity as a vector. For instance,

var velocity:Vector3D = new Vector3D(2, 0);

**Step 2**

Represent the line normal as a vector (which it is). For instance,

var normal:Vector3D = new Vector3D(1, -1/line_slope);

normal.normalize();

**Step 3**

Do the vector math when a collision is detected. You can imagine that the velocity vector can be projected onto the normal, and it is only that bit that will be reflected off of the surface. So, we’ll project it onto the normal and set the net change to 2 * this value. 1* the value makes the velocity 0, 2 * the value sends it back an equal amount. We then take this reflected vector and subtract from the incident velocity vector.

var reflectionScalar:Number = 2 *velocity.dotProduct(normal);

var reactionProjection:Vector3D = normal.clone();

reactionProjection.scaleBy(reflectionScalar);

velocity.subtract(reactionProjection);

Download source

click to view example

### Like this:

Like Loading...

*Related*

on July 16, 2009 at 11:52 pm |ZacharyJobe:I'm following along with your source, but I'm also trying to get a better grip on the underlying math. In your line class, what to the letters m and b represent? Im familiar with normal – but m and b? Are they just the ratio of the slope?

on July 17, 2009 at 1:02 am |Jobe MakarHi,The equation of a line is:y = m*x + bWhere m is the slope and b is the y-inercept.Is that clear?

on July 20, 2009 at 6:34 pm |ZacharyAwesome! yes that makes perfect sense and is very compact! Thanks.From your post I found a bit more detailed description. For any others (like me) who are just now learning about lines described using slope and intercept, here's a more detailed description:http://www.purplemath.com/modules/strtlneq.htmThanks, Jobe.

on June 24, 2010 at 7:19 am |trent_cbdhey there, i'm trying to reverse engineer what you've done here. just wondering how i could change your drawline function to accept x,y,width,height to draw lines where i want them on the stage, then recalculate the m + b from these values?Cheers.