首页 文章

如何在Unity中使用陀螺仪移动相机

提问于
浏览
0

我有一个横向的Unity游戏 . 我希望能够将相机向左和向右旋转 . 此外,我想根据y轴上的陀螺仪倾斜以及向右或向左旋转的总矢量来前后移动相机 . 换句话说,我希望能够像走在房间里的人一样移动相机 . 相机是我游戏的主要玩家 .

这就是我试图做的事情:

GameObject CamParent;
Rigidbody RB;

void Start()
{

    CamParent = new GameObject("CamParent");
    CamParent.transform.position = this.transform.position;
    this.transform.parent = CamParent.transform;
    Input.gyro.enabled = true;
    RB = this.GetComponent<Rigidbody>();
}

void Update()
{
    CamParent.transform.Rotate(0, -Input.gyro.rotationRateUnbiased.y, 0);
    this.transform.Rotate(-Input.gyro.rotationRateUnbiased.x, 0,0);
    float Z = -Input.gyro.userAcceleration.z;
    RB.AddForce(new Vector3(0,0,Z)*10);
}

1 回答

  • 2

    我尽力回答你的问题,因为你的问题对我来说有点不清楚 .

    首先,由于您使用的是力和物理,因此您应该使用 void FixedUpdate() 函数而不是 void Update() 函数 . 这将确保您的代码以统一的间隔执行,这在处理物理时非常重要 .

    我也不确定你为什么要实例化一个新的GameObject . 您只需将此脚本添加到Unity中的Camera GameObject,然后将Rigidbody组件添加到Camera . 这将简化您的 Start() 函数,该函数应该只包含以下两行:

    Input.gyro.enabled = true;
    RB = gameObject.GetComponent<Rigidbody>();
    

    接下来,重要的是要注意从 Input.gyro.attide 返回的Quaternion具有左手坐标,而Unity具有右手坐标 . 从陀螺仪到Unity的这种转换可以通过以下功能完成:

    Quaternion GyroToUnity(Quaternion quat)
    {
        return new Quaternion(quat.x, quat.z, quat.y, -quat.w);
    }
    

    我确信还有其他方法可以实现这种转换,但这种方式对我有用 .

    现在让's deal with the Camera'旋转 . 首先将Camera 's rotation by setting the camera' s transform.rotation 设置为等于刚从Gyroscope转换的Quaternion . 有's one more problem, however, since Gyroscope z-axis points in the same direction as Unity'的y轴 . 只需执行 transform.Rotate(90,0,0); 即可解决此问题 . 最后,我们使用以下代码行设置Camera的旋转:

    transform.rotation = Quaternion.Euler(new Vector3(0f, transform.rotation.eulerAngles.y, 0f));
    

    最后我们必须处理向相机添加力量 . 我'm not sure exactly how you want movement to be handled, but I assumed you wanted movement about the z-axis with respect to the Camera'的轮换 . 为此,您需要使用相机上Rigidbody组件的 AddRelativeForce(Vector3 relativeForce) .

    但是,为了确定力的方向,我们必须从我们之前转换为Unity的四元数中获取围绕x轴的旋转度 . yourQuat.eulerAngles.x ,返回一个 float ,使得0 <= x <360.通过我们定向相机坐标系的方式,面向iOS设备的直线向前应该返回大约0.0的值 . 当我玩这个问题时,我发现这段代码充分指导了相机:

    Vector3 relativeForce;
    if (yourQuat.eulerAngles.x > 315 || yourQuat.eulerAngles.x < 90)
        relativeForce = Vector3.forward;
    else if (yourQuat.eulerAngles.x < 315)
        relativeForce = Vector3.back;
    else
        relativeForce = Vector3.zero;
    

    最后取后续 Vector3 值并使用如此

    RB.AddRelativeForce(relativeForce);

    希望有所帮助 . 如果这不是您正在寻找的确切功能,这将为您提供一个良好的开端来微调您的程序,使其完全符合您的要求 .

相关问题