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

标签 c# unity-game-engine

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

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

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;
            }
        }
    }

(角度基于单位圆)

我真的很喜欢它如何让主体快速旋转,并在主体达到所需角度时减慢速度。 因此,这段代码可以正常工作,除非当前旋转角度约为 350 度,并且目标方向约为 10 度。即使最短路径是逆时针的,机器人也会顺时针旋转。我确切地知道原因,但不知道如何解决。任何帮助将不胜感激。

最佳答案

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

关于c# - 确定统一旋转角色的方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63095997/

相关文章:

iphone - 角色移动时 iOS FPS 低帧率,探查器显示 Physics.Simulate 占用 CPU 时间

c# - wpf windows 位置问题

c# - 编译导致双重警告

c# - 由于缺少 `Application` 引用,Outlook 代码编译错误

统一按下输入字段时,Android 键盘不显示?

ios - Unity3D/iOS : Running a shell script post-Xcode build

c# - IIS 应用程序池管理和最佳实践

c# - 绑定(bind)数据模板控件属性

c# - 尝试创建嵌套的 ScriptableObject : "AddAssetToSameFile failed because the other asset is not persistent"

java - Unity android 插件 - 广告不会出现在屏幕底部