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

Read Full Post »