Rotating Objects Around Their Center
In actionscript, when you create a Bitmap or Movieclip or Sprite, it’s reference point is at the top left at 0, 0 meaning that if you rotate an object, it will rotate around the top left corner, not the center.
I am currently working on a tower defense game and needed the turrets for my towers to rotate around the center. There are many sites such as Ryan Bosingers that correctly explain you need to use a matrix and transform your object so that the point you want to rotate around is at 0, 0.
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;
}
The problem with solutions such as the above is that over time your objects can start to drift. This is caused because once you rotate your object, you are altering it’s width and height. If you rotate a square 45 degrees, it is a diamond and its width is greater. In the function above you transform an objects back X pixels, rotate it a bit then transform it back the same X pixels, ignoring the fact that the rotation changed the width and height slightly. This adds up over time, which is why you want to basically reset your matrix with the identify() method:
private function rotateAroundCenter (ob:*, angleDegrees:Number, ptRotationPoint:Point) {
var m:Matrix=ob.transform.matrix;
m.identity()
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;
}






