Rotating a Sprite around any point
This time I want to share a simple solution to a relatively simple, but annoying problem.
The problem
The Sprite.rotation property rotates the object always around the registration point of the Sprite. If you need to rotate it around some other point, it's not automatic.
One way to achieve this is to move the content inside the Sprite in order to change its position in relation to the registration point. It works, but it's not elegant and not very handy if the Sprite has many children – you would need to move all of them.
Another way is to wrap your Sprite into another Sprite and rotate the parent. This solution is a bit better, but still has lots of shortcomings. And what about if you need to change the registration point of the object during rotation?
Solution
The Rotator class can be used as a replacement for the default Sprite.rotation property. This class uses a combination of trigonometric functions to rotate an object around a point along with the rotation property itself to create a correct circular movement. It allows you to have a proper rotation no matter if the point is placed inside the rotated object or outside of it. And, what's most fun, you can change the registration point at any moment. Play with the demo above to see it in action.
Source
Check out the source of the class here, or just grab a ZIP with the complete demo here.
Example.
It can be used either directly, in an 'ENTERFRAME' animation, or in combination with Tweener or other similar libraries. It works not only with a Sprite, but also with any class that extends the DisplayObject.
Use it like this:
var s:Sprite = new Sprite();
var r:Rotator = new Rotator(s, new Point(10,10));
r.rotation = 45;
or like this:
import caurina.transitions.Tweener;
var s:Sprite = new Sprite();
var r:Rotator = new Rotator(s, new Point(10,10));
Tweener.addTween(r, { rotation:45, time:1, transition:"linear"} );