首页 > 解决方案 > 确定统一旋转角色的方向?

问题描述

我目前在尝试确定哪个方向是两个角度之间的最短路径时遇到了很多问题。我正在 Unity2D 中编写一个 boid,并且我正在研究分离方面。就上下文而言,我当前的系统通过在 boid 周围创建指定数量的游戏对象来工作(我发现其中 16 个工作得很好)。这些游戏对象有自己的脚本,可以将 linecast 绘制到父 boid,并记录它与玩家的角度。如果 linecast 撞到墙壁或 boid,它会将其角度的余弦和正弦添加到存储在父 boid 中的两个单独列表中。父 boid 计算这两个列表的平均值并基于此创建一个向量。boid 获得与该向量的角度,并将其添加 180 度以找到它需要前进的方向,以免撞到对象。

现在,不起作用的是向那个目标方向旋转身体。我不希望 boid 立即锁定到位,而是缓慢旋转。我想要这个,因为它为身体的运动增加了很多变化。运动采用 boid 所面对的当前方向并以该方向移动。在大多数情况下,我得到了这个代码:

void Rotate()
    {
        if (currentRotation != goalRotation)
        {
            int sign = (currentRotation < goalRotation) ? 1 : -1;
            rotateSpeed = Mathf.Abs(currentRotation - goalRotation) / 10;
            currentRotation += rotateSpeed * sign;
            if (Mathf.Abs(currentRotation - goalRotation) <= .5) //If the current rotation is close, just make it the goal rotation.
            {
                currentRotation = goalRotation;
            }
        }
    }

(角度基于单位圆)

我真的很喜欢它如何开始快速旋转 boid,并在 boid 达到所需角度时减慢速度。因此,此代码有效,除非当前旋转是 350 度,而目标方向是 10 度。即使最短的路径是逆时针的,boid 也会顺时针旋转。我确切地知道为什么,但不知道如何解决它。任何帮助,将不胜感激。

标签: c#unity3d

解决方案


我不明白是什么boid,但这是解决方案:

不光滑

transform.LookAt(target);

光滑的

var targetRotation = Quaternion.LookRotation(targetObj.transform.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.deltaTime);

您可以结合Quaternion.RotateTowardsQuaternion.Slerp实现超流畅的解决方案。


推荐阅读