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

猜你喜欢

转载自blog.csdn.net/weixin_45072334/article/details/105976116
今日推荐