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

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

第一人稱相機觀察:

using UnityEngine;
using System.Collections;

//第一人稱相機觀察
public class CameraObserve : MonoBehaviour {
    
	// Update is called once per frame
	void Update () 
    {
        float mouseX = Input.GetAxis("Mouse X");
        float mouseY = Input.GetAxis("Mouse Y");

        //要麼上下觀察,要麼左右觀察
        if (Mathf.Abs(mouseX) > Mathf.Abs(mouseY))
            transform.eulerAngles += new Vector3(0, mouseX, 0);
        else
            transform.eulerAngles += new Vector3(-mouseY, 0, 0);//攝像機繞x軸旋轉的方向跟滑鼠y移動方向相反
	}
}

物體平滑自轉90度:
using UnityEngine;
using System.Collections;

//物體平滑自轉90度
public class RotateSelf : MonoBehaviour {

    bool isRotateSelf = false;
    Vector3 targetEuler = Vector3.zero;

	// Update is called once per frame
	void Update () 
    {
        if (Input.GetKeyDown(KeyCode.R))
        {
            isRotateSelf = true;
            targetEuler = transform.eulerAngles + new Vector3(0, 90, 0);
        }
        if (Input.GetKeyDown(KeyCode.T))
            isRotateSelf = false;

        //平滑轉90度
        if(isRotateSelf)
            transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(targetEuler), Time.deltaTime);
	}
}