You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
115 lines
2.8 KiB
115 lines
2.8 KiB
using System;
|
|
using UnityEngine;
|
|
using UnityEngine.AI;
|
|
|
|
public class PlayerMovement : MonoBehaviour
|
|
{
|
|
[Header("Components")]
|
|
[SerializeField] private Player player;
|
|
[SerializeField] private NavMeshAgent agent;
|
|
|
|
private Vector3 target;
|
|
|
|
private float lookRotationSpeed = 8f;
|
|
private bool isMoving = false;
|
|
private bool onInteraction = false;
|
|
|
|
private bool prepareEvent = false;
|
|
private Action onDestinationReached;
|
|
|
|
private Animator animator => player.Animator;
|
|
|
|
public void MoveTo(Vector3 point, Action action = null)
|
|
{
|
|
if (agent == null) return;
|
|
|
|
target = point;
|
|
agent.destination = point;
|
|
onDestinationReached = action;
|
|
}
|
|
|
|
public void MoveToBlock(Vector3 point, Action action = null)
|
|
{
|
|
InteractionManager.Instance.AddBlockReason("Moving", false);
|
|
MoveTo(point, () =>
|
|
{
|
|
action?.Invoke();
|
|
InteractionManager.Instance.RemoveBlockReason("Moving");
|
|
});
|
|
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
if (onInteraction) return;
|
|
|
|
isMoving = !agent.pathPending && agent.remainingDistance > agent.stoppingDistance;
|
|
|
|
if (isMoving)
|
|
{
|
|
prepareEvent = true;
|
|
FaceTarget();
|
|
}
|
|
|
|
SetAnimations();
|
|
|
|
if (prepareEvent && Vector3.Distance(transform.position, target) <= 1.5f)
|
|
{
|
|
prepareEvent = false;
|
|
onDestinationReached?.Invoke();
|
|
}
|
|
|
|
}
|
|
|
|
private void FaceTarget()
|
|
{
|
|
if (agent.velocity == Vector3.zero) return;
|
|
|
|
Vector3 direction = (agent.destination - transform.position).normalized;
|
|
Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
|
|
transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * lookRotationSpeed);
|
|
}
|
|
|
|
public void StopMovement()
|
|
{
|
|
agent.destination = transform.position;
|
|
isMoving = false;
|
|
animator.SetBool("Walking", false);
|
|
}
|
|
|
|
private void SetAnimations()
|
|
{
|
|
if (!animator) return;
|
|
|
|
animator.SetBool("Walking", agent.velocity != Vector3.zero);
|
|
}
|
|
|
|
private void ActivateAgent(bool activate)
|
|
{
|
|
agent.enabled = activate;
|
|
onInteraction = !activate;
|
|
}
|
|
|
|
public void CancelInteraction()
|
|
{
|
|
onDestinationReached = null;
|
|
}
|
|
|
|
|
|
|
|
public void ActivateAgent() => ActivateAgent(true);
|
|
public void DeactivateAgent() => ActivateAgent(false);
|
|
|
|
public void OnInteraction(Vector3 position, Vector3 rotation)
|
|
{
|
|
onInteraction = true;
|
|
agent.Warp(position);
|
|
transform.rotation = Quaternion.Euler(rotation);
|
|
}
|
|
|
|
public void OutInteraction(Vector3 position)
|
|
{
|
|
agent.Warp(position);
|
|
onInteraction = false;
|
|
}
|
|
}
|