Actionscript 3.0: Rotate Around Center Point

Problem:

You need to rotate a movieclip/sprite around it’s center point, but its registration point is at (0,0) and you can’t and/or don’t feel like putting this object in the center of a container movieclip and rotating that.

Solution:

Use the transform matrix and show it who’s boss.

If you want to get this done simply and quickly, you can use this rotateAroundCenter function:

 private function rotateAroundCenter (ob:*, angleDegrees:Number, ptRotationPoint:Point) {
      var m:Matrix=ob.transform.matrix;
      m.tx -= ptRotationPoint.x;
      m.ty -= ptRotationPoint.y;
      m.rotate (angleDegrees*(Math.PI/180));
      m.tx += ptRotationPoint.x;
      m.ty += ptRotationPoint.y;
      ob.transform.matrix=m;
 }

Now to make this work, you could call it like this:

//this will create a point object at the center of the display object
ptRotationPoint = new Point(mcPhoto.x + mcPhoto.width/2, mcPhoto.y+mcPhoto.height/2);
//call the function and pass in the object to be rotated, the amount in degrees, and the point object we created
rotateAroundCenter(mcPhoto, 90, ptRotationPoint);

There you go, that should work. If you want to take it further, Jack Doyle at Greensock.com (author of TweenLite) wrote an amazing class called TransformMatrixProxy which will allow you to easily do all types of transformations (including rotation and skewing) based on the registration point you specify. Oh, and you can tween these properties as well… hell yeah…

I haven’t tried it out myself yet, but the demo works great and I’m sure it’s a really great tool. Go check it out. A screen shot of the TransformMatrixProxy demo at greensock.com

Comments

4 Responses to “Actionscript 3.0: Rotate Around Center Point”

  1. Raj on July 22nd, 2008 9:20 am

    Thanx dude! The function works fine.

  2. niceBoat on September 9th, 2008 7:31 pm

    Thanks a lot for posting this!

  3. Xav on November 19th, 2008 5:51 pm

    Ok it works, but why the hell didn’t they put centering properties in actionscript ? Isn’t this pure stupidity, given that it is still missing in CS4 ?

  4. rbosinger on November 19th, 2008 6:11 pm

    Well, keep in mind that it is also possible to center the contents of a movieclip so that the registration point sits in the middle. Then the normal “rotate” property would rotate around center. Yes, I’m surprised there isn’t a built in function that would do that for you. There’s probably a reason for it. This is a quick fix, although it is a very powerful because knowing how to use the Matrix class will enable you to do all kinds of image transformations. I imagine in the future the type of functionality that the “TransformMatrixProxy” offers might be built right in.

Leave a Reply