玩家在Y轴上不想要的旋转

3
任何四元数天才能告诉我我的代码有什么问题吗?我有这个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;
}         

通过多次调整,我得出结论,问题似乎来自于射线投射部分,但我不明白为什么。

2个回答

1

我对四元数的经验主要仅限于使用FromToRotationLookRotation,并进行试错,直到它能够正常工作,所以我对四元数的了解不是很深入,但我认为可能发生了以下情况:

您检测了表面法线与上方向之间的旋转,然后将其添加到当前旋转中。问题在于,即使您当前的旋转已经与表面法线对齐,仍会添加该旋转,导致过度旋转。

enter image description here

你应该计算从你当前的向上方向到表面法线的旋转,或者像我下面做的那样,这相当容易理解:
使用你当前的旋转确定你想要朝向的方向。
lookDirection = transform.rotation * Vector3.forward

使用targetRotation来确定您想要朝上的方向。
upDirection = targetRotation * Vector3.up

使用Quaternion.LookRotation计算最终旋转角度

LookRotation(Vector3 forward, Vector3 upwards)

这将使您的射线投射块看起来像这样:

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

编辑:我在大学使用我的破电脑,所以我还没有测试过这个。


0

我知道这是一个旧帖子,而且我还不能评论答案,但Rishaan的答案对我有用,我只需要更改:

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

To:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接