Unity3D学习(三)打飞碟游戏

来源:互联网 发布:win10qq网络不可用 编辑:程序博客网 时间:2024/04/30 14:28

第三次比较大的实践是打飞碟游戏,这时老师已经介绍了各种动作管理,工厂模式之类的模式,比较方便管理,也方便丰富游戏内容。

这次作业有使用运动学和物理学两种处理方式
这里同样仅贴出游戏效果和代码。
这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

checkCollision.cs

using System.Collections;using System.Collections.Generic;using UnityEngine;using game;namespace game {    public class checkCollision : MonoBehaviour {        public Camera cam;        FirstSceneController sceneController;        // Use this for initialization        void Start () {            cam = Camera.main;            sceneController = Director.getInstance ().currentSceneController as FirstSceneController;        }        // Update is called once per frame        void Update () {            if (Input.GetMouseButtonDown (0)) {                Vector3 mp = Input.mousePosition;                Ray ray = cam.ScreenPointToRay (mp);                RaycastHit hit;                if (Physics.Raycast (ray, out hit)) {                    Debug.Log ("enter hit...");                    Debug.Log (hit.collider.gameObject.tag);//                  Disk disk = hit.collider;//                  sceneController.hitDisk (hit.collider.gameObject);//                  Debug.Log(hit.transform.GetComponent<DiskScript> ().disk);                    Disk disk = hit.transform.GetComponent<DiskScript> ().disk;                    if (hit.collider.tag == "Player") {                        Debug.Log ("hit the disks...");//                      Disk disk = hit.transform.GetComponent<DiskScript> ().disk;                        sceneController.hitDisk (disk);                    }//                  if (hit.collider.tag == "Finish") {//                      Debug.Log ("hitting the grond...");//                      sceneController.hitGround (hit.point);//                  }//                  if (hit.collider.tag == "Test") {//                      Debug.Log ("collision test...");//                  }                }            }        }    }}

Director.cs

using System.Collections;using System.Collections.Generic;using UnityEngine;using game;namespace game {    public class Director : System.Object {        private static Director _instance;        public SceneController currentSceneController;        public static Director getInstance() {            if (_instance == null) {                _instance = new Director ();            }            return _instance;        }    };}

Disk.cs

using System.Collections;using System.Collections.Generic;using UnityEngine;using game;namespace game {    public class Disk {        GameObject disk;        DiskScript diskScript;        public Vector3 startPos;//      public Vector3 endPos;        Vector3 speed = Vector3.zero;        public Disk(GameObject d) {            startPos = new Vector3 (30, 0, 100);            disk = d;            diskScript = d.AddComponent<DiskScript> ();            diskScript.disk = this;            disk.tag = "Player";//          endPos = new Vector3 (5, 4, 3);//          disk = Object.Instantiate (Resources.Load("prefabs/Disk", typeof (GameObject)), startPos) as GameObject;//          disk.AddComponent<Rigidbody> ();        }        public GameObject getGameObj() {            return disk.gameObject;        }        public Rigidbody getRigidbody() {            return disk.GetComponent<Rigidbody> ();        }        public void disappear() {            Debug.Log ("Disk disappeared...");            this.disk.SetActive (false);        }        public void appear() {            Debug.Log ("Disk appeared...");            this.disk.SetActive (true);        }        public void setObj(GameObject obj) {            disk = obj;        }    };}

DiskFactory.cs

using System.Collections;using System.Collections.Generic;using UnityEngine;using game;namespace game {    public class DiskFactory : MonoBehaviour {        Queue<Disk> freeQueue;        List<Disk> usingList;        int count;        GameObject originalDisk;        Vector3 startPos;        Vector3 endPos;        void Awake() {            freeQueue = new Queue<Disk> ();            usingList = new List<Disk> ();            count = 0;            startPos = new Vector3 (30, 0, 100);            endPos = new Vector3 (100, 0, 100);            originalDisk = Object.Instantiate (Resources.Load("prefabs/Disk", typeof (GameObject))) as GameObject;            originalDisk.transform.position = startPos;            originalDisk.AddComponent<Rigidbody> ();            originalDisk.SetActive (false);        }        // Use this for initialization        void Start () {        }        // Update is called once per frame        void Update () {        }        public Disk produceDisk() {            Disk newDisk;            newDisk = null;            if (freeQueue.Count == 0) {                Debug.Log ("produce a new disk");                GameObject newObj = GameObject.Instantiate (originalDisk);                newDisk = new Disk (newObj);                Debug.Log ("disk appear...");                newDisk.getGameObj ().SetActive (true);//appear                count++;//              freeQueue.Enqueue (newDisk);            } else {                Debug.Log ("reuse the old disk");                newDisk = freeQueue.Dequeue ();                newDisk.appear ();            }            newDisk.getGameObj ().transform.position = startPos;            usingList.Add (newDisk);            return newDisk;        }        public void recycle (Disk disk) {            Debug.Log ("recycle...");            disk.disappear ();            disk.getGameObj ().transform.position = endPos;            usingList.Remove (disk);            freeQueue.Enqueue (disk);            Debug.Log (freeQueue.Count);        }        public void recycleAll() {            while (usingList.Count != 0) {                recycle (usingList[0]);            }        }    }}

DiskScript.cs(这个是为了能从GameObj获取到controller)

using System.Collections;using System.Collections.Generic;using UnityEngine;using game;namespace game {    public class DiskScript : MonoBehaviour {        public Disk disk;        // Use this for initialization        void Start () {            for (int i = 0; i < transform.childCount; i++)            {                GameObject g = transform.GetChild(i).gameObject;                g.AddComponent<DiskScript>().disk = disk;            }        }        // Update is called once per frame        void Update () {        }    }}

FirstSceneController.cs

using System.Collections;using System.Collections.Generic;using UnityEngine;using UnityEngine.UI;using game;namespace game {    public class FirstSceneController : MonoBehaviour, userAction, SceneController {//      private FirstSceneActionManager actionManager;        private MoveAction ma;        private SSMoveAction ssma;        private Scorer scorer;        userGUI UI;        DiskFactory df;        Disk disk;        int round;        bool started = false;        float timeLimit = 5f;        float currentTime = 0;        Ruler ruler;        Text ScoreText;//分数文本        Text RoundText;//轮数文本 //      Text gameover;        GameObject canvas;//      public GUIText GameText;//倒计时文本  //      public GUIText FinalText;//结束文本        void Awake() {            Debug.Log ("Awake...");            Director director = Director.getInstance ();            director.currentSceneController = this; // ???            UI = gameObject.AddComponent<userGUI> () as userGUI;// ???            loadResources();            round = -1;        }        void Start() {//          actionManager = GetComponent<FirstSceneActionManager> ();            ma = GetComponent<MoveAction> ();            ssma = GetComponent<SSMoveAction> ();            df = GetComponent<DiskFactory> ();            scorer = GetComponent<Scorer> ();            ruler = new Ruler (round);            canvas = GameObject.Instantiate (Resources.Load ("prefabs/Canvas")) as GameObject;            ScoreText = canvas.transform.Find("Score").GetComponent<Text> ();            RoundText = canvas.transform.Find ("Round").GetComponent<Text> ();            RoundText.text = "Round:0";        }        void Update() {//          ScoreText.text = "Score:" + scorer.getScore().ToString();              if (round != -1) RoundText.text = "Round:" + round.ToString();             ScoreText.text = "Score:" + scorer.getScore().ToString();            if (started) {                currentTime += Time.deltaTime;            }            if ((currentTime >= timeLimit) && round < 3 && scorer.getScore () >= enough (round) && started) {                Debug.Log ("call nextRound()...");                Debug.Log ("round is : ");                Debug.Log (round);                currentTime = 0;                df.recycleAll ();                nextRound ();//              Debug.Log ("nextRound...");            } else if ((currentTime >= timeLimit) && scorer.getScore () < enough (round)) {                df.recycleAll ();                started = false;                gameover ();            }            if (scorer.getScore () >= 6) {                Debug.Log (scorer.getScore());                youWin ();            }        }        public void gameover() {            UI.gameover = true;        }        public void loadResources() {            Debug.Log ("Loading resources...");        }        public void startGame() {            round = 0;//          disk = new Disk ();            nextRound();        }        public void hitDisk(Disk disk) {            if (round == -1)                return;//          scorer.setRound (round);//          Debug.Log(ruler);//test//          scorer.addScore();            scorer.addScore (ruler);            Debug.Log (disk);            Debug.Log ("Enter hitDisk...");            Debug.Log (scorer.getScore());//test            if (disk != null) df.recycle(disk);//          disk.SetActive(false);//          Debug.Log("test");        }        public void nextRound() {            if (round == -1)                return;//          round++;//          Vector3 force = getRoundForce ();//need Manager//          print(df);            Debug.Log ("current round is : ");            Debug.Log (round);            started = true;            ruler = new Ruler (round);//          Debug.Log(ruler);//test            ma.setRuler (ruler);//  刚体控制            ma.setDisk (df.produceDisk());//          ssma.setDisk (df.produceDisk ());//运动学控制//          ssma.setRuler (ruler);            Debug.Log ("produced a disk...");//          Debug.Log (scorer.getScore());//          if (scorer.getScore () == enough(round)) {//              Debug.Log ("enter next round");//              nextRound ();//          }            round++;        }        public void restart() {            currentTime = 0;            round = 0;            scorer.reset ();            Debug.Log ("restart");            nextRound ();        }        public void youWin() {            UI.win = true;        }        public int enough(int round) {            if (round == 1) {                return 1;            } else if (round == 2) {                return 3;            } else {                return 6;            }        }        public void hitGround(Vector3 hitPos) {            Debug.Log ("hitted the ground...");        }    }}

interface.cs

using System.Collections;using System.Collections.Generic;using UnityEngine;using game;namespace game {    public interface userAction {//      void loadResource();        void startGame();        void restart();    }    public interface SceneController {        void loadResources();    }}

Ruler.cs

using System.Collections;using System.Collections.Generic;using UnityEngine;using game;namespace game {    public class Ruler {        int round;        Vector3 startPos;        int point;        Color color;        public Ruler(int r) {            round = r;            if (round == 0) {                startPos = new Vector3 (30, 0, 100);                point = 1;                color = Color.red;            } else if (round == 1) {                startPos = new Vector3 (30, 0, 100);                point = 2;                color = Color.blue;            } else {                startPos = new Vector3 (30, 0, 100);                point = 3;                color = Color.black;            }        }        public int getPoint() {            return point;        }        public void setRound(int r) {            round = r;        }        public Color getColor() {            return color;        }    };}

Scorer.cs

using System.Collections;using System.Collections.Generic;using UnityEngine;using game;namespace game {    public class Scorer : MonoBehaviour {        int score;        int round;        // Use this for initialization        public Scorer() {            score = 0;            round = 0;        }        void Start () {            score = 0;            round = 0;        }        // Update is called once per frame        void Update () {        }        public void setRound(int rnd) {            round = rnd;        }        public void addScore(Ruler ruler) {            score += ruler.getPoint ();        }//      public void addScore() {//          if (round == 0) {//              score += 1;//          } else if (round == 1) {//              score += 2;//          } else {//              score += 3;//          }//      }        public int getScore() {            return score;        }        public void reset() {            round = 0;            score = 0;        }    }}

userGUI.cs

using System.Collections;using System.Collections.Generic;using UnityEngine;using game;public class userGUI : MonoBehaviour {    userAction action;    public int Flag = 0;    public bool gameover = false;    public bool win = false;    // Use this for initialization    void Start () {        action = Director.getInstance ().currentSceneController as userAction;        Flag = 1;        gameover = false;        win = false;    }    // Update is called once per frame    void Update () {    }    void OnGUI() {//      Debug.Log (Flag);        if (Flag == 1) {//          Debug.Log (Flag);            if (GUI.Button (new Rect (Screen.width / 2 - 70, Screen.height / 2, 140, 70), "start")) {                Debug.Log ("start Button");                Flag = 0;                action.startGame ();//              Debug.Log (Flag);            }        }        if (gameover) {            Debug.Log ("game over");            if (GUI.Button (new Rect (Screen.width / 2 - 70, Screen.height / 2, 140, 70), "Game Over")) {                action.restart ();                gameover = false;            }        }        if (win) {            Debug.Log ("you win");            if (GUI.Button (new Rect (Screen.width / 2 - 70, Screen.height / 2, 140, 70), "You win!")) {                action.restart ();                gameover = false;                win = false;            }        }    }}
0 0
原创粉丝点击