Unity3D游戏开发--基础游戏 SpaceShooter学习笔记(游戏流程脚本)

让我们想想游戏的流程是什么:陨石随机产生,从上方落下,玩家控制飞机躲避并发射子弹击中陨石,击中陨石加分并且显示在屏幕上,飞机撞到陨石游戏结束,按R键重新开始。
本篇脚本实现陨石随机产生、加分、游戏结束判断、按R键重新开始这四个功能。
这里用到了通过协程实现陨石不断随机产生,yield语句使语句的执行有间隔时间段。
使用SceneManager.LoadScene函数实现游戏重启。
加分函数和游戏结束函数都是在碰撞脚本中被调用

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine;

public class GameController : MonoBehaviour {

    public Vector3 spawnValue;
    public GameObject[] hazards;
    public float spawnWait =1f;
    public int n = 10;
    public float wait = 10f;
    private int score;
    private bool gameOver;
    public GameObject helpText;
    public GameObject overText;

    void Start () {
        //开启协程 用yild作为s时间间隔
        StartCoroutine(SpawnWaves());
        gameOver = false;
	}
	
	// Update is called once per frame
	void Update () {
        if(gameOver && Input.GetKeyDown(KeyCode.R))
        {
            UnityEngine.SceneManagement.SceneManager.LoadScene(0);
        }
 
	}
    void Spawn()
    {
        
            GameObject o = hazards[Random.Range(0, hazards.Length)];
            Vector3 p = new Vector3(Random.Range(-spawnValue.x, spawnValue.x), 0f, spawnValue.z);
            Quaternion q = Quaternion.identity;//rotation的类型 与父物体或世界轴旋转一致
            Instantiate(o, p, q);

    }
    IEnumerator SpawnWaves()
    {
        yield return new WaitForSeconds(spawnWait);
        while (true)
        {
            int t = n;
            while (t>0)
            {
                if (gameOver)
                {

                    break;
                }

                t--;
                Spawn();
                yield return new WaitForSeconds(spawnWait);
            }
            yield return new WaitForSeconds(wait);
            if (gameOver)
            {
              
                break;
            }
        }
    
  
}


    public void AddScore(int v)
    {//加分
        score += v;
        GameObject game = GameObject.Find("Score");
        game.GetComponent<Text>().text = "Score:" + score;
    }

    public void GameOver()
    {//游戏结束判断
        gameOver = true;

        
        helpText.GetComponent<Text>().text = "Press 'R' to restart";
        overText.GetComponent<Text>().text = "Game Over";
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值