敌人 AI 总是传送到 Z 轴上的 0 并变得隐形

Enemy AI Always Teleports to 0 on the Z Axis and Becomes Invisible

我一直在使用 Unity 开发 2D 俯视 space 射击游戏。我目前正在编写敌人 AI 的代码,它将能够跟随玩家,同时保持距离。我 运行 遇到了一个问题,即 AI 总是传送回 Z 轴上的 0,这使得敌人不可见。到目前为止,这是我的整个敌人脚本。

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);
        }
    }
}

谢谢!

自从我完成 unity 以来已经有一段时间了,而且我现在已经很晚了。但希望这能帮助您走上正轨。

 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;
        }
     }
 }