102 lines
2.7 KiB
C#
102 lines
2.7 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class HeroController : MonoBehaviour
|
|
{
|
|
[Header("Øâèäê³ñòü ðóõó")]
|
|
[Range(1f, 20f)]
|
|
[SerializeField] private float _movementSpeed = 5f;
|
|
|
|
[Header("Ïðèñêîðåííÿ ðóõó")]
|
|
[Range(1f, 5f)]
|
|
[SerializeField] private float _runMultiplier = 2f;
|
|
|
|
[Header("Ãðàâ³òàö³ÿ")]
|
|
[SerializeField] private float _gravity = -9.81f;
|
|
|
|
[Header("Ñèëà ñòðèáêó")]
|
|
[Range(1f, 20f)]
|
|
[SerializeField] private float _jumpHeight = 2f;
|
|
|
|
[Header("Íàëàøòóâàííÿ ïðèñ³äàííÿ")]
|
|
[SerializeField] private KeyCode _crouchKey = KeyCode.C;
|
|
|
|
private CharacterController _characterController;
|
|
private Vector3 _controllerVelocity;
|
|
private bool _isCrouching = false;
|
|
|
|
void Start()
|
|
{
|
|
_characterController = GetComponent<CharacterController>();
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
HandleCrouch();
|
|
HandleMovement();
|
|
HandleGravity();
|
|
HandleJump();
|
|
}
|
|
|
|
private void HandleCrouch()
|
|
{
|
|
if (Input.GetKeyDown(_crouchKey))
|
|
{
|
|
if (!_isCrouching)
|
|
{
|
|
transform.localScale = new Vector3(0.2f, 0.3f, 0.2f);
|
|
_characterController.height = 0.54f;
|
|
_characterController.center = new Vector3(0, -0.63f, 0);
|
|
_isCrouching = true;
|
|
}
|
|
else
|
|
{
|
|
transform.localScale = new Vector3(0.2f, 0.8f, 0.2f);
|
|
_characterController.height = 1.8f;
|
|
_characterController.center = new Vector3(0, 0, 0);
|
|
_isCrouching = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
private void HandleMovement()
|
|
{
|
|
float moveX = Input.GetAxis("Horizontal");
|
|
float moveZ = Input.GetAxis("Vertical");
|
|
Vector3 movement = transform.right * moveX + transform.forward * moveZ;
|
|
|
|
float currentSpeed = _movementSpeed;
|
|
|
|
if (Input.GetKey(KeyCode.LeftShift) && !_isCrouching)
|
|
{
|
|
currentSpeed *= _runMultiplier;
|
|
}
|
|
else if (_isCrouching)
|
|
{
|
|
currentSpeed *= 0.5f;
|
|
}
|
|
|
|
_characterController.Move(movement * currentSpeed * Time.deltaTime);
|
|
}
|
|
|
|
private void HandleGravity()
|
|
{
|
|
if (_characterController.isGrounded && _controllerVelocity.y < 0)
|
|
{
|
|
_controllerVelocity.y = -2f;
|
|
}
|
|
|
|
_controllerVelocity.y += _gravity * Time.deltaTime;
|
|
_characterController.Move(_controllerVelocity * Time.deltaTime);
|
|
}
|
|
|
|
private void HandleJump()
|
|
{
|
|
if (Input.GetButtonDown("Jump") && _characterController.isGrounded)
|
|
{
|
|
_controllerVelocity.y = Mathf.Sqrt(_jumpHeight * -2f * _gravity);
|
|
}
|
|
}
|
|
}
|