繁体   English   中英

确定统一旋转角色的方向?

[英]Determining which direction to rotate a character in unity?

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

现在,不起作用的是向那个目标方向旋转身体。 我不希望 boid 立即锁定到 position,而是缓慢旋转。 我想要这个,因为它为身体的运动增加了很多变化。 运动采用 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 也会顺时针旋转。 我确切地知道为什么,但不知道如何解决它。 任何帮助,将不胜感激。

我不明白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来实现超平滑的解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM