Flash Momentum Tutorial
By Matt Carpenter2007-12-15
Damping and Limiting
As you can see, the ball can get moving pretty fast and shows no signs of slowing down ever. Perhaps this is how you want the ball to behave. For most applications, however, you will probably want to limit the object’s speed to within reason. You may also want the object to slow down over time. The rest of this tutorial will address these two features.
To limit the speed of the ball, we use a little trig. Don’t be afraid of the math, I’ve already worked it out here for you. Those of you who like math can probably figure out what’s going on pretty easily. Those of you who hate it can just copy the code.
// limit the velocity to MAX_SPEED
if ( Math.sqrt(Math.pow(this.velocity.x,2) + Math.pow(this.velocity.y,2)) > MAX_SPEED ) {
velAng = Math.atan2( this.velocity.y, this.velocity.x );
this.velocity.x = MAX_SPEED * Math.cos( velAng );
this.velocity.y = MAX_SPEED * Math.sin( velAng );
}
And finally we’ll slow the object down over time. To slow the object down, we simply multiply the velocity by a number less than zero each frame. You could get the same effect by dividing the velocity by a number greater than zero. As you can see in the code, it doesn’t take much to slow the ball down.
DAMPING_FACTOR = 0.98;
// slow down the ball by the DAMPING_FACTOR
this.velocity.x *= DAMPING_FACTOR;
this.velocity.y *= DAMPING_FACTOR;
Throw-able Ball with Limiting and Damping
Tutorial Pages:
» startDrag Woes
» Get the motion
» Damping and Limiting
» The End
