Hello, ive been trying to make my npcs walk to waypoints and use the animations ive made. I dont know what im doing wrong but its not working.
heres the script:
using System.Collections;
using UnityEngine;
public class LoganMovement : MonoBehaviour
{
public float moveSpeed = 1f;
public Animator animator;
public Vector2[] waypoints; // Public array to set different waypoints in the Inspector
private int currentWaypointIndex = 0;
private bool isMoving = false;
void Start()
{
if (waypoints.Length > 0)
{
StartCoroutine(MoveAlongPath());
}
else
{
Debug.LogWarning("No waypoints set for Logan.");
}
}
IEnumerator MoveAlongPath()
{
while (true)
{
if (!isMoving && waypoints.Length > 0)
{
Vector2 targetPos = waypoints[currentWaypointIndex];
StartCoroutine(MoveToTarget(targetPos));
currentWaypointIndex = (currentWaypointIndex + 1) % waypoints.Length;
}
yield return null;
}
}
IEnumerator MoveToTarget(Vector2 targetPos)
{
isMoving = true;
while ((Vector2)transform.position != targetPos)
{
Vector2 newPos = Vector2.MoveTowards((Vector2)transform.position, targetPos, moveSpeed * Time.deltaTime);
UpdateAnimation(newPos - (Vector2)transform.position);
transform.position = newPos;
yield return null;
}
UpdateAnimation(Vector2.zero); // Stop animation
isMoving = false;
}
void UpdateAnimation(Vector2 direction)
{
if (direction != Vector2.zero)
{
animator.SetFloat("MoveX", direction.x);
animator.SetFloat("MoveY", direction.y);
}
animator.SetBool("IsMoving", direction != Vector2.zero);
}
