当玩家在身边时产生AI(Unity3d / C#)

时间:2017-08-14 23:33:12

标签: c# unity3d

我有一个脚本,当前通过设置位置(点生成)生成敌人。我想知道如果玩家在距离产卵点50米范围内,我怎么能让它们产卵。

流浪经理:

public class WanderingManager : MonoBehaviour {

    public Transform[] wanderingPoints;

    void getNewPos(GameObject target){
        target.SendMessage("setNewWanderPos", wanderingPoints[Random.Range(0, wanderingPoints.Length)].position, SendMessageOptions.DontRequireReceiver);
    }
}

Enemy Manager脚本:

[RequireComponent(typeof(WanderingManager))]

public class EnemyManager: MonoBehaviour {

    public int maxZombies = 7;
    public float spawnInterval = 5.0f;
    public string zombiesTag = "Zombie", playerTag = "Player";
    public GameObject[] ZombiePrefabs = null;

    private GameObject player = null;
    private ArrayList Zombies = new ArrayList();
    private float lastTime = -10.0f;
    private bool loaded = false;
    private WanderingManager manager;
    void Start () {
        manager = GetComponent<WanderingManager>();
        findPlayer();
    }

    // Update is called once per frame
    void LateUpdate () {

        if(player == null && loaded){
            StartCoroutine(Restart());
        }

        if(Time.time > lastTime){
            for(int i=0; i<Zombies.Count; i++){
                if(Zombies[i] == null){
                    Zombies.RemoveAt(i);
                }
            }

            if(Zombies.Count > maxZombies){
                Zombies.RemoveAt(Zombies.Count - 1);
            }else{
                Transform point = manager.wanderingPoints[Random.Range(0, manager.wanderingPoints.Length)];
                GameObject Z = Instantiate(ZombiePrefabs[Random.Range(0, ZombiePrefabs.Length)], point.position, point.rotation * Quaternion.Euler(0.0f, Random.Range(0.0f, 180.0f), 0.0f)) as GameObject;
                Zombies.Add(Z);
            }
            lastTime = Time.time + spawnInterval;
        }
    }

    void findPlayer(){
        GameObject newPlayer = GameObject.FindWithTag(playerTag);
        if(newPlayer != null && !newPlayer.name.Contains("Clone")){
            player = newPlayer;
            loaded = true;
        }else if(newPlayer != null && newPlayer.name.Contains("Clone")){
            Destroy(newPlayer);
            retrySearch();
        }
    }

    void retrySearch(){
        findPlayer();
    }

    IEnumerator Restart(){

        yield return new WaitForSeconds(10.0f);

        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
}

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

做一个距离检查。像这样:

if (Vector3.Distance(player.transform.position,enemySpawn.transform.position) < 50):
{
     spawnEnemyLogic();
}