Literally no movement With Enemy - Laser Defenders

Hello!
I hope I have asked this in the right spot! SO I am going through the laser Defender videos and got up to the move along path. I have given up after 3 days of trying and copied the code from GitHub, but still the problem remains… IT WONT MOVE! It goes to the first waypoint, but nowhere else. I have checked to make sure the waypoints are in order. I have checked my code, and copied the code (In the end). Here is the copied code I used.

public class EnemyPathing : MonoBehaviour
{
[SerializeField] List waypoints;
[SerializeField] float moveSpeed = 2f;

int waypointIndex = 0;

private void Start()
{
    transform.position = waypoints[waypointIndex].transform.position;
}
private void Update()
{
    Move();
}

private void Move()
{
if (waypointIndex <= waypoints.Count - 1)
{
var targetPosition = waypoints[waypointIndex].transform.position;
var movementThisFrame = moveSpeed * Time.deltaTime;
transform.position = Vector2.MoveTowards(transform.position, targetPosition, movementThisFrame);

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

I hope this can be resolved. OH the unity version I am using is 2020.2.5f1.
Thanks :slight_smile:

1 Like

Hi Kanga,

Try to replace Vector2.MoveTowards with Vector3.MoveTowards in the EnemyPathing class.


See also:

1 Like

Hi Nina, this worked like a charm for me (Unity 2020.3.2f1), but can I ask: Why the Vector2.MoveTowards is not working?

Edit: Nevermind :sweat_smile: I found Out that when I created the waypoints, I forgot to reset the position (Rick would be ashamed of me not being tidy), so I had the waypoints in a “Z” different than the Enemy. They were not in the same plane. I figured it out after checking out other posts. The Vector3 works flawlessly because it transports the enemy to wherever 3D position is the waypoint

1 Like

Exactly. The z-position was the problem. :slight_smile:

Our condition checks if all position values are equal. With Vector2.MoveTowards, the enemy’s z-position gets set to 0f but the z-position of the waypoint is not necessarily 0f too. With Vector3.MoveTowards the enemy moves towards the waypoint position including the z-position.

1 Like

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

Privacy & Terms