我希望这个对象围绕它的中心旋转,而不是围绕左上角旋转。
代码如下:
switch (event.keyCode)
{
case 37:
car.rotation = -90;
car.x -= 5;
break;
当我按下左键时,汽车会向左转,但现在它会因为围绕着顶角旋转而跳起来。谢谢。我希望这个对象围绕它的中心旋转,而不是围绕左上角旋转。
代码如下:
switch (event.keyCode)
{
case 37:
car.rotation = -90;
car.x -= 5;
break;
当我按下左键时,汽车会向左转,但现在它会因为围绕着顶角旋转而跳起来。谢谢。以下将围绕中心旋转:
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,然后旋转它,最后再将其转换回来。
实现这个最简单的方法就是将你的汽车精灵/影片剪辑添加到另一个精灵上,其中x和y坐标为宽度和高度属性的一半。如果汽车是在Adobe Flash中绘制的,你还可以将其拖动到左上角,使中心点位于中间。
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;
}
}
object.rotation = Math.round(object.rotation);
看看会发生什么。 - Barış Uşaklı