AS3 如何使一个物体绕其中心点旋转

10

我希望这个对象围绕它的中心旋转,而不是围绕左上角旋转。

代码如下:

        switch (event.keyCode)
        {
            case 37:
            car.rotation = -90;
               car.x -= 5;
               break;
当我按下左键时,汽车会向左转,但现在它会因为围绕着顶角旋转而跳起来。谢谢。
3个回答

22

以下将围绕中心旋转:

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);
}
    

它将对象的中心转换为0,0,然后旋转它,最后再将其转换回来。


似乎有一个非常小的错误会随着每次旋转而累积,使我的旋转轮逐渐移动。我的图像完美地居中。非常奇怪。 - Deyan Vitanov
1
@DeyanVitanov 尝试移除最后一行 object.rotation = Math.round(object.rotation); 看看会发生什么。 - Barış Uşaklı

8

实现这个最简单的方法就是将你的汽车精灵/影片剪辑添加到另一个精灵上,其中x和y坐标为宽度和高度属性的一半。如果汽车是在Adobe Flash中绘制的,你还可以将其拖动到左上角,使中心点位于中间。


0
转载Mallario在OpenFL社区的解决方案:https://community.openfl.org/t/rotation-around-center/8751/9,该解决方案不使用transform.matrix。我在Haxe中进行了适应,但在ActionScript 3中几乎相同。
package p.util;

import openfl.display.DisplayObject;
using p.util.FloatUtilities;

class DisplayObjectUtilities {
    /**
     * Positions and rotates a display object by its center anchor.
     */
    public static function centerOrient(object: DisplayObject, x: Float, y: Float, rotation: Float) {
        var w = object.width;
        var h = object.height;
        x -= w / 2;
        y -= h / 2;
        object.rotation = rotation;

        // Code from https://community.openfl.org/t/rotation-around-center/8751/9
        {
            var hypotenuse = Math.sqrt(w / 2 * w / 2 + h / 2 * h / 2);
            var newX = hypotenuse * Math.cos((rotation + 45.0).toRadians());
            var newY = hypotenuse * Math.sin((rotation + 45.0).toRadians());
            x -= newX;
            y -= newY;
        }

        object.x = x;
        object.y = y;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接