I've been working on a 2D top-down space shooter game in Unity. I am currently coding the enemy AI, which will be able to follow the player, while also keeping its distance. I am running into a problem where the AI always teleports back to 0 on the Z-axis, which makes the Enemy invisible. Here is my whole enemy script so far.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
float speed = 5;
float stoppingDistance = 4;
float retreatDistance = 2;
Transform player;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
}
void Update()
{
if(Vector2.Distance(transform.position, player.position) > stoppingDistance)
{
transform.position = Vector2.MoveTowards(transform.position, player.position, speed * Time.deltaTime);
} else if(Vector2.Distance(transform.position, player.position) < stoppingDistance && Vector2.Distance(transform.position, player.position) > retreatDistance) {
transform.position = this.transform.position;
} else if(Vector2.Distance(transform.position, player.position) < retreatDistance) {
transform.position = Vector2.MoveTowards(transform.position, player.position, -speed * Time.deltaTime);
}
}
}
Thank you!