Laser Defender, Waypoints Issue

Hello, I was following the Laser Defender guide part 11 (Pathfinding). And encountered an issue with enemy not following the waypoints. I did everything exactly as in video. And My first route was working fine, but when I added new path and attached it to new enemy prefab, the enemy just stay on the first waypoint. When I tried new path on my first enemy, it stopped moving too. It started all over againg rewrote the scripts. And the enemy did not move at all this time. I serialized all i could to check if something was missing. But everyithing was ok.

I noticed that the waypoing index was not increasing in Inspector. When i manually incremented it, the ship started to move to second waypoint. When i dragged the ship right after play button was pressed it moved to the very first waypoint and stopped there.

So i figured out that something didnt let the index to increment. The compiler did not show any error.
I accidently replaced Vector2 with Vector3 in the Pathfinder script in the line:
float delta = waveConfig.GetMoveSpeed() * Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, targetPosition, delta);

to:

float delta = waveConfig.GetMoveSpeed() * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, targetPosition, delta);

and then everyting started to work again.

In video it is mentioned that one has to use Vector3 insted of Vector2 in the line

Vector3 targetPosition = waypoints[waypointIndex].position;

to make this condition not give error:

if(transform.position == targetPosition)
{
waypointIndex++;
}

But even if it doesnt show any error, there should be all vector 3’s to make script work

3 Likes

Hi zanjin,

Welcome to our community, and good job on analysing the problem! :slight_smile:

Whether you use Vector2 or Vector3 does not matter for the compiler. The code is valid. However, our condition is very specific: if (transform.position == targetPosition).

Since transform.position is of type Vector3, a Vector2 objects will get implicitely converted to a Vector3 object with z = 0f.

If targetPosition.z != 0f, the whole condition will become false, and the waypointIndex will never increment.

If you want to use Vector2, you need to ensure that the targetPosition.z is 0f. Only then the code will work as expected.

I hope this made sense. :slight_smile:


See also:

3 Likes

Yes, thank you, that makes sense now.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms