Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AS3 Rotate an object around its center point

I want this object to rotate around its center rather than the top left corner. The code looks like this:

        switch (event.keyCode)
        {
            case 37:
            car.rotation = -90;
               car.x -= 5;
               break;

So when i press the left key, the car turns left but as it is now it jumps up a bit because its rotating around the top corner.

Thanks

like image 782
anton petersson Avatar asked Apr 03 '13 13:04

anton petersson


2 Answers

The following will rotate around center :

public function rotateAroundCenter(object:DisplayObject, angleDegrees:Number):void {
    if (object.rotation == angleDegrees) {
        return;
    }
        
    var matrix:Matrix = object.transform.matrix;
    var rect:Rectangle = object.getBounds(object.parent);
    var centerX = rect.left + (rect.width / 2);
    var centerY = rect.top + (rect.height / 2);
    matrix.translate(-centerX, -centerY);
    matrix.rotate((angleDegrees / 180) * Math.PI);
    matrix.translate(centerX, centerY);
    object.transform.matrix = matrix;
    
    object.rotation = Math.round(object.rotation);
}
    

It translates the center of the object to 0,0 then rotate it and then translate it back.

like image 73
Barış Uşaklı Avatar answered Nov 09 '22 03:11

Barış Uşaklı


The easiest way to accomplish this is to add your car sprite/movieclip onto another sprite, where the x and the y coordinates are half the width and height properties. If the car is drawn in adobe flash you can also drag it to the top left, so that the center point is in the middle.

like image 45
Bart Avatar answered Nov 09 '22 03:11

Bart