Unity 第一人稱視角,鼠標控制鏡頭,WASD控制移動,按`鍵解鎖鼠標(仿和平精英)

using UnityEngine;

public class PlayerMove : MonoBehaviour
{
    private CharacterController _playerController;

    private Vector3 _direction;


    public float speed = 15;
    public float jumpPower = 5;
    public float gravity = 7f;


    public float mouseSpeed = 2f;


    public float minMouseY = -45f;
    public float maxMouseY = 45f;


    private float _rotationY = 0f;
    private float _rotationX = 0f;
    private bool _onOff;

    public Transform agretctCamera;


    private void Start()
    {
        _playerController = GetComponent<CharacterController>();
        Cursor.lockState = CursorLockMode.Locked;
        _onOff = true;
    }


    private void LateUpdate()
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        if (_playerController.isGrounded)
        {
            _direction = new Vector3(horizontal, 0, vertical);
            // if (Input.GetKeyDown(KeyCode.Space))
            //     _direction.y = jumpPower;
        }

        _direction.y -= gravity * Time.deltaTime;
        _playerController.Move(_playerController.transform.TransformDirection(_direction * (Time.deltaTime * speed)));

        if (_onOff)
        {
            _rotationX += agretctCamera.transform.localEulerAngles.y + Input.GetAxis("Mouse X") * mouseSpeed;
            _rotationY -= Input.GetAxis("Mouse Y") * mouseSpeed;
            _rotationY = Mathf.Clamp(_rotationY, minMouseY, maxMouseY);
            transform.eulerAngles = new Vector3(0, _rotationX, 0);
            agretctCamera.transform.eulerAngles = new Vector3(_rotationY, _rotationX, 0);
        }

        if (Input.GetKeyDown(KeyCode.BackQuote))
        {
            if (_onOff)
            {
                Cursor.lockState = CursorLockMode.None;
                _onOff = false;
            }
            else
            {
                Cursor.lockState = CursorLockMode.Locked;
                _onOff = true;
            }
        }
    }
}

 

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