1. 程式人生 > >[Unity基礎]對Rotation的一些理解與例項(一)

[Unity基礎]對Rotation的一些理解與例項(一)

using UnityEngine;
using System.Collections;

public class TestRotation : MonoBehaviour{

	// Update is called once per frame
	void Update () 
    {
        //編輯器上,Transform元件上的Rotation即為eulerAngles
        //假如Rotation為20.5  40.7  80.9,則eulerAngles也為20.5  40.7  80.9
        if (Input.GetKeyDown(KeyCode.Q)) print("eulerAngles" + transform.eulerAngles);
        if (Input.GetKeyDown(KeyCode.W)) print("rotation" + transform.rotation);


        //沿某個軸,旋轉到某個角度(每次呼叫AngleAxis函式,eulerAngles先會被重置為(0,0,0),再繞某軸旋轉)
        //特點:非旋轉軸的其餘兩個軸,值均為0
        //假如Rotation為20.5  40.7  80.9
        if (Input.GetKeyDown(KeyCode.A)) transform.rotation = Quaternion.AngleAxis(30, Vector3.right);////繞x軸旋轉30度,編輯器上的Rotation變為30 0 0
        if (Input.GetKeyDown(KeyCode.S)) transform.rotation = Quaternion.AngleAxis(60, Vector3.up);//繞y軸旋轉60度,編輯器上的Rotation變為0 60 0
        if (Input.GetKeyDown(KeyCode.D)) transform.rotation = Quaternion.AngleAxis(90, Vector3.forward);//繞z軸旋轉90度,編輯器上的Rotation變為0 0 90

        
        //直接修改eulerAngles
        if (Input.GetKeyDown(KeyCode.E)) transform.rotation = Quaternion.Euler(new Vector3(45, 180, 135));//編輯器上的Rotation變為45 180 135
        //等同於 if (Input.GetKeyDown(KeyCode.R)) transform.eulerAngles = new Vector3(45, 180, 135);//編輯器上的Rotation變為45 180 135


        //沿某個軸,旋轉到某個角度
        //假如Rotation為20.5  40.7  80.9
        if (Input.GetKeyDown(KeyCode.Z)) transform.rotation = Quaternion.Euler(transform.eulerAngles + new Vector3(50, 0, 0));//繞x軸旋轉50度,編輯器上的Rotation變為70.5  40.7  80.9
        if (Input.GetKeyDown(KeyCode.X)) transform.rotation = Quaternion.Euler(transform.eulerAngles + new Vector3(0, 100, 0));//繞y軸旋轉100度,編輯器上的Rotation變為70.5  140.7  80.9
        if (Input.GetKeyDown(KeyCode.C)) transform.rotation = Quaternion.Euler(transform.eulerAngles + new Vector3(0, 0, 150));//繞z軸旋轉150度,編輯器上的Rotation變為70.5  140.7  230.9


        //if (Input.GetKeyDown(KeyCode.V)) transform.eulerAngles += new Vector3(50, 0, 0);//繞x軸旋轉50度,編輯器上的Rotation變為70.5  40.7  80.9
        //if (Input.GetKeyDown(KeyCode.B)) transform.eulerAngles += new Vector3(0, 100, 0);//繞y軸旋轉100度,編輯器上的Rotation變為70.5  140.7  80.9
        //if (Input.GetKeyDown(KeyCode.N)) transform.eulerAngles += new Vector3(0, 0, 150);//繞z軸旋轉150度,編輯器上的Rotation變為70.5  140.7  230.9

	}
}

       由於Unity幫我們封裝好了一些類,減少了數學上的運算,所以對於物體旋轉的操作,熟悉一下eulerAngles和Quaternion的一些方法就可以解決很多旋轉上的問題了。