c# - 在没有 parent 的情况下使用平台旋转播放器

标签 c# unity3d rotation

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

player.transform.rotation *= platform.rotation;

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

最佳答案

我将向您展示一个简单的脚本示例,它使立方体根据输入旋转,同时对其所在平台的旋转使用react:

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. 开始获取平台的旋转四元数(在你的例子中,当立方体对象爬上平台时获取它)
  2. 使用 AD 围绕局部 Y 轴正常旋转立方体。
  3. 之后检查平台的rotation是否改变,如果是:

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

    3.b 使用*= 运算符将四元数添加到立方体的旋转

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

差不多就这些了。<​​/p>

关于c# - 在没有 parent 的情况下使用平台旋转播放器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49476439/

相关文章:

c# - 在 UserControl WPF 的视口(viewport)中使用 VisualBrush

ios - 将 Swift 集成到导出的 Unity 项目中而不是使用 Objective C?

Unity3d 编辑器 : how to prevent changes from being undone upon exiting play mode?

c# - 直接通过C#中的实例连接

c# - 如何将一些 C# 代码转换为 Pascal?

c# - 如何在保存后立即检索 objectId

c++ - glm glx 旋转不起作用

actionscript-3 - AS3 围绕其中心点旋转对象

XNA Vector2 旋转问题

c# - Double.doubleToLongBits 在 C# 中等效?