- Home /
The question is answered, right answer was accepted
Enemy stopped at first waypoints.
I wanna make enemy loop back to the first waypoints after it finished its patrol path. But somehow it stopped at the first waypoint. Basically didn't even complete the first cycle. This is my code:
public class RedAlienMovement : MonoBehaviour
{
private Waypoints wPoints;
private int wPointsIndex;
[SerializeField] private float speed;
void Start()
{
wPoints = GameObject.FindGameObjectWithTag("Waypoints").GetComponent<Waypoints>();
}
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, wPoints.waypoints[0].position, speed * Time.deltaTime);
if (Vector2.Distance(transform.position, wPoints.waypoints[wPointsIndex].position) < 0.1f)
{
if (wPointsIndex < wPoints.waypoints.Length - 1)
{
wPointsIndex++;
}
else
{
wPointsIndex = 0;
}
}
}
Answer by tormentoarmagedoom · Feb 09, 2020 at 02:44 PM
Hello.
Some things:
FIrst, Maybe you should use NAVMESH system to move the enemies, it will help you with route calculation, speed, avoid obstacles, etc... And simplificate assign new target.
Second, Your problem is here:
transform.position = Vector2.MoveTowards(transform.position, wPoints.waypoints[0].position, speed * Time.deltaTime);
wPoints.waypoints[0] should be wPoints.waypoints[wPointsIndex]
Thats the original problem.
Bye!
Yeah i heard about the Navmesh. Haven't learn it yet. Also thanks for the reply, it helps a lot. :)
Then, really, learn navmesh. Is one of the usefull tools in unity. 100% recommended :D
Good luck!
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
AI pause and attack a player in c# (script included) 2 Answers
Make player follow waypoints, but still control it's X axis 3 Answers
Looping Between Waypoints 1 Answer