Files
ClickRPG/Assets/Scripts/CharacterController.cs

79 lines
2.3 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class CharacterController : MonoBehaviour
{
private float moveToUpdateRate = 0.1f;
private float lastMoveToUpdate;
private IInteractable targetInteractable;
private Transform moveTarget;
private NavMeshAgent agent;
private Animator animator;
void Awake ()
{
agent = GetComponent<NavMeshAgent>();
animator = GetComponentInChildren<Animator>();
}
void Update ()
{
if (moveTarget != null && Time.time - lastMoveToUpdate > moveToUpdateRate)
{
animator.ResetTrigger("attack");
lastMoveToUpdate = Time.time;
MoveToPosition(moveTarget.position);
}
if (animator != null)
{
float speed = agent.velocity.magnitude;
float normalisedSpeed = speed / agent.speed;
animator.SetFloat("moveSpeed", normalisedSpeed);
}
if (targetInteractable != null)
{
// Check if we've reached the destination
// agent.remainingDistance is not always reliable, so we also check velocity
if (!agent.pathPending && agent.remainingDistance <= agent.stoppingDistance && agent.velocity.sqrMagnitude == 0f)
{
// We've arrived. Trigger the interaction.
targetInteractable.OnInteract();
// Clear the pending interaction so it doesn't fire again
targetInteractable = null;
}
}
}
public void LookTowards (Vector3 direction)
{
transform.rotation = Quaternion.LookRotation(direction);
}
public void MoveToTarget (Transform target)
{
moveTarget = target;
}
public void MoveToPosition (Vector3 position)
{
agent.SetDestination(position);
agent.isStopped = false;
}
public void MoveToInteractable(Vector3 position, IInteractable interactable)
{
agent.SetDestination(position);
agent.isStopped = false;
// Remember the interactable we want to trigger on arrival
targetInteractable = interactable;
}
public void StopMovement ()
{
agent.isStopped = true;
moveTarget = null;
}
}