78 lines
2.6 KiB
C#
78 lines
2.6 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
[RequireComponent(typeof(CharacterController))]
|
|
public class FPSController : MonoBehaviour
|
|
{
|
|
public Camera playerCamera;
|
|
public float walkSpeed = 6f;
|
|
public float runSpeed = 12f;
|
|
public float jumpPower = 7f;
|
|
public float gravity = 20f;
|
|
public float lookSpeed = 2f;
|
|
public float lookXLimit = 45f;
|
|
public float bhopMultiplierIncrement = 0.05f;
|
|
public float maxBhopSpeed = 20f;
|
|
|
|
Vector3 moveDirection = Vector3.zero;
|
|
float rotationX = 0;
|
|
float bhopMultiplier = 1f;
|
|
bool isJumping = false;
|
|
bool wasRunning = false;
|
|
|
|
public bool canMove = true;
|
|
|
|
CharacterController characterController;
|
|
|
|
void Start()
|
|
{
|
|
characterController = GetComponent<CharacterController>();
|
|
Cursor.lockState = CursorLockMode.Locked;
|
|
Cursor.visible = false;
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
Vector3 forward = transform.TransformDirection(Vector3.forward);
|
|
Vector3 right = transform.TransformDirection(Vector3.right);
|
|
bool isRunning = characterController.isGrounded ? Input.GetKey(KeyCode.LeftShift) : wasRunning;
|
|
wasRunning = isRunning;
|
|
float curSpeedX = canMove ? ((isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Vertical")) * bhopMultiplier : 0;
|
|
float curSpeedY = canMove ? ((isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Horizontal")) * bhopMultiplier : 0;
|
|
float movementDirectionY = moveDirection.y;
|
|
moveDirection = (forward * curSpeedX) + (right * curSpeedY);
|
|
|
|
if (Input.GetButton("Jump") && canMove && characterController.isGrounded)
|
|
{
|
|
moveDirection.y = jumpPower;
|
|
bhopMultiplier = Mathf.Min(bhopMultiplier + bhopMultiplierIncrement, maxBhopSpeed / (isRunning ? runSpeed : walkSpeed));
|
|
isJumping = true;
|
|
}
|
|
else
|
|
{
|
|
moveDirection.y = movementDirectionY;
|
|
}
|
|
|
|
if (!characterController.isGrounded)
|
|
{
|
|
moveDirection.y -= gravity * Time.deltaTime;
|
|
}
|
|
else if (!Input.GetButton("Jump"))
|
|
{
|
|
bhopMultiplier = 1f;
|
|
isJumping = false;
|
|
}
|
|
|
|
characterController.Move(moveDirection * Time.deltaTime);
|
|
|
|
if (canMove)
|
|
{
|
|
rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
|
|
rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
|
|
playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
|
|
transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
|
|
}
|
|
}
|
|
}
|