First Commit
This commit is contained in:
commit
eed6b79efc
2836 files changed
+948481
No files matched your search
@@ -0,0 +1,52 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class PlayerInputHandler : MonoBehaviour
|
||||
{
|
||||
[Header("Components")]
|
||||
[SerializeField] private PlayerMovement playerMovement;
|
||||
[SerializeField] private PlayerLook playerLook;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
if (playerMovement == null) playerMovement = GetComponent<PlayerMovement>();
|
||||
if (playerLook == null) playerLook = GetComponentInChildren<PlayerLook>();
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
// Пока открыто меню/планшет/окно торга — игрок стоит на месте (гравитация продолжает работать)
|
||||
if (GameInputLock.IsLocked)
|
||||
{
|
||||
if (playerMovement != null) playerMovement.ProcessMove(Vector2.zero);
|
||||
return;
|
||||
}
|
||||
|
||||
HandleMovementInput();
|
||||
HandleLookInput();
|
||||
}
|
||||
|
||||
private void HandleMovementInput()
|
||||
{
|
||||
// Читаем оси WASD. GetAxisRaw дает более резкое, отзывчивое управление без инерции.
|
||||
float horizontal = Input.GetAxisRaw("Horizontal");
|
||||
float vertical = Input.GetAxisRaw("Vertical");
|
||||
|
||||
// Нормализуем вектор, чтобы игрок не двигался быстрее по диагонали
|
||||
Vector2 moveInput = new Vector2(horizontal, vertical).normalized;
|
||||
|
||||
if (playerMovement != null)
|
||||
playerMovement.ProcessMove(moveInput);
|
||||
}
|
||||
|
||||
private void HandleLookInput()
|
||||
{
|
||||
// Читаем движение мыши
|
||||
float mouseX = Input.GetAxis("Mouse X");
|
||||
float mouseY = Input.GetAxis("Mouse Y");
|
||||
|
||||
Vector2 lookInput = new Vector2(mouseX, mouseY);
|
||||
|
||||
if (playerLook != null && playerLook.enabled)
|
||||
playerLook.ProcessLook(lookInput);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 00826943886c407c952993731de997e0
|
||||
timeCreated: 1789818508
|
||||
@@ -0,0 +1,53 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class PlayerLook : MonoBehaviour
|
||||
{
|
||||
[Header("Look Settings")]
|
||||
[SerializeField] private float mouseSensitivity = 150f;
|
||||
[SerializeField] private Transform playerBody;
|
||||
|
||||
private float xRotation = 0f;
|
||||
|
||||
public float Sensitivity => mouseSensitivity;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
if (playerBody == null) playerBody = transform.parent != null ? transform.parent : transform;
|
||||
mouseSensitivity = PlayerPrefs.GetFloat("perekup_sensitivity", mouseSensitivity);
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
// Блокируем курсор в центре экрана и скрываем его (если не открыто меню)
|
||||
GameInputLock.ApplyCursor();
|
||||
}
|
||||
|
||||
public void SetSensitivity(float value)
|
||||
{
|
||||
mouseSensitivity = Mathf.Clamp(value, 20f, 600f);
|
||||
PlayerPrefs.SetFloat("perekup_sensitivity", mouseSensitivity);
|
||||
}
|
||||
|
||||
/// <summary>Поворот взгляда в заданном направлении (после телепорта/выхода из машины).</summary>
|
||||
public void ResetPitch(float pitch = 0f)
|
||||
{
|
||||
xRotation = pitch;
|
||||
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
|
||||
}
|
||||
|
||||
public void ProcessLook(Vector2 input)
|
||||
{
|
||||
float mouseX = input.x * mouseSensitivity * Time.deltaTime;
|
||||
float mouseY = input.y * mouseSensitivity * Time.deltaTime;
|
||||
|
||||
// Расчет наклона камеры с ограничением, чтобы нельзя было сломать шею
|
||||
xRotation -= mouseY;
|
||||
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
|
||||
|
||||
// Применяем вращение камеры (вверх/вниз)
|
||||
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
|
||||
|
||||
// Вращаем само тело игрока (влево/вправо)
|
||||
playerBody.Rotate(Vector3.up * mouseX);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4662192a51344c429f6fb8cb1730a7e2
|
||||
timeCreated: 1789818561
|
||||
@@ -0,0 +1,117 @@
|
||||
using UnityEngine;
|
||||
|
||||
[RequireComponent(typeof(CharacterController))]
|
||||
public class PlayerMovement : MonoBehaviour
|
||||
{
|
||||
[Header("Movement Settings")]
|
||||
[SerializeField] private float moveSpeed = 4f;
|
||||
[SerializeField] private float crouchSpeed = 2f;
|
||||
[SerializeField] private float gravity = -9.81f;
|
||||
|
||||
[Header("Crouch Settings")]
|
||||
[SerializeField] private KeyCode crouchKey = KeyCode.LeftControl;
|
||||
[SerializeField] private float standHeight = 2.0f;
|
||||
[SerializeField] private float crouchHeight = 1.0f;
|
||||
[SerializeField] private float crouchTransitionSpeed = 10f;
|
||||
[SerializeField] private Transform playerCamera; // Ссылка на камеру игрока
|
||||
|
||||
[Header("Ground Check")]
|
||||
[SerializeField] private Transform groundCheck;
|
||||
[SerializeField] private float groundDistance = 0.4f;
|
||||
[SerializeField] private LayerMask groundMask;
|
||||
|
||||
private CharacterController controller;
|
||||
private Vector3 velocity;
|
||||
private bool isGrounded;
|
||||
|
||||
private float initialHeight;
|
||||
private Vector3 standCameraPos;
|
||||
private Vector3 crouchCameraPos;
|
||||
private Vector3 initialCenter;
|
||||
private bool isCrouching;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
controller = GetComponent<CharacterController>();
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
// Запоминаем исходные значения из Инспектора
|
||||
initialHeight = controller.height;
|
||||
initialCenter = controller.center;
|
||||
|
||||
if (playerCamera == null)
|
||||
{
|
||||
Camera cam = GetComponentInChildren<Camera>();
|
||||
if (cam != null) playerCamera = cam.transform;
|
||||
}
|
||||
|
||||
if (playerCamera != null)
|
||||
{
|
||||
standCameraPos = playerCamera.localPosition;
|
||||
// Камера опускается ровно на разницу высоты
|
||||
crouchCameraPos = new Vector3(
|
||||
standCameraPos.x,
|
||||
standCameraPos.y - (standHeight - crouchHeight),
|
||||
standCameraPos.z
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
HandleCrouch();
|
||||
}
|
||||
|
||||
private void HandleCrouch()
|
||||
{
|
||||
if (Input.GetKeyDown(crouchKey))
|
||||
{
|
||||
isCrouching = !isCrouching;
|
||||
}
|
||||
|
||||
float targetHeight = isCrouching ? crouchHeight : standHeight;
|
||||
float currentDelta = initialHeight - targetHeight;
|
||||
|
||||
// ГЛАВНАЯ ФОРМУЛА: дно капсулы остается на земле
|
||||
Vector3 targetCenter = new Vector3(
|
||||
initialCenter.x,
|
||||
initialCenter.y - (currentDelta * 0.5f),
|
||||
initialCenter.z
|
||||
);
|
||||
|
||||
controller.height = Mathf.MoveTowards(controller.height, targetHeight, Time.deltaTime * crouchTransitionSpeed);
|
||||
controller.center = Vector3.MoveTowards(controller.center, targetCenter, Time.deltaTime * crouchTransitionSpeed);
|
||||
|
||||
if (playerCamera != null)
|
||||
{
|
||||
Vector3 targetCamPos = isCrouching ? crouchCameraPos : standCameraPos;
|
||||
playerCamera.localPosition = Vector3.MoveTowards(playerCamera.localPosition, targetCamPos, Time.deltaTime * crouchTransitionSpeed);
|
||||
}
|
||||
}
|
||||
|
||||
public void ProcessMove(Vector2 input)
|
||||
{
|
||||
// Проверка касания земли (сфера на уровне ног)
|
||||
isGrounded = groundCheck != null
|
||||
? Physics.CheckSphere(groundCheck.position, groundDistance, groundMask, QueryTriggerInteraction.Ignore) || controller.isGrounded
|
||||
: controller.isGrounded;
|
||||
|
||||
if (isGrounded && velocity.y < 0)
|
||||
{
|
||||
velocity.y = -2f; // Небольшое прижатие к земле для стабильного спуска по склонам
|
||||
}
|
||||
|
||||
// Выбор текущей скорости в зависимости от состояния приседа
|
||||
float currentSpeed = isCrouching ? crouchSpeed : moveSpeed;
|
||||
|
||||
// Движение относительно локальных координат игрока
|
||||
Vector3 move = transform.right * input.x + transform.forward * input.y;
|
||||
controller.Move(move * (currentSpeed * Time.deltaTime));
|
||||
|
||||
// Применение гравитации
|
||||
velocity.y += gravity * Time.deltaTime;
|
||||
controller.Move(velocity * Time.deltaTime);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bf210e4b179e4c4a93ffda4241a24602
|
||||
timeCreated: 1789818546
|
||||
Reference in new issue
Block a user