【问题标题】:Rotate player with platform without parenting无需育儿即可使用平台旋转播放器
【发布时间】:2018-03-25 13:32:40
【问题描述】:

我目前正在制作一个小型平台游戏 3D 游戏,但不幸的是我无法让玩家在骑着平台时正确旋转,这里的事情是我不想让玩家成为平台,到目前为止我已经设法让他随着平台顺利移动,但旋转仍然无处可去,这是我用于旋转的代码:

player.transform.rotation *= platform.rotation;

这是我得到的效果: Rotation Error 不大好 :( 我想解决方案很简单,一些公式,但不幸的是我的数学不太好:(所以,谢谢你们,希望你们能帮助我。

【问题讨论】:

  • 你想让玩家的轮换和平台的轮换一样吗?

标签: c# unity3d rotation


【解决方案1】:

我将向您展示一个简单的脚本示例,该示例通过输入使立方体旋转,同时对其所在平台的旋转做出反应:

using UnityEngine;

public class CubeRotation : MonoBehaviour {

    public GameObject Platform;
    Quaternion PreviousPlatformRotation;
    public float rotationSpeed = 50;

    private void Start() {
        PreviousPlatformRotation = Platform.transform.rotation;
    }

    private void Update() {
        //Rotate the cube by input
        if (Input.GetKey(KeyCode.A)) {
            transform.Rotate(Vector3.up, Time.deltaTime * rotationSpeed);
        }
        if (Input.GetKey(KeyCode.D)) {
            transform.Rotate(Vector3.up, -Time.deltaTime * rotationSpeed);
        }

        //Adjust rotation due to platform rotating
        if (Platform.transform.rotation != PreviousPlatformRotation) {
            var platformRotatedBy = Platform.transform.rotation * Quaternion.Inverse(PreviousPlatformRotation);
            transform.rotation *= platformRotatedBy;
            PreviousPlatformRotation = Platform.transform.rotation;
        }
    }
}

平台旋转调整的逻辑是这样的:

  1. 开始时获取平台的rotation 四元数(在您的情况下,当立方体对象爬上平台时获取它)
  2. 使用 AD 围绕局部 Y 轴正常旋转立方体。
  3. 然后检查平台的rotation是否发生了变化,如果是:

    3.a 获取自上一帧以来平台旋转了多少,操作Actual rotation * Inverse(Previous Rotation);这个操作类似于两个四元数之间的差异

    3.b 使用 *= 运算符将该四元数添加到多维数据集的 rotation

    3.c 将平台之前的旋转值设置为新的。

差不多了。

【讨论】:

  • 感谢您的帮助,但不幸的是我不知道为什么它根本不起作用。当我跳上平台时没有任何反应,这里是根据你写的代码:void LateUpdate() { _player.transform.position = transform.position + _movOffset; if (transform.rotation != PreviousPlatformRotation) { PreviousPlatformRotation = transform.rotation; platformRotatedBy = transform.rotation * Quaternion.Inverse(PreviousPlatformRotation); _player.transform.rotation *= platformRotatedBy; } }
  • 1) 不要在LateUpdate 中更新旋转,而是在Update 中更新 - 如果您这样做,旋转将更新一帧延迟; 2)您在四元数的“减法”之前执行PreviousPlatformRotation = transform.rotation;,这意味着之前的旋转与实际旋转之间没有区别,因此立方体不会随平台旋转。按照我发布的顺序使用我的代码。
  • 奇怪,我按照你说的做了,但是现在当我跳到平台上时,相机开始左右晃动,并且播放器没有旋转,只是晃动,这是代码的顺序行:'if (transform.rotation != PreviousPlatformRotation) { platformRotatedBy = transform.rotation * Quaternion.Inverse(PreviousPlatformRotation); _player.transform.rotation *= platformRotatedBy; PreviousPlatformRotation = transform.rotation; }'
  • 您使用的是FPSController 标准资产吗?
  • 是的,它是 Unity 第一人称角色控制器
猜你喜欢
  • 2015-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多