Simple maths in AS3 part 3 - rotating object around another
April 9, 2008 — flaimHi everyone,
Next part of the series.
This time I wrote a small function which uses trigonometry (sin and cos) to rotate one object around another one.
The only thing you need to do is to specify the two objects used in the animation and some parameters like that:
rotate_around_object ( object_to_rotate, center_object, radius, speed , start angle);
The function will create an event listener for the object (on_enter_frame) and move object_to_rotate around the center_object in a certain radius at a certain speed. The animation will start at the specified start_angle. If you want to change the rotation direction - specify the speed with a minus value.
The code is here (AS3) :
function rotate_around_object(object1,object2,radius,speed,angle)
{
var xpos,ypos;
object1.addEventListener(Event.ENTER_FRAME, object_ENTERFRAME);
function object_ENTERFRAME(e:Event):void
{
xpos = object2.x + object2.width/2 + Math.cos(angle) * radius;
ypos = object2.y + object2.height/2 + Math.sin(angle) * radius;
angle += speed;
object1.x=xpos;
object1.y=ypos;
}
};
// example usage (you need 4 movieclips on the stage in this example..
// …with instance names: point1, point2.. and so on.
rotate_around_object(point2,point1,100,.2,0);
rotate_around_object(point4,point3,200,.1,45);
You can download the fla file here.
You can see it running here.
Have fun,
FLAIM







