Flex/ActionScript – rotate Sprite around its center

actionscript-3apache-flexflash

I have created a Sprite in Actionscript and rendered it to a Flex Canvas. Suppose:

var fooShape:Sprite = new FooSpriteSubclass();

fooCanvas.rawChildren.addChild(myshape);

//Sprite shape renders on screen

fooShape.rotation = fooNumber;

This will rotate my shape, but seems to rotate it around the upper-left
point of its parent container(the canvas).

How can I force the Sprite to rotate about is own center point? I could obviously
write code to calculate the rotation, and then have it re-render, but I think there
must be a built-in way to do this, and certainly do not want to 'reinvent the wheel'
if possible.

I am using FlexBuilder, and therefore do not have access to the full Flash API.

Thank you much!

Best Answer

The following steps are required to rotate objects based on a reference point (using Matrix object and getBounds):

  1. Matrix translation (moving to the reference point)
  2. Matrix rotation
  3. Matrix translation (back to original position)


For example to rotate an object 90 degrees around its center:

// Get the matrix of the object  
var matrix:Matrix = myObject.transform.matrix; 

// Get the rect of the object (to know the dimension) 
var rect:Rectangle = myObject.getBounds(parentOfMyObject); 

// Translating the desired reference point (in this case, center)
matrix.translate(- (rect.left + (rect.width/2)), - (rect.top + (rect.height/2))); 

// Rotation (note: the parameter is in radian) 
matrix.rotate((90/180)*Math.PI); 

// Translating the object back to the original position.
matrix.translate(rect.left + (rect.width/2), rect.top + (rect.height/2)); 



Key methods used:

Related Topic