81 lines
2.1 KiB
C#
81 lines
2.1 KiB
C#
|
|
using UnityEngine;
|
||
|
|
|
||
|
|
[RequireComponent(typeof(CharacterController))]
|
||
|
|
public class PlayerMovement : MonoBehaviour
|
||
|
|
{
|
||
|
|
public float moveSpeed = 4.5f;
|
||
|
|
public float mouseSensitivity = 2f;
|
||
|
|
public float gravity = -18f;
|
||
|
|
public CameraController cameraController;
|
||
|
|
|
||
|
|
private CharacterController controller;
|
||
|
|
private float verticalVelocity;
|
||
|
|
private float pitch;
|
||
|
|
|
||
|
|
private void Awake()
|
||
|
|
{
|
||
|
|
controller = GetComponent<CharacterController>();
|
||
|
|
}
|
||
|
|
|
||
|
|
private void Start()
|
||
|
|
{
|
||
|
|
Cursor.lockState = CursorLockMode.Locked;
|
||
|
|
Cursor.visible = false;
|
||
|
|
}
|
||
|
|
|
||
|
|
private void Update()
|
||
|
|
{
|
||
|
|
if (cameraController != null && cameraController.IsInFixedMode)
|
||
|
|
{
|
||
|
|
// During the attention shot the player should not move or rotate the camera.
|
||
|
|
ApplyGravityOnly();
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
LookAround();
|
||
|
|
Move();
|
||
|
|
}
|
||
|
|
|
||
|
|
private void LookAround()
|
||
|
|
{
|
||
|
|
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
|
||
|
|
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity;
|
||
|
|
|
||
|
|
transform.Rotate(Vector3.up * mouseX);
|
||
|
|
pitch = Mathf.Clamp(pitch - mouseY, -65f, 70f);
|
||
|
|
cameraController?.SetPitch(pitch);
|
||
|
|
}
|
||
|
|
|
||
|
|
private void Move()
|
||
|
|
{
|
||
|
|
float horizontal = Input.GetAxisRaw("Horizontal");
|
||
|
|
float vertical = Input.GetAxisRaw("Vertical");
|
||
|
|
|
||
|
|
// WASD is interpreted relative to the player's current view direction.
|
||
|
|
Vector3 direction = (transform.right * horizontal + transform.forward * vertical).normalized;
|
||
|
|
|
||
|
|
if (controller.isGrounded && verticalVelocity < 0f)
|
||
|
|
{
|
||
|
|
verticalVelocity = -1f;
|
||
|
|
}
|
||
|
|
|
||
|
|
verticalVelocity += gravity * Time.deltaTime;
|
||
|
|
|
||
|
|
Vector3 velocity = direction * moveSpeed;
|
||
|
|
velocity.y = verticalVelocity;
|
||
|
|
|
||
|
|
controller.Move(velocity * Time.deltaTime);
|
||
|
|
}
|
||
|
|
|
||
|
|
private void ApplyGravityOnly()
|
||
|
|
{
|
||
|
|
if (controller.isGrounded && verticalVelocity < 0f)
|
||
|
|
{
|
||
|
|
verticalVelocity = -1f;
|
||
|
|
}
|
||
|
|
|
||
|
|
verticalVelocity += gravity * Time.deltaTime;
|
||
|
|
controller.Move(Vector3.up * verticalVelocity * Time.deltaTime);
|
||
|
|
}
|
||
|
|
}
|