Yesterday, I was working on a Flash animation for a client. Part of the animation involved an automobile driving over the client’s product as a display of structural integrity. That meant spinning wheels. That meant a little fun with geometry and ActionScript.
I threw together some ActionScript 2 to rotate the wheels based on the movement of the vehicle. Not sure if it’s perfect, but it seemed to work okay.
The ActionScript to calculate the rotation of each wheel depends on two formulae:
Thanks, Pythagoras and Pi. Thorasandpi.
Here is the resulting ActionScript (attached to the wheel movie clip):
onEnterFrame = function() {
// _parent is the vehicle clip. It's what's moving.
// Figure out its x and y coordinates relative to last time.
dx = _parent._x - this.lastx;
dy = _parent._y - this.lasty;
// The sum of the square of the two sides (horiz. and vert. change)
sum = Math.pow(dx, 2) + Math.pow(dy, 2)
// The hypotenuse
dist = Math.sqrt(Math.abs(sum));
// The direction is determined by whether dx is positive or negative
dist = dx < 0 ? -1 * dist : dist;
_rotation = _rotation + ( (360 / (_width * Math.PI) ) * dist );
// Store the vehicle's x and y coordinates for next time.
this.lastx = _parent._x;
this.lasty = _parent._y;
}
And here is an example:
I’m sure this is basic stuff for most ActionScript people, but I don’t work with it that often. Sometimes I wish I did. I’ve always loved geometry, and I know there are all kinds of fun puzzles like this when you combine animation with math. Ah well… just not enough hours in the day.
Jul 3rd, 2009 at 4:58 am kamran
brother ur work is courgeos i like that.i want to learn the actione scripting can u teach me plz.