unity相機自由移動

unity相機實現自由移動

分享一下項目中的的相機移動代碼。記錄學習過程,其中有參考別人的代碼,代碼可以直接使用。創建一個空物體爲相機的parent,就可以了

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

//巡遊模式攝像機控制
public class CameraMove : MonoBehaviour
{

    public static CameraMove Instance = null;
    public float smoothTime = 5f;
    private Vector3 dirVector3;
   
    private float paramater = 0.1f;
    //旋轉參數
    public float xspeed = -3f;
    public float yspeed = 3f;
    private Quaternion targetRot;
    private Quaternion cameraRot;
    
    public bool smooth;
    private float LookAngle;
    private float LookAngley;
    void Awake()
    {
        Instance = this;
    }

    private void Start()
    {
       
        targetRot = transform.parent.localRotation;
        cameraRot = transform.localRotation;
       
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        

        //移動
        dirVector3 = Vector3.zero;

        if (Input.GetKey(KeyCode.W))
        {
            if (Input.GetKey(KeyCode.LeftShift)) dirVector3.z = 3;
            else dirVector3.z = 1;
        }
        if (Input.GetKey(KeyCode.S))
        {
            if (Input.GetKey(KeyCode.LeftShift)) dirVector3.z = -3;
            else dirVector3.z = -1;
        }
        if (Input.GetKey(KeyCode.A))
        {
            if (Input.GetKey(KeyCode.LeftShift)) dirVector3.x = -3;
            else dirVector3.x = -1;
        }
        if (Input.GetKey(KeyCode.D))
        {
            if (Input.GetKey(KeyCode.LeftShift)) dirVector3.x = 3;
            else dirVector3.x = 1;
        }
        if (Input.GetKey(KeyCode.Q))
        {
            if (Input.GetKey(KeyCode.LeftShift)) dirVector3.y = -3;
            else dirVector3.y = -1;
        }
        if (Input.GetKey(KeyCode.E))
        {
            if (Input.GetKey(KeyCode.LeftShift)) dirVector3.y = 3;
            else dirVector3.y = 1;
        }
        transform.parent.transform.Translate(dirVector3 * paramater, Space.Self);
      
    }
    private void Update()
    {
        //按下右鍵旋轉
        if (!Input.GetMouseButton(1)) return;
        LookRotation();
      
    }

    public void LookRotation()
    {
        float yRot  = Input.GetAxis("Mouse X") ;
        float xRot  = Input.GetAxis("Mouse Y") ;
        LookAngle += xRot * xspeed;
        LookAngley += yRot * yspeed;
        targetRot = Quaternion.Euler(0f, LookAngley, 0f);
        cameraRot = Quaternion.Euler(LookAngle, 0f, 0f);

        if (smooth)
        {
            transform.parent.localRotation = Quaternion.Slerp(transform.parent.localRotation, targetRot, smoothTime * Time.deltaTime);
            transform.localRotation = Quaternion.Slerp(transform.localRotation, cameraRot, smoothTime * Time.deltaTime);
        }
        else
        {
            transform.parent.localRotation = targetRot;
            transform.localRotation = cameraRot;
        }
    }
}`
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章