如何随机产生敌人?

时间:2014-11-28 11:19:08

标签: c# unity3d

我正在使用EnemyScript将敌人移向玩家并杀死玩家,但我无法在代码中随机生成它。我目前通过将预制件放在场景上直接通过屏幕产生它。

这是我的EnemyScript

using UnityEngine;
using System.Collections;

public class EnemyScript : MonoBehaviour {

public Transform target;
public float speed = 2f;

void Update ()
{
    transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}


void OnTriggerEnter2D(Collider2D otherCollider)
{
    PlayerControl shot = otherCollider.gameObject.GetComponent<PlayerControl>();
    if (shot != null)
    {
        Destroy(shot.gameObject); 
    }
}

}

3 个答案:

答案 0 :(得分:1)

你可以使用类似的东西:

public GameObject myObj;

void Start () 
{
    enemy = GameObject.Find("enemy");
    InvokeRepeating("SpawnEnemy", 1.6F, 1F);                
}

public void SpawnEnemy() 
{       

    Vector3 position = new Vector3(Random.Range(35.0F, 40.0F), Random.Range(-4F, 2F), 0);       
    Instantiate(myObj, position, Quaternion.identity);

}
在InvokeRepeating调用中,您可以在那里添加随机范围,而不是定时实例化。这个例子只是我之前做过的一些原型代码的片段,它可能不能直接满足你的需求,但希望能给你一个关于做什么的一般想法。

编辑:有意义的是,将它放入场景中的某个空白对象,不要将其附加到真正的敌人身上。

答案 1 :(得分:0)

我这样编程了。

public GameObject enemyPrefab;
public float numEnemies;
public float xMin = 20F;
public float xMax = 85F;
public float yMin = 3.5F;
public float yMax = -4.5F;

void Start () {

    for (int i=0; i< numEnemies; i++) {
        Vector3 newPos = new Vector3(Random.Range(xMin,xMax),Random.Range(yMin,yMax),0);
        GameObject enemy = Instantiate(enemyPrefab,newPos,Quaternion.identity) as GameObject;
    }
}

答案 2 :(得分:0)

随机时间段之后,这会在随机位置产生随机数量的敌人,所有敌人都可以在Inspector中调整。

public float minTime = 1;
public float maxTime = 3;
public int minSpawn = 1;
public int maxSpawn = 4;
public Bounds spawnArea; //set these bounds in the inspector
public GameObject enemyPrefab;

private spawnTimer = 0;

Vector3 randomWithinBounds(Bounds r) {
    return new Vector3(
        Random.Range(r.min.x, r.max.x),
        Random.Range(r.min.y, r.max.y),
        Random.Range(r.min.z, r.max.z));
}

void Update() {
    spawnTimer -= Time.deltaTime;
    if(spawnTimer <= 0) {
        spawnTimer += Random.Range(minTime, maxTime);
        int randomSpawnCount = Random.Range(minSpawn, maxSpawn);
        for(int i = 0; i < randomSpawnCount; i++) {
            Instantiate(transform.transformPoint(enemyPrefab), randomWithinBounds(spawnArea), Quaternion.identity);
        }
    }
}

//bonus: this will show you the spawn area in the editor

void OnDrawGizmos() {
    Gizmos.matrix = transform.localToWorldMatrix;
    Gizmos.color = Color.yellow;
    Gizmos.drawWireCube(spawnArea.center, spawnArea.size);
}

这里的人似乎喜欢使用协同程序来延迟时间,但我个人更喜欢在Update()中跟踪自己的计时器,以最大限度地提高控制力和可预测性。

相关问题