簡體   English   中英

在 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);

四元數的文檔

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
    transfrom.rotate (0, _rotationSpeed * Time.deltaTime, 0);
}

您可以通過在 .cs 腳本中添加以下行來旋轉對象。

transform.Rotate(Vector3.up,這里可以放horizo​​natl speed);

如果您希望將此添加到游戲對象中,您可以將游戲對象放入腳本中:

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);
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM