Scale & rotate around an arbitrary centre
The mini project I picked as my first dip into AS3 was a short example that I had been planning for this blog, so here it is in AS3, instead of AS2 as I had originally planned.
The South Park Chin balls Flash app required that the user drag and zoom a loaded photo. Anyone who's ever done this will know that you can't just scale the picture around it's registration point when you zoom. Why? because the centre point changes as you pan the image around. So the requirement in a nutshell is - to be able to scale a MovieClip around an arbitrary centre.
Sure, you could take the Russian doll approach with multiple clips inside clips, but that just ain't cool! I thought I'd share the way I did it as it's pretty concise.
First of all here's the principal in action. Scaling and rotation, both performed around an arbitrary centre point that you can alter by dragging that little marker around. Go on, have a go.
Loading example SWF…
Download the source files for this example
Most of the source files just serve to create the example interface. The only class we need to discuss is the one with the scale and rotating logic. The class VirtualCentreSprite is an extension of the Sprite class. In AS2 it would have to be an extension of the MovieClip class, but we don't need a timeline. You could use this as a base class for sprites across your project to ensure they all have this capability.
It has two methods as follows:
void scaleAround( offsetX:Number, offsetY:Number, absScaleX:Number, absScaleY:Number )
void rotateAround( offsetX:Number, offsetY:Number, toDegrees:Number )
The scaling method is the simplest. It's basically GCSE vector maths. We calculate the position that the clip should be at after scaling, do the scaling (which will move the clip according to the centre that Flash knows about) and then we simply reposition it to where it should be.
Click to see source of method scaleAround
The rotating method is a bit more complex, because it uses a transformation matrix. But thanks to the flash.geom package this is short and sweet. Again the principal is that we let Flash rotate the sprite and then adjust the position.
Click to see source of method rotateAround
September 1st, 2008 at 2:09 pm
Nice demo Man.
All what the math the newbies want.
October 30th, 2008 at 5:25 am
Thank you very much!