【问题标题】:XNA Negative Rotation?XNA 负旋转?
【发布时间】:2014-09-06 13:40:34
【问题描述】:

我正在编写一个星际飞船游戏,并且刚刚完成了管理旋转的部分。我使用了一个简单的 if/else 语句来检查船是否必须正转或反转才能尽快面对目标。但是我看到 Rotation-Value 可以为负值,然后船确实旋转到错误的方向(它最终仍然面向目标点,但需要更长的时间)。请告诉我我做错了什么:(

功能:

 public bool RotateOrMove(Vector2 position)
    {
        if (IsRotationg == null) //todo
        {
            Vector2 direction = Position - position;
            direction.Normalize();
            FinalRotation = (float)Math.Atan2(-direction.X, direction.Y);
            IsRotationg = true;
        }

        if (Equals(FinalRotation, Rotation)) 
            IsRotationg = false;

        if (IsRotationg == false)
        {
            Position = position;
            return true;
        }
        else
        {
            if (FinalRotation >= Rotation)
            {
                Rotation += RotationVelocity;

                if (FinalRotation - Rotation < RotationVelocity)
                {
                    Rotation = FinalRotation;
                    IsRotationg = false;
                }
            }
            if (FinalRotation < Rotation)
            {
                Rotation -= RotationVelocity;

                if (FinalRotation - Rotation > -RotationVelocity)
                {
                    Rotation = FinalRotation;
                    IsRotationg = false;
                }
            }


            return false;
        }


    }

玩家级拥有这艘船。当玩家按下鼠标右键时,该方法将每帧调用一次,直到飞船到达光标所指的位置。

if (!Ship.RotateOrMove(Position)) 
                Position -= Velocity;

因此,如果船不得不旋转而无法移动,它将移除之前添加的速度,以确保船不会移动。

希望你能理解我的问题^^

【问题讨论】:

  • 是不是每次都转错方向?
  • @bubbinator 不,这有点罕见。但是当船指向东南并且我想将它转向西南时,它肯定会发生。

标签: c# xna rotation


【解决方案1】:

Math.Atan2 从 -pi 到 pi 返回值。

要获得平滑的旋转,您可以使用从here 获得的代码

private float CurveAngle(float from, float to, float step)
{
 if (step == 0) return from;
 if (from == to || step == 1) return to;

 Vector2 fromVector = new Vector2((float)Math.Cos(from), (float)Math.Sin(from));
 Vector2 toVector = new Vector2((float)Math.Cos(to), (float)Math.Sin(to));

 Vector2 currentVector = Slerp(fromVector, toVector, step);

 return (float)Math.Atan2(currentVector.Y, currentVector.X);
}

private Vector2 Slerp(Vector2 from, Vector2 to, float step)
{
 if (step == 0) return from;
 if (from == to || step == 1) return to;

 double theta = Math.Acos(Vector2.Dot(from, to));
 if (theta == 0) return to;

 double sinTheta = Math.Sin(theta);
 return (float)(Math.Sin((1 - step) * theta) / sinTheta) * from + (float)(Math.Sin(step * theta) / sinTheta) * to;
}

【讨论】:

  • 感谢您的回答 :) 但我不明白我必须在哪里调用 CurveAngle(); ^^
  • CruveAngle 进行初始(从)旋转、最终(到)旋转和步进。变量step取0到1之间的值,当step为0时从角度返回,当step为1时返回角度,所以你只需要给从0到1的step值就可以得到中间角度
  • (抱歉回复晚了,但我忙于学校和那些事情^^)是的,但我仍然不知道我必须在哪里调用 CurveAngle?
  • 哈哈,我刚刚尝试并在正确的位置使用 FIRST TRY 调用它:D xD 谢谢,完美运行^^
猜你喜欢
  • 2011-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-07
相关资源
最近更新 更多