c# - 玩家在 Y 轴上不需要的旋转

标签 c# visual-studio unity3d

任何四元数天才都可以告诉我我的代码有什么问题吗?我有这个 PlayerRotation 脚本,它可以做两件事:

局部旋转玩家的Y轴

将玩家与表面的法线对齐

PlayerMovement 只是让玩家在 transform.forward 轴上前进。问题是,当我开始播放并在一些颠倒的表面上播放时,我的播放器的 Y 轴随操纵杆随机偏移,就像向前倾斜操纵杆会使播放器稍微向右旋转

input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
Vector2 inputDir = input.normalized;
//Angle part
if (inputDir != Vector2.zero)
{
    targetAngle = Mathf.Atan2(input.x, input.y) * Mathf.Rad2Deg + cam.eulerAngles.y;
    Quaternion localRotation = Quaternion.Euler(0f, targetAngle - lastTargetAngle, 0f);
    transform.rotation = transform.rotation * localRotation;
    lastTargetAngle = targetAngle;
}
//Raycast part
if (Physics.Raycast(transform.position - transform.up * start, -transform.up, out hit, end))
{
    Quaternion targetRotation = Quaternion.FromToRotation(transform.up, hit.normal);
    transform.rotation = targetRotation * transform.rotation;
}         

经过多次调整后得出结论,问题似乎出在光线转换部分,但我不明白为什么

最佳答案

我在四元数方面的经验几乎仅限于使用 FromToRotationLookRotation 并反复试验直到我开始工作,所以我不是最了解四元数的但这是我认为正在发生的事情:

您正在检测表面法线和向上矢量之间的旋转,然后将其添加到当前旋转。这样做的问题是,即使您当前的旋转已经与表面法线对齐,您仍然会添加该旋转,导致它过度旋转。

enter image description here

你应该做的是计算从当前向上方向到表面法线的旋转,或者像我在下面做的那样,这很容易理解:

使用您当前的旋转来确定您想要查看的方向

lookDirection = transform.rotation * Vector3.forward

并使用您的 targetRotation 来确定您想要向上的方向

upDirection = targetRotation * Vector3.up

并使用 Quaternion.LookRotation 计算您的最终旋转

LookRotation(Vector3 forward, Vector3 upwards)

导致您的光线转换 block 看起来像这样:

Quaternion targetRotation = Quaternion.FromToRotation(transform.up, hit.normal);
transform.rotation = Quaternion.LookRotation(transform.rotation * Vector3.forward, targetRotation * Vector3.up);

编辑:我在 Uni 使用我的 craptop,所以我还没有实际测试过。

关于c# - 玩家在 Y 轴上不需要的旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56102198/

相关文章:

c# - 在 C# 中使用 Access 2010 数据库

visual-studio - 如何在 Visual Studio 中突出显示用户指定的单词?

c++ - 链接器问题 VS2015。 LNK2019 和 LNK2001 未解析的外部符号

C# 在字典/列表中存储类类型

swift 3 : Unity Integration leads to crash on app lauch

c# - 保存多个同名文件

c# - 将 LINQ 表达式从 C# 转换为 VB.NET 在 Group by 中引发异常

c# - 任何人都可以解释图形数据结构的 java 或 C# 实现吗

visual-studio - 当 tsconfig.json 在项目中时,保存时的 typescript 编译不起作用

c# - 统一场景之间的自动淡入淡出不适用于 OSX