84 lines
3.0 KiB
C#
84 lines
3.0 KiB
C#
using UnityEngine;
|
||
using UnityEngine.InputSystem;
|
||
|
||
[RequireComponent(typeof(CharacterController))]
|
||
public class PlayerMovement : MonoBehaviour
|
||
{
|
||
[Header("Настройки скорости")]
|
||
public float walkSpeed = 3.0f; // Обычный шаг
|
||
public float runSpeed = 6.0f; // Бег (Shift)
|
||
public float sneakSpeed = 1.5f; // Тактический шаг (Ctrl)
|
||
|
||
[Header("Настройки вращения")]
|
||
public float turnSmoothTime = 0.1f; // Плавность поворота модельки
|
||
private float turnSmoothVelocity;
|
||
|
||
[Header("Камера")]
|
||
public Transform cam; // Ссылка на главную камеру
|
||
|
||
private CharacterController controller;
|
||
private Vector3 velocity;
|
||
private float gravity = -9.81f;
|
||
|
||
void Start()
|
||
{
|
||
controller = GetComponent<CharacterController>();
|
||
|
||
// Скрываем и блокируем курсор
|
||
Cursor.lockState = CursorLockMode.Locked;
|
||
Cursor.visible = false;
|
||
}
|
||
|
||
void Update()
|
||
{
|
||
HandleMovement();
|
||
}
|
||
|
||
void HandleMovement()
|
||
{
|
||
// Гравитация
|
||
if (controller.isGrounded && velocity.y < 0)
|
||
{
|
||
velocity.y = -2f;
|
||
}
|
||
|
||
float currentSpeed = walkSpeed;
|
||
float horizontal = 0f;
|
||
float vertical = 0f;
|
||
|
||
// Читаем ввод с клавиатуры через New Input System
|
||
var keyboard = Keyboard.current;
|
||
if (keyboard != null)
|
||
{
|
||
// Ускорение и замедление
|
||
if (keyboard.leftShiftKey.isPressed) currentSpeed = runSpeed;
|
||
else if (keyboard.leftCtrlKey.isPressed) currentSpeed = sneakSpeed;
|
||
|
||
// Направления (WASD)
|
||
if (keyboard.dKey.isPressed) horizontal += 1f;
|
||
if (keyboard.aKey.isPressed) horizontal -= 1f;
|
||
if (keyboard.wKey.isPressed) vertical += 1f;
|
||
if (keyboard.sKey.isPressed) vertical -= 1f;
|
||
}
|
||
|
||
Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
|
||
|
||
if (direction.magnitude >= 0.1f)
|
||
{
|
||
// Вычисляем угол поворота с учетом направления камеры
|
||
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
|
||
|
||
// Плавно поворачиваем капсулу
|
||
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
|
||
transform.rotation = Quaternion.Euler(0f, angle, 0f);
|
||
|
||
// Двигаем контроллер
|
||
Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
|
||
controller.Move(moveDir.normalized * currentSpeed * Time.deltaTime);
|
||
}
|
||
|
||
// Применяем гравитацию
|
||
velocity.y += gravity * Time.deltaTime;
|
||
controller.Move(velocity * Time.deltaTime);
|
||
}
|
||
} |