Flash Momentum Tutorial
By Matt Carpenter2007-12-15
Get the motion
The first step in maintaining an object’s motion is figuring out what that motion is and saving it. To do this we simply need to save the objects location from the last frame, and then subtract that from the current frame’s location. This gives us the object’s velocity.
As an example of what I mean, I’ve written the following handlers for a ball MovieClip.
The key point to be aware of is that I am saving the position of the
clip so I can use it to calculate the velocity. We only need to execute
this code when the object is not being dragged. The velocity won’t be
changing once it is released. To keep the object moving once it is
released, we simply add the velocity values to its current position.
Sidenote:
You can get some pretty annoying behavior if you don’t include releaseOutside in the events that trigger the stopDrag.
This is because the mouse moves before the object does, making it
possible to let go of the mouse when the object isn’t under it.
onClipEvent(load) {
// initialize the variables needed to calculate and store momentum
this.lastFramePosition = new Object();
this.velocity = new Object();
this.lastFramePosition.x = this._x;
this.lastFramePosition.y = this._y;
this.velocity.x = 0;
this.velocity.y = 0;
this.isDragging = false;
}
onClipEvent(enterFrame) {
if (this.isDragging) {
// calculate and save the object's velocity
this.velocity.x = this._x - this.lastFramePosition.x;
this.velocity.y = this._y - this.lastFramePosition.y;
// save the current location to the lastFramePosition
this.lastFramePosition.x = this._x;
this.lastFramePosition.y = this._y;
}
else {
// the object is not being dragged, so keep it moving
this._x += this.velocity.x;
this._y += this.velocity.y;
}
}
// Make the object draggable
on(press) {
this.startDrag();
this.isDragging = true;
}
on(release, releaseOutside) {
this.stopDrag();
this.isDragging = false;
}
Throw-able Ball
Tutorial Pages:
» startDrag Woes
» Get the motion
» Damping and Limiting
» The End
