| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- [RequireComponent(typeof(CharacterController))]
- public class PlayerController : MonoBehaviour
- {
- CharacterController cc;
- public Transform ftpCamera;
- private float mouseX, mouseY;//鼠标的移动值
- public float mouseSensitivity = 120f;//鼠标灵敏度
- //限制鼠标y轴
- public float minMouseY = -70f;
- public float maxMouseY = 70f;
- private float xRotation;
- public float moveSpeed = 20f;
- public float jumpSpeed = 50f;
- private float hMove, vMove;
- private Vector3 dir;
- public float gravity = 9.81f;//重力
- private Vector3 velocity;
- public Transform groundCheck;
- public float checkRadius=0.5f;
- public LayerMask groundLayer;
- private bool isGround;
- private bool isLock;
- // Start is called before the first frame update
- void Start()
- {
- cc = GetComponent<CharacterController>();
- Cursor.lockState = CursorLockMode.Locked;
- Cursor.visible = false;
- isLock = false;
- }
- // Update is called once per frame
- void Update()
- {
- if (Input.GetKeyDown(KeyCode.Q))
- {
- if (isLock)
- {
- Cursor.lockState = CursorLockMode.Locked;
- Cursor.visible = false;
- isLock = false;
- }
- else
- {
- Cursor.lockState = CursorLockMode.None;
- Cursor.visible = true;
- isLock = true;
- }
- }
- if (isLock)
- {
- return;
- }
- mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
- mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
- xRotation -= mouseY;
- xRotation = Mathf.Clamp(xRotation, minMouseY, maxMouseY);
- transform.Rotate(Vector3.up * mouseX);
- ftpCamera.localRotation = Quaternion.Euler(xRotation, 0, 0);
- isGround = Physics.CheckSphere(groundCheck.position, checkRadius, groundLayer);
- if (isGround && velocity.y < 0)
- {
- velocity.y = -1f;
- }
- hMove = Input.GetAxis("Horizontal") * moveSpeed;
- vMove = Input.GetAxis("Vertical") * moveSpeed;
- dir = transform.forward * vMove + transform.right * hMove;
- cc.Move(dir * Time.deltaTime);
- if (Input.GetButtonDown("Jump") && isGround)
- {
- velocity.y = jumpSpeed;
- }
- velocity.y -= gravity * Time.deltaTime;
- cc.Move(velocity * Time.deltaTime);
- }
- }
|