Simple maths in AS3 part 3 - rotating object around another

object rotation

Hi 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

Simple maths in AS3 part 2 - rotation

Hello,

This time a short explanation how to use trigonometry and rotation to achieve a ‘point_to’ effect. The maths is really simple here and useful for various effects and other uses. I’ve used a mousemove listener on the stage to execute the function and mouseX + mouseY to give the coordinates to the script. The movieclip (or sprite if you wish) can be rotated to face the direction of a point you specify (in this case - the mouse position on the stage).

Here is the code (as3):

var dx,dy,target_rotation:Number;

function point_to(what)
{
dx = mouseX - what.x;
dy = mouseY - what.y;
what.rotation = Math.atan2(dy, dx) * 180 / Math.PI;
}

// example usage
stage.addEventListener(MouseEvent.MOUSE_MOVE,stage_MOUSEMOVE);
function stage_MOUSEMOVE(e:MouseEvent):void
{
 point_to(movie_mc);
}

You can download the FLA file here. The example can be seen here.

Feel free to comment and have fun with Flash!,

FLAIM