Unity 鼠標控制俯視相機的平移移動、限制移動範圍和放大縮小

using UnityEngine;

public class CameraController : MonoBehaviour
{
    //控制視野縮放的速率
    private float _viewValue;

    //控制攝像機移動的速率
    private float _moveSpeed;
    private Camera _camera;

    private void Start()
    {
        _camera = gameObject.GetComponent<Camera>();
        _viewValue = 20f;
        _moveSpeed = 50f;
    }

    void Update()
    {
        //放大
        if (Input.GetAxis("Mouse ScrollWheel") < 0)
        {
            if (_camera.orthographicSize <= 3000)
                _camera.orthographicSize += _viewValue;
        }

        //縮小
        if (Input.GetAxis("Mouse ScrollWheel") > 0)
        {
            if (_camera.orthographicSize >= 50)
                _camera.orthographicSize -= _viewValue;
        }

        //移動視角
        if (Input.GetMouseButton(1)) return;
        transform.Translate(Vector3.left * (Input.GetAxis("Mouse X") * _moveSpeed));
        transform.Translate(Vector3.up * (Input.GetAxis("Mouse Y") * -_moveSpeed));
        //限制移動的範圍
        var position = gameObject.transform.position;
        position = new Vector3(Mathf.Clamp(position.x, -7500, -3500), 2000,
            Mathf.Clamp(position.z, -4000, 4000));
        gameObject.transform.position = position;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章