Home > Back-end >  Enemy AI Always Teleports to 0 on the Z Axis and Becomes Invisible
Enemy AI Always Teleports to 0 on the Z Axis and Becomes Invisible

Time:01-08

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!

CodePudding user response:

it's been a while since I done unity and its mega late where I'am. But hopefully this helps you get on track.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;

 public class Enemy : MonoBehaviour
 {
 
     public Transform Player;
     float MoveSpeed = 4;
     float MoveSpeed2 = MoveSpeed   2;
     float MaxDist = 4;
     float MinDist = 2; 
 
     void Start()
     {
 
     }
 
     void Update()
     {
         transform.LookAt(Player);
 
         if (Vector2.Distance(transform.position, Player.position) > MinDist && Vector2.Distance(transform.position, Player.position) < MaxDist)
         { 
            //continue aproach
             transform.position  = transform.forward * MoveSpeed * Time.deltaTime;
 
         } else if ( Vector2.Distance(transform.position, Player.position) >= MaxDist && Vector2.Distance(transform.position, Player.position) > MinDist )
             {
                 // get closer
                 transform.position  = transform.forward * MoveSpeed2 * Time.deltaTime;
             } 
             else if(Vector2.Distance(transform.position, player.position) <= MinDist && Vector2.Distance(transform.position, Player.position) < MaxDist) { 
                 
                 // Retreat
                 transform.position  = transform.backward * MoveSpeed2 * Time.deltaTime;
        }
     }
 }
  •  Tags:  
  • Related