Adobe Flash cs4旋转数学

3

我目前遇到了关于对象朝向另一个对象旋转的问题。目前情况如图所示,我的对象在原点时能够旋转并移动到3个象限中除了正90度到180度象限的对象。当移动到该对象时,我的对象会旋转几圈一段时间。不知道有没有人知道为什么?我用的旋转语句是 rotation += (foodLocationDegrees - (rotation - 90)) * .2; 其中food是用来计算的。

var angle:Number = Math.atan2(foodTarget.y - y, foodTarget.x - x); 
            foodLocationDegrees =Math.floor((angle  * 180 / Math.PI));

y和x是一个鱼的对象,foodtarget是食物的对象。
 public function moveToFood():void
        {   

            var dx:Number = x - _destinationX;
            var dy:Number = y - _destinationY;

            trace("Food location degree relative to fish mouth "+foodLocationDegrees);
            var targetRotation:Number = 0;
            if (foodLocationDegrees > 0 && foodLocationDegrees < 90)
            {
            trace("food is on 1st quadrant of the fish mount");
                this.x -= dx / 18;
                this.y -= dy / 18;
            }else if (foodLocationDegrees > 90 && foodLocationDegrees < 180)
            {
            trace("food is on 2nd quadrant of the fish mount"); 

                this.x -= dx / 18;
                this.y -= dy / 18;
            }else if (foodLocationDegrees > -180 && foodLocationDegrees < -90)
            {
                trace("food is on 3nd quadrant of the fish mount");

                this.x -= dx / 18;
                this.y -= dy / 18;
            }else if (foodLocationDegrees < 0 && foodLocationDegrees > -90)
            {
                trace("food is on 4nd quadrant of the fish mount");

                this.x -= dx / 18;
                this.y -= dy / 18;
            }
            trace("Before adding Rotation " + rotation);
            var number:Number = (foodLocationDegrees - (rotation - 90)) * .1;
            trace("rotation to add "+number);
            rotation += (foodLocationDegrees - (rotation - 90)) * .2;

            trace("After adding Rotation " + rotation);

            //removing food when both hit boxes hit
            if (hit.hitTestObject(foodTarget.hit))
            {
                foodInPond--;
                foodTarget.removeSelf();
            }

        }

PS:我的数学知识非常薄弱,因为我没有花时间学习数学,公式是从这里提问的答案和我自己摸索数字拼凑而成的,请见谅。 - sutoL
1个回答

0
public function moveToFood(food:Food):void
{
    var speed:Number = 6.5;

    var a:Number = food.x - x;
    var b:Number = food.y - y;
    var ang:Number = Math.atan2(b, a);

    rotation = ang * 180 / Math.PI;

    x += Math.cos(ang) * speed;
    y += Math.sin(ang) * speed;
}

你不能只是使用sincos来朝着你所面向的方向移动吗?


我尝试了你的函数,但是鱼离开了食物。而且这个函数是在Enter_frame处理程序中处理的,使得值重复改变。 - sutoL
我能够让鱼移动,但是我遇到了鱼头旋转以面对食物的问题。使用您的方法,鱼侧向移动。这是因为我的鱼符号的注册点设置方式导致的吗? - sutoL
你需要在库中将图形旋转,使其面向右侧而不是向上。 - Marty
谢谢,那个有效。我可以知道在哪里阅读公式的工作原理吗? - sutoL
http://en.wikipedia.org/wiki/File:Sine_and_Cosine.svg sin和cos函数所接受的弧度值相当于-1到1之间的值。例如,cos(0)将等于1,而sin(0)等于0。因此,如果您查看公式,当您的角度为0弧度时,您沿x轴移动1 *速度,并沿y轴移动0 *速度(0)。 - Marty

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