95 lines
2.3 KiB
C#
95 lines
2.3 KiB
C#
using UnityEngine;
|
|
|
|
namespace ShiningGames.Prototyping
|
|
{
|
|
[RequireComponent(typeof(CharacterController))]
|
|
public class FPSController : MonoBehaviour
|
|
{
|
|
public float movementSpeed = 5f;
|
|
|
|
public float mouseSensitivity = 2f;
|
|
|
|
public float jumpForce = 7f;
|
|
|
|
public float crouchHeight = 0.5f;
|
|
|
|
public float standHeight = 2f;
|
|
|
|
public float crouchSpeed = 2f;
|
|
|
|
private CharacterController characterController;
|
|
|
|
private Vector3 moveDirection;
|
|
|
|
private bool isCrouching;
|
|
|
|
private Camera playerCamera;
|
|
|
|
private float originalCameraHeight;
|
|
|
|
private void Start()
|
|
{
|
|
characterController = GetComponent<CharacterController>();
|
|
playerCamera = Camera.main;
|
|
originalCameraHeight = playerCamera.transform.localPosition.y;
|
|
Cursor.lockState = CursorLockMode.Locked;
|
|
Cursor.visible = false;
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
MovePlayer();
|
|
LookAround();
|
|
Jump();
|
|
}
|
|
|
|
private void MovePlayer()
|
|
{
|
|
float axis = Input.GetAxis("Horizontal");
|
|
float axis2 = Input.GetAxis("Vertical");
|
|
Vector3 vector = base.transform.forward * axis2;
|
|
Vector3 vector2 = base.transform.right * axis;
|
|
moveDirection = (vector + vector2).normalized * movementSpeed;
|
|
if (!characterController.isGrounded)
|
|
{
|
|
moveDirection.y += Physics.gravity.y * Time.deltaTime;
|
|
}
|
|
characterController.Move(moveDirection * Time.deltaTime);
|
|
}
|
|
|
|
private void LookAround()
|
|
{
|
|
float num = Input.GetAxis("Mouse X") * mouseSensitivity;
|
|
float num2 = Input.GetAxis("Mouse Y") * mouseSensitivity;
|
|
base.transform.Rotate(Vector3.up * num);
|
|
playerCamera.transform.Rotate(Vector3.left * num2);
|
|
}
|
|
|
|
private void Jump()
|
|
{
|
|
if (characterController.isGrounded && Input.GetButtonDown("Jump"))
|
|
{
|
|
moveDirection.y = jumpForce;
|
|
}
|
|
}
|
|
|
|
private void Crouch()
|
|
{
|
|
if (Input.GetButtonDown("Crouch"))
|
|
{
|
|
isCrouching = !isCrouching;
|
|
if (isCrouching)
|
|
{
|
|
characterController.height = crouchHeight;
|
|
playerCamera.transform.localPosition = new Vector3(playerCamera.transform.localPosition.x, originalCameraHeight - crouchSpeed, playerCamera.transform.localPosition.z);
|
|
}
|
|
else
|
|
{
|
|
characterController.height = standHeight;
|
|
playerCamera.transform.localPosition = new Vector3(playerCamera.transform.localPosition.x, originalCameraHeight, playerCamera.transform.localPosition.z);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|