【问题标题】:Player unwanted rotation on the Y axis玩家在 Y 轴上不需要的旋转
【发布时间】:2019-05-12 18:25:24
【问题描述】:

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

经过多次调整后得出的结论是问题似乎来自光线投射部分,但我不明白为什么

【问题讨论】:

    标签: c# visual-studio unity3d


    【解决方案1】:

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

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

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

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

    lookDirection = transform.rotation * Vector3.forward
    

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

    upDirection = targetRotation * Vector3.up
    

    并使用Quaternion.LookRotation计算您的最终轮换

    LookRotation(Vector3 向前,Vector3 向上)

    导致你的光线投射块看起来像这样:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      相关资源
      最近更新 更多