gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:42:28 26 4
gpt4 key购买 nike

任何四元数天才都可以告诉我我的代码有什么问题吗?我有这个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com