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

3 comments:
Jobe:
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?
Hi,
The equation of a line is:
y = m*x + b
Where m is the slope and b is the y-inercept.
Is that clear?
Awesome! 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.htm
Thanks, Jobe.
Post a Comment