在 Unity 3D 中旋转对象

Rotate object in Unity 3D

我可以使用以下代码使用加速度计旋转对象。

transform.rotation = Quaternion.LookRotation(Input.acceleration.normalized, Vector3.up);

但我想旋转对象,例如屏幕正在旋转 - 0、90、180 和 360 度。我如何使用 Unity 3D 来实现?

您可以这样使用 transform.rotation

transform.rotation = new Quaternion(rotx, roty, rotz, rotw);

您可以这样使用 transform.Rotate

transform.Rotate(rotx, roty, rotz);

Documentation for Quaternion

Documentation for transform.rotation

带有加速度计输入的旋转屏幕示例:

float accelx, accely, accelz = 0;

void Update ()
{
    accelx = Input.acceleration.x;
    accely = Input.acceleration.y;
    accelz = Input.acceleration.z;
    transform.Rotate (accelx * Time.deltaTime, accely * Time.deltaTime, accelz * Time.deltaTime);
}

如果要将对象旋转到特定角度,请使用:

float degrees = 90;
Vector3 to = new Vector3(degrees, 0, 0);

transform.eulerAngles = Vector3.Lerp(transform.rotation.eulerAngles, to, Time.deltaTime);

这将绕 x 轴旋转 90 度。

为了自己旋转你的游戏对象

int _rotationSpeed = 15;

void Update () {

    // Rotation on y axis
    // be sure to capitalize Rotate or you'll get errors
    transform.Rotate(0, _rotationSpeed * Time.deltaTime, 0);
}

您只需在 .cs 脚本中添加以下行即可旋转对象。

transform.Rotate(Vector3.up,这里可以放水平速度);

如果您想将其添加到游戏对象中,您可以将游戏对象放入脚本中:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TheNameOfYourScriptHere : MonoBehaviour
{
    public float speed = 100;
    
    public GameObject yourgameobject;
    
    void Update()
    {
          yourgameobject.transform.Rotate(0, speed * Time.deltaTime, 0);
    }
}

请注意,此旋转速度更快,因此您可以更好地查看它的运行情况。