views:

3232

answers:

4

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!

+2  A: 

translate the point you want to rotate around to 0,0. rotate by what you want, translate back to the original x, y coordinates.

Here's a post showing how to implement: Rotate about center

CookieOfFortune
A: 

If you want to rotate around the center, merely center the asset inside your sprite by setting the internal assets x and y to half of the width and height of the asset. This swill center your content and allow it to rotate around a center point.

An example of runtime loaded assets is as follows:

var loader:Loader = new Loader():
var request:URLRequest = new URLRequest(path/to/asset.ext);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, _onLoaderComplete);
loader.load(request);

private function _onLoaderComplete(e:Event):void
{
    var mc:MovieClip = e.target.content as MovieClip;
    mc.x = -mc.width * 0.5;
    mc.y = -mc.height * 0.5;
    mc.rotation = 90;
    addChild(mc);
}

Brian Hodge
blog.hodgedev.com

Brian Hodge
A: 

Below are the following steps required to rotate objects based on any 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 and 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:

Ronnie Liew