- Home /
AI movement script doesn't appear to be working
I'm following this tutorial (https://noobtuts.com/unity/2d-pacman-game) and I seem to be doing something wrong. Near the bottom of the tutorial, there is a script that tells the ghosts to move, however when I implement it in my game the ghost will only go to the first waypoint I created and not the others. All of the waypoints are properly associated with the script after it has been placed on the ghost. Can anybody think of anything else I could be doing wrong, or something I've missed? I've copied the code exactly like this:
using UnityEngine; using System.Collections;
public class GhostMove : MonoBehaviour { public Transform[] waypoints; int cur = 0;
public float speed = 0.3f;
void FixedUpdate()
{
// Waypoint not reached yet? then move closer
if (transform.position != waypoints[cur].position)
{
Vector2 p = Vector2.MoveTowards(transform.position,
waypoints[cur].position,
speed);
GetComponent<Rigidbody2D>().MovePosition(p);
}
// Waypoint reached, select next one
else cur = (cur + 1) % waypoints.Length;
// Animation
Vector2 dir = waypoints[cur].position - transform.position;
GetComponent<Animator>().SetFloat("DirX", dir.x);
GetComponent<Animator>().SetFloat("DirY", dir.y);
}
void OnTriggerEnter2D(Collider2D co)
{
if (co.name == "pacman")
Destroy(co.gameObject);
}
}
Answer by Lady_Saturday · Mar 27, 2018 at 06:05 PM
I changed the script to this, to include a slight error margin in the distance from the points, and it works now.
// Waypoint not reached yet? then move closer if (Vector2.Distance(transform.position, waypoints[cur].position) < 0.1f) { if (cur == waypoints.Length) { cur = 0; } else { cur++; } } // Waypoint reached, select next one else { Vector2 p = Vector2.MoveTowards(transform.position, waypoints[cur].position, speed); GetComponent().MovePosition(p);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612154927im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
FPS Waypoints not working right 1 Answer
How to make the sprite move a certain amount of pixels when a key is pressed? 1 Answer
Maze Game Pathfinding AI 0 Answers
Saving Vector2 coordinates as waypoints to dynamic array 1 Answer
Make player follow a waypoint path but still be able to control player movement 1 Answer