软件编程
位置:首页>> 软件编程>> C#编程>> Unity3D实现飞机大战游戏(2)

Unity3D实现飞机大战游戏(2)

作者:阿浪啊  发布时间:2021-11-16 10:41:38 

标签:Unity3D,飞机大战

本文为大家分享了Unity3D飞机大战游戏第一部分的实现代码,供大家参考,具体内容如下

让飞机可以发射 *

准备工作:

1、将 * 设置成预制体
2、在飞机下新建一个子物体Gun

Unity3D实现飞机大战游戏(2)

3、调整好位置以后,将 * 设置成预制体


//发射 * 的速率
public float rate = 0.2f;
public GameObject bullet;// * 的类型
//发射 * 的方法
public void fire()
{
 //初始化一个 * 预制体
 GameObject.Instantiate(bullet, transform.position, Quaternion.identity);
}

public void openFire(){
 //每隔多长时间使用发射 * 的方法
 InvokeRepeating("fire", 0, rate);
}
//ctrl+shift+m添加生命周期函数
private void Start()
{
 openFire();
}

敌机的制作与运动

1.将敌机放入到游戏场景当中,给敌机添加脚本
2.敌机应当拥有自己的血量和速度,且向下移动
3.当敌机在游戏界面外后,销毁敌机


//默认血量
public int hp = 1;
//默认速度
public float speed = 2;
// Update is called once per frame
void Update()
{
 //飞机向下移动
 this.transform.Translate(Vector3.down*speed*Time.deltaTime);
 if (this.transform.position.y <= -5.6f)
 {
  Destroy(this.gameObject);
 }
}

奖励物品


public int type;//表示 * 的类型
public float speed = 1.5f;//奖励物品下落速度
// Update is called once per frame
void Update()
{//让其进行下降
 this.transform.Translate(Vector3.down * speed * Time.deltaTime);
 //如果出了游戏边界区域以后销毁
 if (this.transform.position.y <= -4.5f)
 {
  Destroy(this.gameObject);
 }
}

随机生成 * 和敌机

1.在游戏场景上方新建一个空物体,让其位置处生成敌机和奖励物品,将其移到屏幕外
2.将敌机和奖励物品设置为预制体Prefabs


//第0号敌机
public GameObject enemy0Prefab;
//第1号敌机
public GameObject enemy1Prefab;
//第二号敌机
public GameObject enemy2Prefab;
//奖励物品的预制体
public GameObject award0Prefab;
public GameObject award1Prefab;
//敌机生成的速率
public float enemy0Rate=0.5f;
public float enemy1Rate = 5f;
public float enemy2Rate = 8f;
//奖励物品生成的速率
public float award0Rate = 7f;
public float award1Rate = 10f;
// Start is called before the first frame update
void Start()
{
 InvokeRepeating("creatEnemy0", 1, enemy0Rate);
 InvokeRepeating("creatEnemy1", 5, enemy1Rate);
 InvokeRepeating("creatEnemy2", 8, enemy2Rate);
 InvokeRepeating("creatAward0", 15, award0Rate);
 InvokeRepeating("creatAward1", 18, award1Rate);
}
//生成第0号敌机
//位置信息的x信息应当要随机生成
public void creatEnemy0()
{
 float x = Random.Range(-2.15f, 2.15f);
 Instantiate(enemy0Prefab, new Vector3(x,transform.position.y,0), Quaternion.identity);
}

public void creatEnemy1()
{
 float x = Random.Range(-2f, 2f);
 Instantiate(enemy1Prefab, new Vector3(x, transform.position.y, 0), Quaternion.identity);
}
public void creatEnemy2()
{
 float x = Random.Range(-1.5f, 1.5f);
 Instantiate(enemy2Prefab, new Vector3(x, transform.position.y, 0), Quaternion.identity);
}
public void creatAward0()
{
 float x = Random.Range(-2f, 2f);
 Instantiate(award0Prefab, new Vector3(x, transform.position.y, 0), Quaternion.identity);
}
public void creatAward1()
{
 float x = Random.Range(-2f, 2f);
 Instantiate(award1Prefab, new Vector3(x, transform.position.y, 0), Quaternion.identity);
}

更多有趣的经典小游戏实现专题,分享给大家:

C++经典小游戏汇总

python经典小游戏汇总

python俄罗斯方块游戏集合

JavaScript经典游戏 玩不停

javascript经典小游戏汇总

来源:https://blog.csdn.net/qq_42216823/article/details/88364183

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com