90 lines
2.6 KiB
C#
90 lines
2.6 KiB
C#
using UnityEngine;
|
|
using Code.Input;
|
|
|
|
namespace Code.Gameplay.Player
|
|
{
|
|
public class PlayerMovement : MonoBehaviour
|
|
{
|
|
[Header("References")]
|
|
[SerializeField] private Rigidbody2D _rb;
|
|
[SerializeField] private Transform _groundCheck;
|
|
[SerializeField] private LayerMask _groundLayer;
|
|
|
|
[Header("Movement")]
|
|
[SerializeField] private float _moveSpeed = 5f;
|
|
[SerializeField] private float _sprintSpeedMultiplier = 1.8f;
|
|
[SerializeField] private float _jumpForce = 12f;
|
|
|
|
[Header("Ground Check")]
|
|
[SerializeField] private float _groundCheckRadius = 0.2f;
|
|
|
|
private IInputService _input;
|
|
private bool _isGrounded;
|
|
private bool _jumpRequested;
|
|
|
|
public bool IsGrounded => _isGrounded;
|
|
|
|
public void Construct(IInputService input)
|
|
{
|
|
_input = input;
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
HandleInput();
|
|
CheckGround();
|
|
}
|
|
|
|
private void FixedUpdate()
|
|
{
|
|
Move();
|
|
HandleJump();
|
|
}
|
|
|
|
private void HandleInput()
|
|
{
|
|
transform.rotation = _input.MoveInput switch
|
|
{
|
|
> 0 => Quaternion.identity,
|
|
< 0 => Quaternion.Euler(0, -180, 0),
|
|
_ => transform.rotation
|
|
};
|
|
|
|
if (_input.JumpPressed && !_jumpRequested)
|
|
{
|
|
_jumpRequested = true;
|
|
}
|
|
}
|
|
|
|
private void CheckGround()
|
|
{
|
|
_isGrounded = Physics2D.OverlapCircle(_groundCheck.position, _groundCheckRadius, _groundLayer);
|
|
}
|
|
|
|
private void Move()
|
|
{
|
|
float moveInput = _input.MoveInput;
|
|
float speed = _input.SprintHeld ? _moveSpeed * _sprintSpeedMultiplier : _moveSpeed;
|
|
float targetVelocityX = moveInput * speed;
|
|
|
|
// Плавное изменение скорости (опционально, можно и напрямую)
|
|
_rb.linearVelocity = new Vector2(targetVelocityX, _rb.linearVelocity.y);
|
|
}
|
|
|
|
private void HandleJump()
|
|
{
|
|
if (_jumpRequested && _isGrounded)
|
|
{
|
|
_rb.linearVelocity = new Vector2(_rb.linearVelocity.x, _jumpForce);
|
|
_jumpRequested = false;
|
|
}
|
|
}
|
|
|
|
// Для отладки
|
|
private void OnDrawGizmosSelected()
|
|
{
|
|
if (_groundCheck != null)
|
|
Gizmos.DrawWireSphere(_groundCheck.position, _groundCheckRadius);
|
|
}
|
|
}
|
|
} |