Friday, August 20, 2010

Rotate around center Flex/AS3

I have been searching for rotating any display object based on its center and ended up with the stuffs using MatrixTransformer.

Though it may helpful to use those stuffs, it didnt work for me. finally i did a work around it and created a method which uses the getRect() of AS3 and works well without the MatrixTransformer stuff. I have posted that function here and it will be helpful for some one.

/**
* Rotates the object based on its center
* Parameters: @obj => the object to rotate
* @ rotation => angle to rotate
* */
public function RotateAroundCenter(obj:Object, rotation:Number):void
{

var bound:Rectangle = new Rectangle();
// get the bounded rectangle of objects
bound = obj.getRect(this);

// calculate mid poits
var midx1:Number = bound.x + bound.width/2;
var midy1:Number = bound.y + bound.height/2;

// assign the rotation
obj.rotation = rotation;

// assign the previous mid point as (x,y)
obj.x = midx1;
obj.y = midy1;

// get the new bounded rectangle of objects
bound = obj.getRect(this);

// calculate new mid points
var midx2:Number = bound.x + bound.width/2;
var midy2:Number = bound.y + bound.height/2;

// calculate differnece between the current mid and (x,y) and subtract

 //it to position the object in the previous bound.
var diff:Number = midx2 - obj.x;
obj.x -= diff;
diff = midy2 - obj.y;
obj.y -= diff;
}


//////////////////


Usage:

you can use the above function as described below,

var img:Canvas = new Canvas()
RotateAroundCenter(img, rotation);


cheers.

5 comments:

  1. It helped me! Thank you a lot!

    ReplyDelete
  2. sorry but it do not work for me T_T

    ReplyDelete
  3. You are a GENIUS.

    I had to make one modification for it to work.

    I changed: obj.rotation = this._rotation;

    to

    obj.rotation += 10;

    The compiler didn't like _rotation.

    Thanks!

    ReplyDelete
    Replies
    1. Hi Ruf,

      Thought it is a very late reply, thanks for the notification. I have updated the code. Replace "this._rotation" with "rotation".

      Thanks

      Delete