using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using KairoEngine.Core; namespace KairoEngine.CharacterSystem { /// /// Action to move a character in a certain direction and speed. /// public class CharacterFollowTargetAction : IAction { CharacterController character; Transform target; float speed = 1f; float animationSpeed = 1f; float targetDistance; bool done = false; // Constructor public CharacterFollowTargetAction(CharacterController character, Transform target, float targetDistance, float speed, float animationSpeed = 1f) { this.character = character; this.target = target; this.targetDistance = targetDistance; this.speed = speed; this.animationSpeed = animationSpeed; } public void Start() { character.navMeshAgent.destination = target.position; character.navMeshAgent.updatePosition = true; character.navMeshAgent.updateRotation = false; character.navMeshAgent.isStopped = false; character.navMeshAgent.speed = speed; } public void Update() { if(Vector3.Distance(character.navMeshAgent.destination, target.position) > targetDistance) { character.navMeshAgent.destination = target.position; } if (character.navMeshAgent == null) return; if (character.navMeshAgent.pathPending) { //Debug.Log("Calculating path"); return; } else { //Debug.Log($"Following path with {character.navMeshAgent.path.corners.Length} corners ({character.unique_name})"); } if (character.navMeshAgent.path == null) { //Debug.Log("No path"); return; } if (character.navMeshAgent.path.corners.Length == 0) { //End(); return; } if (character.navMeshAgent.isStopped) return; //Debug.Log($"Remaining distance: {character.navMeshAgent.remainingDistance} ({character.unique_name})"); if (character.navMeshAgent.remainingDistance < character.navMeshAgent.stoppingDistance) { character.navMeshAgent.isStopped = true; character.navMeshAgent.path.ClearCorners(); //End(); return; } TurnToPoint(character.navMeshAgent.steeringTarget); Vector3 heading = character.navMeshAgent.steeringTarget - character.transform.position; float distance = heading.magnitude; Vector3 direction = heading / distance; character.animator.SetFloat("horizontal", 0); character.animator.SetFloat("vertical", animationSpeed); } private void TurnToPoint(Vector3 point) { Quaternion targetRotation = Quaternion.LookRotation (point - character.transform.position); character.animator.transform.rotation = Quaternion.Slerp (character.animator.transform.rotation, targetRotation, 100f * Time.deltaTime); } public void End() { character.animator.SetFloat("horizontal", 0); character.animator.SetFloat("vertical", 0); character.navMeshAgent.isStopped = true; character.navMeshAgent.speed = 0; done = true; } public bool IsDone() { return done; } } }