рефакторю управление игроком
This commit is contained in:
1 parent
2746850727
commit
f632508497
18 files changed
+1044
-66
No files matched your search
@@ -151,6 +151,16 @@ public partial class @PlayerControls: IInputActionCollection2, IDisposable
|
||||
""interactions"": """",
|
||||
""initialStateCheck"": false,
|
||||
""priority"": 0
|
||||
},
|
||||
{
|
||||
""name"": ""Attack"",
|
||||
""type"": ""Button"",
|
||||
""id"": ""68813cd9-75a1-4031-b390-a01395eef173"",
|
||||
""expectedControlType"": """",
|
||||
""processors"": """",
|
||||
""interactions"": """",
|
||||
""initialStateCheck"": false,
|
||||
""priority"": 0
|
||||
}
|
||||
],
|
||||
""bindings"": [
|
||||
@@ -263,6 +273,17 @@ public partial class @PlayerControls: IInputActionCollection2, IDisposable
|
||||
""action"": ""EnterMenu"",
|
||||
""isComposite"": false,
|
||||
""isPartOfComposite"": false
|
||||
},
|
||||
{
|
||||
""name"": """",
|
||||
""id"": ""7b7eeb94-7e87-4db8-a3e0-0b75c77293b9"",
|
||||
""path"": ""<Mouse>/leftButton"",
|
||||
""interactions"": """",
|
||||
""processors"": """",
|
||||
""groups"": """",
|
||||
""action"": ""Attack"",
|
||||
""isComposite"": false,
|
||||
""isPartOfComposite"": false
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -277,6 +298,7 @@ public partial class @PlayerControls: IInputActionCollection2, IDisposable
|
||||
m_Player_Crouch = m_Player.FindAction("Crouch", throwIfNotFound: true);
|
||||
m_Player_Look = m_Player.FindAction("Look", throwIfNotFound: true);
|
||||
m_Player_EnterMenu = m_Player.FindAction("EnterMenu", throwIfNotFound: true);
|
||||
m_Player_Attack = m_Player.FindAction("Attack", throwIfNotFound: true);
|
||||
}
|
||||
|
||||
~@PlayerControls()
|
||||
@@ -363,6 +385,7 @@ public partial class @PlayerControls: IInputActionCollection2, IDisposable
|
||||
private readonly InputAction m_Player_Crouch;
|
||||
private readonly InputAction m_Player_Look;
|
||||
private readonly InputAction m_Player_EnterMenu;
|
||||
private readonly InputAction m_Player_Attack;
|
||||
/// <summary>
|
||||
/// Provides access to input actions defined in input action map "Player".
|
||||
/// </summary>
|
||||
@@ -399,6 +422,10 @@ public partial class @PlayerControls: IInputActionCollection2, IDisposable
|
||||
/// </summary>
|
||||
public InputAction @EnterMenu => m_Wrapper.m_Player_EnterMenu;
|
||||
/// <summary>
|
||||
/// Provides access to the underlying input action "Player/Attack".
|
||||
/// </summary>
|
||||
public InputAction @Attack => m_Wrapper.m_Player_Attack;
|
||||
/// <summary>
|
||||
/// Provides access to the underlying input action map instance.
|
||||
/// </summary>
|
||||
public InputActionMap Get() { return m_Wrapper.m_Player; }
|
||||
@@ -442,6 +469,9 @@ public partial class @PlayerControls: IInputActionCollection2, IDisposable
|
||||
@EnterMenu.started += instance.OnEnterMenu;
|
||||
@EnterMenu.performed += instance.OnEnterMenu;
|
||||
@EnterMenu.canceled += instance.OnEnterMenu;
|
||||
@Attack.started += instance.OnAttack;
|
||||
@Attack.performed += instance.OnAttack;
|
||||
@Attack.canceled += instance.OnAttack;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -471,6 +501,9 @@ public partial class @PlayerControls: IInputActionCollection2, IDisposable
|
||||
@EnterMenu.started -= instance.OnEnterMenu;
|
||||
@EnterMenu.performed -= instance.OnEnterMenu;
|
||||
@EnterMenu.canceled -= instance.OnEnterMenu;
|
||||
@Attack.started -= instance.OnAttack;
|
||||
@Attack.performed -= instance.OnAttack;
|
||||
@Attack.canceled -= instance.OnAttack;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -553,5 +586,12 @@ public partial class @PlayerControls: IInputActionCollection2, IDisposable
|
||||
/// <seealso cref="UnityEngine.InputSystem.InputAction.performed" />
|
||||
/// <seealso cref="UnityEngine.InputSystem.InputAction.canceled" />
|
||||
void OnEnterMenu(InputAction.CallbackContext context);
|
||||
/// <summary>
|
||||
/// Method invoked when associated input action "Attack" is either <see cref="UnityEngine.InputSystem.InputAction.started" />, <see cref="UnityEngine.InputSystem.InputAction.performed" /> or <see cref="UnityEngine.InputSystem.InputAction.canceled" />.
|
||||
/// </summary>
|
||||
/// <seealso cref="UnityEngine.InputSystem.InputAction.started" />
|
||||
/// <seealso cref="UnityEngine.InputSystem.InputAction.performed" />
|
||||
/// <seealso cref="UnityEngine.InputSystem.InputAction.canceled" />
|
||||
void OnAttack(InputAction.CallbackContext context);
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,16 @@
|
||||
"interactions": "",
|
||||
"initialStateCheck": false,
|
||||
"priority": 0
|
||||
},
|
||||
{
|
||||
"name": "Attack",
|
||||
"type": "Button",
|
||||
"id": "68813cd9-75a1-4031-b390-a01395eef173",
|
||||
"expectedControlType": "",
|
||||
"processors": "",
|
||||
"interactions": "",
|
||||
"initialStateCheck": false,
|
||||
"priority": 0
|
||||
}
|
||||
],
|
||||
"bindings": [
|
||||
@@ -177,6 +187,17 @@
|
||||
"action": "EnterMenu",
|
||||
"isComposite": false,
|
||||
"isPartOfComposite": false
|
||||
},
|
||||
{
|
||||
"name": "",
|
||||
"id": "7b7eeb94-7e87-4db8-a3e0-0b75c77293b9",
|
||||
"path": "<Mouse>/leftButton",
|
||||
"interactions": "",
|
||||
"processors": "",
|
||||
"groups": "",
|
||||
"action": "Attack",
|
||||
"isComposite": false,
|
||||
"isPartOfComposite": false
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -23,15 +23,7 @@ namespace _Project.Scripts
|
||||
}
|
||||
void Update()
|
||||
{
|
||||
if (isStarted && !isWorking && isLooped)
|
||||
{
|
||||
while (isLooped)
|
||||
{
|
||||
isStarted = false;
|
||||
isWorking = true;
|
||||
coroutine = StartCoroutine(ColorCoroutine());
|
||||
}
|
||||
}
|
||||
|
||||
if (isStarted && !isWorking)
|
||||
{
|
||||
isStarted = false;
|
||||
@@ -44,23 +36,30 @@ namespace _Project.Scripts
|
||||
|
||||
IEnumerator ColorCoroutine()
|
||||
{
|
||||
float elapsedTime = 0f;
|
||||
|
||||
while (elapsedTime < TimeForChange)
|
||||
do
|
||||
{
|
||||
image.color = Color.Lerp(prevColor, Color.clear, elapsedTime / TimeForChange);
|
||||
elapsedTime += Time.deltaTime;
|
||||
yield return null;
|
||||
}
|
||||
elapsedTime = 0f;
|
||||
while (elapsedTime < TimeForChange)
|
||||
{
|
||||
elapsedTime += Time.deltaTime;
|
||||
image.color = Color.Lerp( Color.clear,prevColor, elapsedTime / TimeForChange);
|
||||
yield return null;
|
||||
}
|
||||
coroutine = null;
|
||||
isWorking = false;
|
||||
float elapsedTime = 0f;
|
||||
|
||||
while (elapsedTime < TimeForChange)
|
||||
{
|
||||
image.color = Color.Lerp(prevColor, Color.clear, elapsedTime / TimeForChange);
|
||||
elapsedTime += Time.deltaTime;
|
||||
yield return null;
|
||||
}
|
||||
|
||||
elapsedTime = 0f;
|
||||
while (elapsedTime < TimeForChange)
|
||||
{
|
||||
elapsedTime += Time.deltaTime;
|
||||
image.color = Color.Lerp(Color.clear, prevColor, elapsedTime / TimeForChange);
|
||||
yield return null;
|
||||
}
|
||||
|
||||
coroutine = null;
|
||||
isWorking = false;
|
||||
|
||||
} while (isLooped);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class TargetDummy : MonoBehaviour, IDamageable
|
||||
{
|
||||
[SerializeField] private float health = 100f;
|
||||
|
||||
public void TakeDamage(float amount)
|
||||
{
|
||||
health -= amount;
|
||||
Debug.Log($"Враг получил {amount} урона. Осталось HP: {health}");
|
||||
|
||||
if (health <= 0)
|
||||
{
|
||||
Destroy(gameObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 2d7a447e6bc04aec8bf4805369d10a05
|
||||
timeCreated: 1790086695
|
||||
@@ -0,0 +1,24 @@
|
||||
using _Project.Scripts.PlayerUtils;
|
||||
using _Project.Scripts.Utilities;
|
||||
|
||||
namespace _Project.Scripts
|
||||
{
|
||||
public class Player : MonoSingleton<Player>
|
||||
{
|
||||
private PlayerMovement movement;
|
||||
public PlayerControls controls { get; set; }
|
||||
|
||||
void Awake()
|
||||
{
|
||||
base.Awake();
|
||||
|
||||
movement = GetComponent<PlayerMovement>();
|
||||
controls = GetComponent<PlayerControls>();
|
||||
}
|
||||
|
||||
void Update()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 75b0375d82064442a50d4b6cf42048bb
|
||||
timeCreated: 1790082561
|
||||
@@ -10,32 +10,36 @@ public class PlayerController : MonoBehaviour
|
||||
[SerializeField] private float mouseSensitivity = 0.1f;
|
||||
[SerializeField] private float maxLookAngle = 80f;
|
||||
|
||||
[Header("Оружие и Стрельба (Hitscan)")]
|
||||
[SerializeField] private float damage = 25f;
|
||||
[Tooltip("Задержка между выстрелами в секундах (0.1 = 600 выстр/мин)")]
|
||||
[SerializeField] private float fireRate = 0.12f;
|
||||
[SerializeField] private float weaponRange = 100f;
|
||||
[SerializeField] private LayerMask hitLayers = ~0; // По кому попадаем (по умолчанию всё)
|
||||
[SerializeField] private bool isAutomatic = true;
|
||||
[Tooltip("Сила вертикального пинка камеры при выстреле")]
|
||||
[SerializeField] private float recoilKick = 1.2f;
|
||||
[SerializeField] private ParticleSystem muzzleFlash;
|
||||
[SerializeField] private GameObject impactPrefab; // Префаб искр / дырки от пули
|
||||
[SerializeField] private AudioClip shootSound;
|
||||
|
||||
[Header("Скорости передвижения (м/с)")]
|
||||
[SerializeField] private float moveSpeed = 6.5f; // Обычный бег (~250 u/s)
|
||||
[SerializeField] private float sprintSpeed = 9.5f; // Спринт (~360 u/s)
|
||||
[SerializeField] private float moveSpeed = 6.5f;
|
||||
[SerializeField] private float sprintSpeed = 9.5f;
|
||||
[SerializeField] private float crouchSpeed = 3f;
|
||||
|
||||
[Header("Параметры Подката (Slide)")]
|
||||
[Tooltip("Начальная взрывная скорость подката")]
|
||||
[SerializeField] private float slideInitialSpeed = 15f; // (~580 u/s)
|
||||
[Tooltip("Длительность скольжения в секундах")]
|
||||
[SerializeField] private float slideInitialSpeed = 15f;
|
||||
[SerializeField] private float slideDuration = 0.85f;
|
||||
[Tooltip("Трение коленей при подкате")]
|
||||
[SerializeField] private float slideFriction = 2.8f;
|
||||
[Tooltip("Наклон камеры набок при подкате (градусы)")]
|
||||
[SerializeField] private float slideCameraTiltAngle = 4f;
|
||||
[SerializeField] private float slideCooldown = 0.35f;
|
||||
|
||||
[Header("Физика CS / Source (Bunnyhop & Strafe)")]
|
||||
[Tooltip("Трение на земле (гасит скорость, если не успели прыгнуть вовремя)")]
|
||||
[SerializeField] private float groundFriction = 5f;
|
||||
[Tooltip("Ускорение на земле")]
|
||||
[SerializeField] private float groundAcceleration = 10f;
|
||||
[Tooltip("Сила набора скорости в воздухе при стрейфах (sv_airaccelerate)")]
|
||||
[SerializeField] private float airAcceleration = 80f;
|
||||
[Tooltip("Лимит добавления скорости в воздухе")]
|
||||
[SerializeField] private float airCap = 2.0f;
|
||||
[Tooltip("Показывать спидометр на экране")]
|
||||
[SerializeField] private bool showSpeedometer = true;
|
||||
|
||||
[Header("Гравитация и Прыжок")]
|
||||
@@ -44,7 +48,6 @@ public class PlayerController : MonoBehaviour
|
||||
[SerializeField] private float fallMultiplier = 1.8f;
|
||||
[SerializeField] private LayerMask groundLayer;
|
||||
[SerializeField] private float groundCheckDistance = 0.12f;
|
||||
[Tooltip("Буфер прыжка (время поблажки для колесика мыши)")]
|
||||
[SerializeField] private float jumpBufferTime = 0.12f;
|
||||
|
||||
[Header("Параметры приседания")]
|
||||
@@ -79,6 +82,10 @@ public class PlayerController : MonoBehaviour
|
||||
private Vector3 horizontalVelocity = Vector3.zero;
|
||||
private float verticalVelocity = 0f;
|
||||
|
||||
// Стрельба
|
||||
private float shootTimer = 0f;
|
||||
private bool isShootingInput = false;
|
||||
|
||||
// Камера
|
||||
private float cameraPitch = 0f;
|
||||
private float yRotation = 0f;
|
||||
@@ -139,8 +146,12 @@ public class PlayerController : MonoBehaviour
|
||||
controls.Player.Crouch.started += ctx => OnCrouchPressed();
|
||||
controls.Player.Crouch.canceled += ctx => OnCrouchReleased();
|
||||
|
||||
// Прыжок на Пробел (через буфер)
|
||||
// Прыжок на Пробел
|
||||
controls.Player.Jump.performed += ctx => QueueJump();
|
||||
|
||||
// Стрельба (ЛКМ) через Input Actions
|
||||
controls.Player.Attack.started += ctx => isShootingInput = true;
|
||||
controls.Player.Attack.canceled += ctx => isShootingInput = false;
|
||||
}
|
||||
|
||||
private void OnEnable() => controls.Player.Enable();
|
||||
@@ -150,25 +161,24 @@ public class PlayerController : MonoBehaviour
|
||||
{
|
||||
moveInput = controls.Player.Move.ReadValue<Vector2>();
|
||||
lookInput = controls.Player.Look.ReadValue<Vector2>();
|
||||
|
||||
|
||||
// Таймер буфера прыжка
|
||||
|
||||
if (jumpBufferTimer > 0f)
|
||||
jumpBufferTimer -= Time.deltaTime;
|
||||
|
||||
if (slideCooldownTimer > 0f)
|
||||
slideCooldownTimer -= Time.deltaTime;
|
||||
|
||||
// ПРЫЖОК НА КОЛЁСИКО МЫШИ (вниз и вверх)
|
||||
// Прыжок на колесико мыши
|
||||
if (Mouse.current != null)
|
||||
{
|
||||
float scrollY = Mouse.current.scroll.y.ReadValue();
|
||||
if (Mathf.Abs(scrollY) > 0.1f) // Крутанули вниз или вверх
|
||||
if (Mathf.Abs(scrollY) > 0.1f)
|
||||
{
|
||||
QueueJump();
|
||||
}
|
||||
}
|
||||
|
||||
HandleShooting();
|
||||
HandleMouseLook();
|
||||
HandleCameraAndBobbing();
|
||||
}
|
||||
@@ -178,21 +188,74 @@ public class PlayerController : MonoBehaviour
|
||||
CheckGrounded();
|
||||
CalculateCustomGravity();
|
||||
|
||||
// Проверяем прыжок/бхоп (если зажат пробел или крутанули колесо)
|
||||
if (jumpBufferTimer > 0f && isGrounded)
|
||||
{
|
||||
ExecuteJump();
|
||||
}
|
||||
|
||||
// Движение (земля, воздух, подкат)
|
||||
ApplyMovement();
|
||||
|
||||
// Применяем скорость в Rigidbody
|
||||
rb.linearVelocity = new Vector3(horizontalVelocity.x, verticalVelocity, horizontalVelocity.z);
|
||||
|
||||
wasGrounded = isGrounded;
|
||||
}
|
||||
|
||||
#region Механика Стрельбы (Weapons)
|
||||
|
||||
private void HandleShooting()
|
||||
{
|
||||
if (shootTimer > 0f)
|
||||
shootTimer -= Time.deltaTime;
|
||||
|
||||
// Проверяем ввод: либо через Input Action, либо напрямую через Mouse (для надежности)
|
||||
bool shootPressed = isShootingInput || (Mouse.current != null && (isAutomatic ? Mouse.current.leftButton.isPressed : Mouse.current.leftButton.wasPressedThisFrame));
|
||||
|
||||
if (shootPressed && shootTimer <= 0f)
|
||||
{
|
||||
Shoot();
|
||||
}
|
||||
}
|
||||
|
||||
private void Shoot()
|
||||
{
|
||||
shootTimer = fireRate;
|
||||
|
||||
// 1. Звук выстрела
|
||||
if (shootSound != null)
|
||||
audioSource.PlayOneShot(shootSound, 0.8f);
|
||||
|
||||
// 2. Вспышка из ствола
|
||||
if (muzzleFlash != null)
|
||||
muzzleFlash.Play();
|
||||
|
||||
// 3. Отдача (вздергивание прицела вверх)
|
||||
cameraPitch -= recoilKick;
|
||||
|
||||
// 4. Рейкаст строго из центра камеры
|
||||
Ray ray = new Ray(cameraPosition.position, cameraPosition.forward);
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, weaponRange, hitLayers, QueryTriggerInteraction.Ignore))
|
||||
{
|
||||
// Нанесение урона врагу
|
||||
if (hit.collider.TryGetComponent<IDamageable>(out var damageable))
|
||||
{
|
||||
damageable.TakeDamage(damage);
|
||||
}
|
||||
// Если попали в физ. объект — отталкиваем его импульсом пули
|
||||
else if (hit.rigidbody != null)
|
||||
{
|
||||
hit.rigidbody.AddForceAtPosition(-hit.normal * (damage * 10f), hit.point, ForceMode.Impulse);
|
||||
}
|
||||
|
||||
// Спавн декали / эффекта удара пули
|
||||
if (impactPrefab != null)
|
||||
{
|
||||
GameObject impact = Instantiate(impactPrefab, hit.point + (hit.normal * 0.001f), Quaternion.LookRotation(hit.normal));
|
||||
Destroy(impact, 3f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private void QueueJump()
|
||||
{
|
||||
jumpBufferTimer = jumpBufferTime;
|
||||
@@ -202,7 +265,6 @@ public class PlayerController : MonoBehaviour
|
||||
|
||||
private void OnCrouchPressed()
|
||||
{
|
||||
// Подкат: если бежим вперед, на земле и кулдаун прошел
|
||||
if (isSprinting && isGrounded && moveInput.y > 0.2f && slideCooldownTimer <= 0f)
|
||||
{
|
||||
StartSlide();
|
||||
@@ -228,7 +290,6 @@ public class PlayerController : MonoBehaviour
|
||||
slideTimer = slideDuration;
|
||||
slideCurrentSpeed = slideInitialSpeed;
|
||||
|
||||
// Направление подката берется от взгляда и нажатых клавиш
|
||||
slideDirection = (transform.forward * moveInput.y + transform.right * moveInput.x).normalized;
|
||||
if (slideDirection.sqrMagnitude < 0.01f) slideDirection = transform.forward;
|
||||
|
||||
@@ -248,13 +309,11 @@ public class PlayerController : MonoBehaviour
|
||||
|
||||
private void ApplyMovement()
|
||||
{
|
||||
// 1. ПОДКАT
|
||||
if (isSliding)
|
||||
{
|
||||
slideCurrentSpeed = Mathf.Lerp(slideCurrentSpeed, crouchSpeed, Time.fixedDeltaTime * slideFriction);
|
||||
slideTimer -= Time.fixedDeltaTime;
|
||||
|
||||
// Небольшое подруливание в подкате
|
||||
Vector3 steerDir = (transform.forward * moveInput.y + transform.right * moveInput.x).normalized;
|
||||
if (steerDir.sqrMagnitude > 0.01f)
|
||||
slideDirection = Vector3.Slerp(slideDirection, steerDir, Time.fixedDeltaTime * 2.5f);
|
||||
@@ -269,17 +328,14 @@ public class PlayerController : MonoBehaviour
|
||||
return;
|
||||
}
|
||||
|
||||
// Вектор желаемого направления (WishDir)
|
||||
Vector3 wishDir = (transform.forward * moveInput.y + transform.right * moveInput.x);
|
||||
wishDir.y = 0f;
|
||||
wishDir.Normalize();
|
||||
|
||||
float targetSpeed = isCrouching ? crouchSpeed : (isSprinting ? sprintSpeed : moveSpeed);
|
||||
|
||||
// 2. НА ЗЕМЛЕ
|
||||
if (isGrounded)
|
||||
{
|
||||
// Если игрок делает баннихоп прямо сейчас — НЕ применяем трение пола!
|
||||
if (jumpBufferTimer <= 0f)
|
||||
{
|
||||
ApplyGroundFriction();
|
||||
@@ -287,7 +343,6 @@ public class PlayerController : MonoBehaviour
|
||||
|
||||
Accelerate(wishDir, targetSpeed, groundAcceleration);
|
||||
}
|
||||
// 3. В ВОЗДУХЕ (Формула CS AirAccelerate)
|
||||
else
|
||||
{
|
||||
AirAccelerate(wishDir, targetSpeed, airAcceleration, airCap);
|
||||
@@ -332,13 +387,11 @@ public class PlayerController : MonoBehaviour
|
||||
float accelSpeed = accel * wishSpeed * Time.fixedDeltaTime;
|
||||
accelSpeed = Mathf.Min(accelSpeed, addSpeed);
|
||||
|
||||
// Добавляем поперечный вектор скорости для стрейфа
|
||||
horizontalVelocity += wishDir * accelSpeed;
|
||||
}
|
||||
|
||||
private void ExecuteJump()
|
||||
{
|
||||
// SLIDE-JUMP: Если прыгаем из подката — сохраняем скорость в воздух!
|
||||
if (isSliding)
|
||||
{
|
||||
horizontalVelocity = slideDirection * slideCurrentSpeed;
|
||||
@@ -346,7 +399,7 @@ public class PlayerController : MonoBehaviour
|
||||
}
|
||||
|
||||
verticalVelocity = Mathf.Sqrt(jumpHeight * -2f * gravity);
|
||||
jumpBufferTimer = 0f; // Сбрасываем запрос на прыжок
|
||||
jumpBufferTimer = 0f;
|
||||
|
||||
if (enableHeadBob)
|
||||
currentImpactOffset = 0.1f;
|
||||
@@ -396,17 +449,14 @@ public class PlayerController : MonoBehaviour
|
||||
|
||||
private void HandleMouseLook()
|
||||
{
|
||||
// Вверх / Вниз
|
||||
cameraPitch -= lookInput.y * mouseSensitivity;
|
||||
cameraPitch = Mathf.Clamp(cameraPitch, -maxLookAngle, maxLookAngle);
|
||||
|
||||
// Наклон камеры в подкате (Camera Roll)
|
||||
float targetTilt = isSliding ? -slideCameraTiltAngle : 0f;
|
||||
currentCameraTilt = Mathf.Lerp(currentCameraTilt, targetTilt, Time.deltaTime * 10f);
|
||||
|
||||
cameraPosition.localRotation = Quaternion.Euler(cameraPitch, 0f, currentCameraTilt);
|
||||
|
||||
// Влево / Вправо
|
||||
yRotation += lookInput.x * mouseSensitivity;
|
||||
transform.rotation = Quaternion.Euler(0f, yRotation, 0f);
|
||||
}
|
||||
@@ -421,7 +471,6 @@ public class PlayerController : MonoBehaviour
|
||||
col.center = new Vector3(col.center.x, col.height * 0.5f, col.center.z);
|
||||
baseCameraY = Mathf.Lerp(baseCameraY, targetCamY, Time.deltaTime * crouchTransitionSpeed);
|
||||
|
||||
// В подкате и в воздухе шаги не трясут камеру
|
||||
bool isMoving = moveInput.sqrMagnitude > 0.01f && isGrounded && !isSliding;
|
||||
|
||||
if (isMoving && enableHeadBob)
|
||||
@@ -458,10 +507,12 @@ public class PlayerController : MonoBehaviour
|
||||
0f
|
||||
);
|
||||
}
|
||||
|
||||
public void SetSensitivity(float newSens)
|
||||
{
|
||||
mouseSensitivity = newSens;
|
||||
}
|
||||
|
||||
private void PlayFootstep()
|
||||
{
|
||||
if (footstepSounds == null || footstepSounds.Length == 0) return;
|
||||
@@ -487,4 +538,10 @@ public class PlayerController : MonoBehaviour
|
||||
string state = isSliding ? " [SLIDE]" : (!isGrounded ? " [AIR]" : "");
|
||||
GUI.Label(new Rect(30, 30, 500, 50), $"Speed: {speed:F1} m/s ({csUnits:F0} u/s){state}", style);
|
||||
}
|
||||
}
|
||||
|
||||
// Интерфейс для любых целей/врагов, принимающих урон
|
||||
public interface IDamageable
|
||||
{
|
||||
void TakeDamage(float amount);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: f89495a02fc2473181e7aa5998a71e2b
|
||||
timeCreated: 1790083064
|
||||
@@ -0,0 +1,107 @@
|
||||
using _Project.Scripts.Utilities;
|
||||
using UnityEngine;
|
||||
|
||||
namespace _Project.Scripts.PlayerUtils
|
||||
{
|
||||
public class PlayerMovement : MonoSingleton<PlayerMovement>
|
||||
{
|
||||
[Header("Камера и Мышь")]
|
||||
[SerializeField] private Transform cameraPosition;
|
||||
[SerializeField] private float mouseSensitivity = 0.1f;
|
||||
[SerializeField] private float maxLookAngle = 80f;
|
||||
|
||||
[Header("Скорости передвижения (м/с)")]
|
||||
[SerializeField] private float moveSpeed = 6.5f; // Обычный бег (~250 u/s)
|
||||
[SerializeField] private float sprintSpeed = 9.5f; // Спринт (~360 u/s)
|
||||
[SerializeField] private float crouchSpeed = 3f;
|
||||
|
||||
[Header("Параметры Подката (Slide)")]
|
||||
[Tooltip("Начальная взрывная скорость подката")]
|
||||
[SerializeField] private float slideInitialSpeed = 15f; // (~580 u/s)
|
||||
[Tooltip("Длительность скольжения в секундах")]
|
||||
[SerializeField] private float slideDuration = 0.85f;
|
||||
[Tooltip("Трение коленей при подкате")]
|
||||
[SerializeField] private float slideFriction = 2.8f;
|
||||
[Tooltip("Наклон камеры набок при подкате (градусы)")]
|
||||
[SerializeField] private float slideCameraTiltAngle = 4f;
|
||||
[SerializeField] private float slideCooldown = 0.35f;
|
||||
|
||||
[Header("Физика CS / Source (Bunnyhop & Strafe)")]
|
||||
[Tooltip("Трение на земле (гасит скорость, если не успели прыгнуть вовремя)")]
|
||||
[SerializeField] private float groundFriction = 5f;
|
||||
[Tooltip("Ускорение на земле")]
|
||||
[SerializeField] private float groundAcceleration = 10f;
|
||||
[Tooltip("Сила набора скорости в воздухе при стрейфах (sv_airaccelerate)")]
|
||||
[SerializeField] private float airAcceleration = 80f;
|
||||
[Tooltip("Лимит добавления скорости в воздухе")]
|
||||
[SerializeField] private float airCap = 2.0f;
|
||||
[Tooltip("Показывать спидометр на экране")]
|
||||
[SerializeField] private bool showSpeedometer = true;
|
||||
|
||||
[Header("Гравитация и Прыжок")]
|
||||
[SerializeField] private float jumpHeight = 1.35f;
|
||||
[SerializeField] private float gravity = -25f;
|
||||
[SerializeField] private float fallMultiplier = 1.8f;
|
||||
[SerializeField] private LayerMask groundLayer;
|
||||
[SerializeField] private float groundCheckDistance = 0.12f;
|
||||
[Tooltip("Буфер прыжка (время поблажки для колесика мыши)")]
|
||||
[SerializeField] private float jumpBufferTime = 0.12f;
|
||||
|
||||
[Header("Параметры приседания")]
|
||||
[SerializeField] private float standingHeight = 2f;
|
||||
[SerializeField] private float crouchingHeight = 1.05f;
|
||||
[SerializeField] private float standingCameraY = 1.6f;
|
||||
[SerializeField] private float crouchingCameraY = 0.8f;
|
||||
[SerializeField] private float crouchTransitionSpeed = 15f;
|
||||
|
||||
private Rigidbody rb;
|
||||
private CapsuleCollider col;
|
||||
|
||||
private Vector2 moveInput;
|
||||
private Vector2 lookInput;
|
||||
private Vector3 horizontalVelocity = Vector3.zero;
|
||||
private float verticalVelocity = 0f;
|
||||
|
||||
private bool isGrounded;
|
||||
private bool wasGrounded;
|
||||
private bool isSprinting = false;
|
||||
private bool isCrouching = false;
|
||||
private float jumpBufferTimer = 0f;
|
||||
|
||||
// Подкат
|
||||
private bool isSliding = false;
|
||||
private float slideTimer = 0f;
|
||||
private float slideCurrentSpeed = 0f;
|
||||
private Vector3 slideDirection = Vector3.zero;
|
||||
private float slideCooldownTimer = 0f;
|
||||
|
||||
private PlayerControls controls;
|
||||
|
||||
void Awake()
|
||||
{
|
||||
base.Awake();
|
||||
|
||||
rb = GetComponent<Rigidbody>();
|
||||
col = GetComponent<CapsuleCollider>();
|
||||
mouseSensitivity = PlayerPrefs.GetFloat("MouseSensitivity", mouseSensitivity);
|
||||
rb.useGravity = false;
|
||||
rb.freezeRotation = true;
|
||||
rb.interpolation = RigidbodyInterpolation.None;
|
||||
|
||||
controls = new PlayerControls();
|
||||
|
||||
controls = Player.Instance.controls;
|
||||
// Спринт
|
||||
controls.Player.Sprint.started += ctx => isSprinting = true;
|
||||
controls.Player.Sprint.canceled += ctx => isSprinting = false;
|
||||
|
||||
/* // Присед и Подкат
|
||||
controls.Player.Crouch.started += ctx => OnCrouchPressed();
|
||||
controls.Player.Crouch.canceled += ctx => OnCrouchReleased();
|
||||
|
||||
// Прыжок на Пробел (через буфер)
|
||||
controls.Player.Jump.performed += ctx => QueueJump();
|
||||
*/
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 51301269a09843b8af775b231056fa86
|
||||
timeCreated: 1790082597
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4cf71ad00ebc47e7849387c806fe9f46
|
||||
timeCreated: 1790083090
|
||||
@@ -0,0 +1,20 @@
|
||||
using UnityEngine;
|
||||
|
||||
namespace _Project.Scripts.Utilities
|
||||
{
|
||||
public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
|
||||
{
|
||||
public static T Instance { get; private set; }
|
||||
|
||||
protected virtual void Awake()
|
||||
{
|
||||
if (Instance != null&& Instance != this)
|
||||
{
|
||||
Destroy(gameObject);
|
||||
return;
|
||||
}
|
||||
Instance = this as T;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: e974b3a40b5b4d09b675d2139ac7407b
|
||||
timeCreated: 1790083100
|
||||
Reference in new issue
Block a user