112 lines
3.2 KiB
C#
112 lines
3.2 KiB
C#
using SepCore.Definition;
|
|
using UnityEngine;
|
|
|
|
namespace SepCore.Components
|
|
{
|
|
public class PlayerMovementComponent : MonoBehaviour
|
|
{
|
|
private static readonly int WalkStateHash = Animator.StringToHash("Base Layer.Walk");
|
|
|
|
[SerializeField] private Transform _model = null;
|
|
[SerializeField] private Animator _animator = null;
|
|
[SerializeField] private float _turnSpeed = 720f;
|
|
|
|
private Transform _target;
|
|
private StatComponent _statComponent;
|
|
private Vector3 _direction;
|
|
private Quaternion _initialModelRotation = Quaternion.identity;
|
|
private bool _canMove;
|
|
private bool _isWalking;
|
|
|
|
public float Speed => _statComponent.GetStatValue(StatType.MoveSpeed);
|
|
public Vector3 Direction => _direction;
|
|
public bool IsMoving => _isWalking;
|
|
|
|
public void OnInit(float speed, Transform target, StatComponent statComponent)
|
|
{
|
|
_target = target;
|
|
_statComponent = statComponent;
|
|
_statComponent.Pipeline.SetBaseValue(StatType.MoveSpeed, speed);
|
|
_initialModelRotation = _model.localRotation;
|
|
_direction = Vector3.zero;
|
|
_canMove = false;
|
|
_isWalking = false;
|
|
_animator.applyRootMotion = false;
|
|
_animator.Rebind();
|
|
ResetWalkPose();
|
|
}
|
|
|
|
public void SetMove(bool canMove)
|
|
{
|
|
_canMove = canMove;
|
|
if (!canMove)
|
|
{
|
|
_direction = Vector3.zero;
|
|
SetWalking(false);
|
|
}
|
|
}
|
|
|
|
public void SetDirection(Vector3 direction)
|
|
{
|
|
direction.y = 0f;
|
|
_direction = Vector3.ClampMagnitude(direction, 1f);
|
|
}
|
|
|
|
public void OnUpdate(float elapseSeconds, float realElapseSeconds)
|
|
{
|
|
if (!_canMove || elapseSeconds <= 0f)
|
|
{
|
|
return;
|
|
}
|
|
|
|
float speed = Speed;
|
|
bool walking = speed > 0f && _direction.sqrMagnitude > Mathf.Epsilon;
|
|
SetWalking(walking);
|
|
if (!walking)
|
|
{
|
|
return;
|
|
}
|
|
|
|
_target.position += _direction * (speed * elapseSeconds);
|
|
Quaternion rotation = Quaternion.LookRotation(_direction, Vector3.up);
|
|
_model.rotation = Quaternion.RotateTowards(_model.rotation, rotation, _turnSpeed * elapseSeconds);
|
|
}
|
|
|
|
public void OnReset()
|
|
{
|
|
_canMove = false;
|
|
_isWalking = false;
|
|
_direction = Vector3.zero;
|
|
_target = null;
|
|
_statComponent = null;
|
|
_model.localRotation = _initialModelRotation;
|
|
ResetWalkPose();
|
|
}
|
|
|
|
private void SetWalking(bool walking)
|
|
{
|
|
if (_isWalking == walking)
|
|
{
|
|
return;
|
|
}
|
|
|
|
_isWalking = walking;
|
|
if (walking)
|
|
{
|
|
_animator.speed = 1f;
|
|
}
|
|
else
|
|
{
|
|
ResetWalkPose();
|
|
}
|
|
}
|
|
|
|
private void ResetWalkPose()
|
|
{
|
|
_animator.speed = 0f;
|
|
_animator.Play(WalkStateHash, 0, 0f);
|
|
_animator.Update(0f);
|
|
}
|
|
}
|
|
}
|