unity3d开发 打飞机小游戏(四)(敌机/奖励物品生成)

来源:互联网 发布:国家对人工智能的政策 编辑:程序博客网 时间:2024/04/27 22:04

紧接着上一期哈,我们讲一下怎么随机生成敌机和奖励物品

首先在资源里面找到你的敌机和奖励物品,拖到场景,选好layer,应该都很熟练了吧,然后给敌机和奖励物品添加一下脚本

敌机的脚本,比较简单

public class Emeny : MonoBehaviour {    public int hp = 1;    public float Speed = 2;    public int score;// Update is called once per framevoid Update () {        transform.Translate(Vector3.down * Speed * Time.deltaTime);        if(transform.position.y<=-5.3f){            Destroy(this.gameObject);        }}}
奖励物品脚本,这里分了两种奖励物品,所以设定了一个type

public class Award : MonoBehaviour {    public int type = 0; // 0 gun 1 explode    public float Speed = 1.5f;// Update is called once per framevoid Update () {        transform.Translate(Vector3.down * Speed * Time.deltaTime);        if (transform.position.y <= -4.5f)            Destroy(this.gameObject);}}
设置完之后呢给物品添加脚本,然后就可以拖进prefabs里面了


这样我们到目前为止就拥有了这么多的模型了


这样呢你可能会发现,敌机和奖励物品不能自动无限出来啊?我们呢就可以给它一个触发器来控制它

建一个空物品,把它拖到场景外一点,这样呢生成出来的敌机不会太突兀是吧

添加脚本,脚本看了上一期的应该非常简单,这里唯一不同的是我们添加了一个在x轴上的随机生成,至于随机的范围怎么确定呢,非常简单,你拖一个物品到场景里然后左右拖动就可以知道范围了~

public class Spawn : MonoBehaviour {    public GameObject enemy0Prefab;    public GameObject enemy1Prefab;    public GameObject enemy2Prefab;    public GameObject award0Prefab;    public GameObject award1Prefab;    //生成敌机/奖励的速率    public float enemy0Rate = 0.5f;    public float enemy1Rate = 2f;    public float enemy2Rate = 5f;    public float award0Rate = 6f;    public float award1Rate = 10f;    // Use this for initialization    void Start () {        InvokeRepeating("createEnemy0", 1, enemy0Rate);        InvokeRepeating("createEnemy1", 2, enemy1Rate);        InvokeRepeating("createEnemy2", 3, enemy2Rate);        InvokeRepeating("createAward0", 6, award0Rate);        InvokeRepeating("createAward1", 10, award1Rate);    }    public void createEnemy0(){        float x = Random.Range(-2.16f,2.16f);        GameObject.Instantiate(enemy0Prefab, new Vector3(x,transform.position.y,0), Quaternion.identity);    }    public void createEnemy1()    {        float x = Random.Range(-2.14f, 2.14f);        GameObject.Instantiate(enemy1Prefab, new Vector3(x, transform.position.y, 0), Quaternion.identity);    }    public void createEnemy2()    {        float x = Random.Range(-2.0f, 2.0f);        GameObject.Instantiate(enemy2Prefab, new Vector3(x, transform.position.y, 0), Quaternion.identity);    }    public void createAward0()    {        float x = Random.Range(-2.0f, 2.0f);        GameObject.Instantiate(award0Prefab, new Vector3(x, transform.position.y, 0), Quaternion.identity);    }    public void createAward1()    {        float x = Random.Range(-2.0f, 2.0f);        GameObject.Instantiate(award1Prefab, new Vector3(x, transform.position.y, 0), Quaternion.identity);    }}

这样添加好脚本,并且把敌机和奖励物品拖进脚本之后呢,就可以运行啦

是不是很好玩呢,感觉动手试试吧



0 0