简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM