element3ds.com
引擎渲染作品 Unity3D 像素风格《猫捕鱼》小游戏(二)
发布于
2017-1-4
3613
46

您需要 登录 才可以下载或查看,没有账号?注册

x
      今天继续上一篇的内容,如何完成这个猫捕鱼的小游戏。


    1.新建一个Game.unity,这是主要的游戏场景;并且在场景中有一个manager对象附加GameManager.cs 组件,组件继承单例类MonoSingleton.cs;
      ①MonoSingleton.cs 代码如下:
  1. using UnityEngine;

  2. /// <summary>
  3. /// @see http://wiki.unity3d.com/index.php/Singleton
  4. /// </summary>
  5. public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
  6. {
  7.         private static T m_Instance = null;

  8.         public static T instance {
  9.                 get {
  10.                         // Instance requiered for the first time, we look for it
  11.                         if (m_Instance == null) {
  12.                                 m_Instance = GameObject.FindObjectOfType (typeof(T)) as T;

  13.                                 // Object not found, we create a temporary one
  14.                                 if (m_Instance == null) {
  15.                                         m_Instance = new GameObject (typeof(T).ToString (), typeof(T)).GetComponent<T> ();
  16.                                         // Problem during the creation, this should not happen
  17.                                         if (m_Instance == null) {
  18.                                                 Debug.LogError ("Problem during the creation of " + typeof(T).ToString ());
  19.                                         }
  20.                                         DontDestroyOnLoad (m_Instance);
  21.                                 }
  22.                                
  23.                                 m_Instance.Init ();
  24.                         }
  25.                         return m_Instance;
  26.                 }
  27.         }
  28.         // If no other monobehaviour request the instance in an awake function
  29.         // executing before this one, no need to search the object.
  30.         private void Awake ()
  31.         {
  32.                 if (m_Instance == null) {
  33.                         m_Instance = this as T;
  34.                         m_Instance.Init ();
  35.                 }
  36.         }

  37.         // This function is called when the instance is used the first time
  38.         // Put all the initializations you need here, as you would do in Awake
  39.         public virtual void Init ()
  40.         {
  41.         }

  42.         // Make sure the instance isn't referenced anymore when the user quit, just in case.
  43.         private void OnApplicationQuit ()
  44.         {
  45.                 m_Instance = null;
  46.         }
  47. }
点击此处复制文本

      ②GameManager.cs 代码如下:
  1. using UnityEngine;
  2. using System.Collections;

  3. public class GameManager : MonoSingleton<GameManager>
  4. {
  5.         public int clearCount = 10;
  6.         public int hp = 3;
  7.         [SerializeField]
  8.         Camera mainCamera;
  9.         private int killCount = 0;
  10.        
  11.         public override void Init ()
  12.         {
  13.                 ScoreManager.instance.Reset();
  14.         }

  15.         public static void DestroyEnemy (int addScorePoint)
  16.         {
  17.                 ScoreManager.instance.AddScore (addScorePoint);
  18.                 AddKillCount ();
  19.         }

  20.         private static void AddKillCount ()
  21.         {
  22.                 instance.killCount += 1;
  23.                 // clear
  24.                 if (instance.killCount >= instance.clearCount)
  25.                         instance.StartCoroutine (instance.GameClear ());
  26.         }

  27.         public static void Miss ()
  28.         {
  29.                
  30.                 Dustbox.instance.StopFishes ();
  31.                 RandomSpawn spawn = GameObject.FindObjectOfType (typeof(RandomSpawn)) as RandomSpawn;
  32.                
  33.                 spawn.enabled = false;
  34.                 Dustbox.instance.StopBullet();
  35.                
  36.                 instance.hp -= 1;
  37.                 spawn.spawnCount = instance.killCount - 1;
  38.                
  39.                
  40.                 // GameOver
  41.                 if (instance.hp <= 0)
  42.                         instance.StartCoroutine (instance.GameOver ());
  43.                 else
  44.                         instance.GetComponent<Animation>().Play ();

  45.                 instance.GetComponent<Animation>().Play ();
  46.                
  47.         }
  48.        
  49.         public void ResetGame ()
  50.         {
  51.                 Destroy (Dustbox.instance.gameObject);
  52.                
  53.                 CatController cat = GameObject.FindObjectOfType (typeof(CatController)) as CatController;
  54.                 cat.Reset ();

  55.                 RandomSpawn spawn = GameObject.FindObjectOfType (typeof(RandomSpawn)) as RandomSpawn;
  56.                 spawn.enabled = true;
  57.                
  58.         }

  59.         public void Fadeout ()
  60.         {
  61.                 if (mainCamera != null)
  62.                         mainCamera.enabled = true;
  63.         }
  64.        
  65.         public void Fadein ()
  66.         {
  67.                 if (mainCamera != null)
  68.                         mainCamera.enabled = false;
  69.         }
  70.        
  71.         IEnumerator GameClear ()
  72.         {
  73.                
  74.                 RandomSpawn spawn = GameObject.FindObjectOfType (typeof(RandomSpawn)) as RandomSpawn;
  75.                 PlayerController controller = GameObject.FindObjectOfType (typeof(PlayerController)) as PlayerController;
  76.                 MusicController sound = GameObject.FindObjectOfType (typeof(MusicController))  as MusicController;
  77.                 AudioClip clip = Resources.Load ("Audio/bgm-jingle1") as AudioClip;
  78.                
  79.                 Dustbox.instance.StopFishes ();
  80.                 spawn.enabled = false;
  81.                 controller.enabled = false;
  82.                
  83.                 if (sound != null)
  84.                         Destroy (sound.gameObject);
  85.                
  86.                 AudioSource.PlayClipAtPoint (clip, Vector3.zero);
  87.                
  88.                 yield return new WaitForSeconds(clip.length);
  89.                
  90.                 Destroy(Dustbox.instance.gameObject);
  91.                 Application.LoadLevel ("Clear");
  92.         }

  93.         public IEnumerator GameOver ()
  94.         {
  95.                 yield return new WaitForSeconds(2);
  96.                 Destroy(Dustbox.instance.gameObject);
  97.                
  98.                 MusicController sound = GameObject.FindObjectOfType (typeof(MusicController)) as MusicController;
  99.                 if (sound != null)
  100.                         Destroy (sound.gameObject);
  101.        
  102.                 Application.LoadLevel ("GameOver");
  103.         }
  104. }
点击此处复制文本

1_0.png

    2.场景中Player 对象,及其附加的组件;
       ① ShotController.cs 射击组件 代码如下:
  1. using UnityEngine;
  2. using System.Collections;

  3. [RequireComponent(typeof(CatController))]
  4. public class ShotController : MonoBehaviour
  5. {
  6.        
  7.         [SerializeField]
  8.         GameObject bulletPrefab;
  9.         private CatAnimationController catAnimation;

  10.         void Start ()
  11.         {
  12.                 catAnimation = GetComponent<CatController> ().GetCatAnimationController ();
  13.         }
  14.        
  15.         public void Shoot ()
  16.         {
  17.                 if (GameObject.FindGameObjectWithTag ("Bullet") != null)
  18.                         return;
  19.                
  20.                 GameObject bullet = GameObject.Instantiate (bulletPrefab) as GameObject;
  21.                 bullet.transform.position = transform.position + Vector3.down * 0.1f + Vector3.forward * 0.2f;
  22.                
  23.                 Vector3 direction = catAnimation.direction;

  24.                 if (direction == Vector3.up)
  25.                         bullet.transform.Rotate (Vector3.forward * 90);
  26.                 else if (direction == Vector3.left)
  27.                         bullet.transform.Rotate (Vector3.forward * 180);

  28.                 bullet.GetComponent<BulletController> ().direction = direction;
  29.         }
  30. }
点击此处复制文本



       ②PlaySound.cs 声音控制 代码如下:
  1. using UnityEngine;
  2. using System.Collections;

  3. public class PlaySound : MonoBehaviour
  4. {
  5.        
  6.         public AudioClip clip;
  7.        
  8.         public void PlayOneShot ()
  9.         {
  10.                 if (clip != null)
  11.                         AudioSource.PlayClipAtPoint (clip, Vector3.zero);
  12.         }
  13. }
点击此处复制文本

       ③PlayerController.cs 主角控制器 代码如下:
  1. using UnityEngine;
  2. using System.Collections;

  3. public class PlayerController : MonoBehaviour
  4. {

  5.         private CatController controller;
  6.         private ShotController shot;
  7.        
  8.         void Start ()
  9.         {
  10.                 controller = GetComponent<CatController> ();
  11.                 shot = GetComponent<ShotController> ();
  12.         }
  13.        
  14.         void Update ()
  15.         {
  16.                 if (Input.GetAxis ("Vertical") > 0)
  17.                         controller.LookUp ();
  18.                 else if (Input.GetAxis ("Horizontal") != 0f)
  19.                         controller.Move (Input.GetAxis ("Horizontal"));

  20.                 if (Input.GetButtonDown ("Fire1"))
  21.                         shot.Shoot ();

  22.                 if (Input.GetKeyDown (KeyCode.LeftShift))
  23.                         Time.timeScale = Time.timeScale == 0 ? 1 : 0;
  24.         }
  25. }
点击此处复制文本


       ④CatController.cs 代码如下:
  1. using UnityEngine;
  2. using System.Collections;

  3. public class CatController : MonoBehaviour
  4. {
  5.        
  6.         CatAnimationController catAnimation;
  7.         [SerializeField]
  8.         float speed = 60;
  9.         private Vector3 firstPosition;
  10.        
  11.         void Start ()
  12.         {
  13.                 catAnimation = GetCatAnimationController ();
  14.                 firstPosition = transform.position;
  15.                 catAnimation.LookUp ();
  16.         }
  17.        
  18.         public CatAnimationController GetCatAnimationController ()
  19.         {
  20.                 return transform.GetComponentInChildren<CatAnimationController> ();
  21.         }
  22.        
  23.         public void Move (float direction)
  24.         {
  25.                 if (direction < 0)
  26.                         catAnimation.MoveLeft ();
  27.                 else
  28.                         catAnimation.MoveRight ();
  29.                
  30.                 transform.Translate (catAnimation.direction * speed * Time.deltaTime);
  31.         }

  32.         public void LookUp ()
  33.         {
  34.                 catAnimation.LookUp ();
  35.         }

  36.         public void Reset ()
  37.         {
  38.                 transform.position = firstPosition;
  39.                 catAnimation.transform.localPosition = Vector3.zero;
  40.                
  41.                 GetComponent<PlayerController> ().enabled = true;
  42.                 catAnimation.LookUp ();
  43.                
  44.                 StartCoroutine (catAnimation.Flashing ());
  45.         }
  46.        
  47.         void OnTriggerEnter (Collider collision)
  48.         {
  49.                 if (collision.CompareTag ("Enemy")) {
  50.                         GameManager.Miss ();
  51.                         catAnimation.failed.enabled = true;
  52.             GetComponent<Collider>().enabled = false;
  53.             GetComponent<Animation>().Play ("MissAnimation@Cat");
  54.                         GetComponent<PlayerController> ().enabled = false;
  55.                 }
  56.         }
  57.        
  58.         void Dead ()
  59.         {
  60.                 StartCoroutine (GameManager.instance.GameOver ());
  61.         }
  62. }
点击此处复制文本
2.png

   

    3.随机生成鱼的出生点;
      RandomSpawn.cs代码如下:
  
  1. using UnityEngine;
  2. using System.Collections;

  3. public class RandomSpawn : MonoBehaviour
  4. {
  5.         [SerializeField]
  6.         GameManager manager;
  7.         [SerializeField]
  8.         GameObject fishPrefab;
  9.         public float spawnPercent = 2f;
  10.         public int spawnCount = 0;
  11.         [SerializeField]
  12.         Transform left = null, right = null;

  13.         void OnDrawGizmosSelected ()
  14.         {
  15.                 if (left == null || right == null)
  16.                         return;
  17.                
  18.                 Gizmos.DrawLine (left.position, right.position);
  19.         }

  20.         void OnEnable ()
  21.         {
  22.                 StartCoroutine (SpawnLoop ());
  23.         GetComponent<Animation>().enabled = true;
  24.         }
  25.        
  26.         void OnDisable ()
  27.         {
  28.                 StopAllCoroutines ();
  29.         GetComponent<Animation>().enabled = false;
  30.         }
  31.        
  32.         IEnumerator SpawnLoop ()
  33.         {
  34.                 while (true) {
  35.                         Spawn ();
  36.                         yield return new WaitForSeconds (spawnPercent);
  37.                 }
  38.         }
  39.        
  40.         public void Spawn ()
  41.         {
  42.                 // spawn limit
  43.                 if (manager.clearCount <= spawnCount)
  44.                         return;
  45.                
  46.                 spawnCount ++;
  47.                
  48.                 float position = Random.Range (left.transform.position.x, right.transform.position.x);
  49.                
  50.                 GameObject fish = GameObject.Instantiate (fishPrefab) as GameObject;
  51.                 fish.transform.position = transform.position + Vector3.left * position + Vector3.forward * 20;
  52.                 fish.transform.parent = Dustbox.instance.transform;
  53.         }
  54.        
  55. }
点击此处复制文本

   
     

    4.设定主角可以重生多次,相应的组件LifeController.cs;
  1. using UnityEngine;
  2. using System.Collections;

  3. public class LifeController : MonoBehaviour
  4. {
  5.        
  6.         [SerializeField]
  7.         GameObject[] life;
  8.         GameManager manager;
  9.        
  10.         void Awake ()
  11.         {
  12.                 manager = FindObjectOfType (typeof(GameManager)) as GameManager;
  13.         }
  14.        
  15.         void OnEnable ()
  16.         {
  17.                 StartCoroutine (LifeCheck ());
  18.         }
  19.        
  20.         void OnDisable ()
  21.         {
  22.                 StopAllCoroutines ();
  23.         }
  24.        
  25.         IEnumerator LifeCheck ()
  26.         {
  27.                 while (true) {
  28.                        
  29.                         for (int i=0; i< life.Length; i++) {
  30.                                 life [i].GetComponent<Renderer>().enabled = i < manager.hp;
  31.                         }
  32.                        
  33.                         yield return new WaitForSeconds(0.5f);
  34.                 }
  35.         }
  36. }
点击此处复制文本


      
     
   
    5.场景中声音的控制 ,组件MusicController.cs;
  1. using UnityEngine;
  2. using System.Collections;

  3. public class MusicController : MonoBehaviour
  4. {
  5.        
  6.         void Start ()
  7.         {
  8.                 if (GameObject.FindObjectsOfType (typeof(MusicController)).Length > 1)
  9.                         Destroy (gameObject);
  10.                 else
  11.                         DontDestroyOnLoad (gameObject);
  12.         }

  13. }
点击此处复制文本




    6.关于计算分数的相关组件;

     ①HighScoreController.cs代码如下:
  1. using UnityEngine;
  2. using System.Collections;

  3. public class HighScoreController : MonoBehaviour
  4. {
  5.        
  6.         TextMesh text;
  7.        
  8.         // Use this for initialization
  9.         void Start ()
  10.         {
  11.                 text = GetComponent<TextMesh> ();
  12.                 ScoreManager.instance.HighScore = PlayerPrefs.GetInt ("highscore");
  13.         }
  14.        
  15.         // Update is called once per frame
  16.         void Update ()
  17.         {
  18.                 text.text = ScoreManager.instance.HighScore.ToString ();
  19.         }
  20. }
点击此处复制文本


     ②ScoreController.cs 代码如下:
  1. using UnityEngine;
  2. using System.Collections;

  3. [RequireComponent(typeof(TextMesh))]
  4. public class ScoreController : MonoBehaviour
  5. {
  6.        
  7.         TextMesh tmesh;
  8.        
  9.         void Awake ()
  10.         {
  11.                 tmesh = GetComponent<TextMesh> ();
  12.         }
  13.        
  14.         void Update ()
  15.         {
  16.                 tmesh.text = ScoreManager.instance.Score.ToString ();
  17.         }
  18. }
点击此处复制文本



     ③ScoreManager.cs 代码如下:
  1. using UnityEngine;
  2. using System.Collections;

  3. public class ScoreManager : MonoSingleton<ScoreManager>
  4. {
  5.         private  int m_Score;
  6.         private  int m_HighScore;

  7.         public int Score {
  8.                 get{ return m_Score;}
  9.                 set { m_Score = value;}
  10.         }

  11.         public  int HighScore {
  12.                 get{ return m_HighScore;}
  13.                 set {
  14.                         PlayerPrefs.SetInt ("highscore", value);
  15.                         m_HighScore = value;
  16.                 }
  17.         }

  18.         public void AddScore (int point)
  19.         {
  20.                 instance.Score += point;
  21.                 instance.HighScore = Mathf.Max (instance.Score, instance.HighScore);
  22.         }

  23.         public void Reset ()
  24.         {
  25.                 instance.Score = 0;
  26.         }
  27. }
点击此处复制文本



    7.新建GameOver.unity 场景,表示游戏失败结束,游戏场景中对象附加GameOverManager.cs组件;
  1. using UnityEngine;
  2. using System.Collections;

  3. public class GameOverManager : MonoSingleton<GameOverManager>
  4. {
  5.         void Update ()
  6.         {
  7.                
  8.                 if (Input.GetButtonDown ("Fire1")) {
  9.                         Application.LoadLevel ("Title");
  10.                 }
  11.        
  12.         }
  13. }
点击此处复制文本



    8.新建Clear.unity 场景,表示游戏胜利,并且清除之前的成绩,可以重新再玩,组件ClearManager.c;
  1. using UnityEngine;
  2. using System.Collections;

  3. public class ClearManager : MonoSingleton<ClearManager>
  4. {

  5.         bool pause = true;
  6.         [SerializeField]
  7.         int waitTime = 3;
  8.        
  9.         IEnumerator Start ()
  10.         {
  11.                 yield return new WaitForSeconds(waitTime);
  12.                
  13.                 pause = false;
  14.         }
  15.        
  16.         void Update ()
  17.         {
  18.                
  19.                 if (pause)
  20.                         return;
  21.                
  22.                 if (Input.GetButtonDown ("Fire1")) {
  23.                         ScoreManager.instance.Reset ();
  24.                         Application.LoadLevel ("Title");
  25.                 }
  26.         }
  27. }
点击此处复制文本



    9.子弹类处理;
       ①BulletController.cs 代码如下:
  1. using UnityEngine;
  2. using System.Collections;

  3. public class BulletController : MonoBehaviour
  4. {
  5.        
  6.         [HideInInspector]
  7.         public Vector3 direction = Vector3.up;
  8.         public float speed = 4f;
  9.         private const float margin = 0.02f;
  10.         private bool isDestroy = false;
  11.        
  12.         void Start ()
  13.         {
  14.                 transform.parent = Dustbox.instance.transform;
  15.                
  16.                 AudioClip shootAudio = Resources.Load ("Audio/shot1") as AudioClip;
  17.                 AudioSource.PlayClipAtPoint (shootAudio, Vector3.zero);
  18.         }
  19.        
  20.         void Update ()
  21.         {
  22.                
  23.                 if( isDestroy )
  24.                         Destroy (gameObject);
  25.                
  26.                
  27.                 transform.Translate (direction * speed * 60 * Time.deltaTime, Space.World);
  28.                
  29.                 Vector3 bulletScreenPos = Camera.main.WorldToViewportPoint (transform.position);
  30.                 if (bulletScreenPos.x < 0 - margin || bulletScreenPos.x > 1 + margin ||
  31.                         bulletScreenPos.y < 0 - margin || bulletScreenPos.y > 1 + margin)
  32.                         Destroy (gameObject);
  33.         }
  34.        
  35.         public void Stop ()
  36.         {
  37.                 enabled = false;
  38.         }
  39.        
  40.         void OnTriggerEnter (Collider collision)
  41.         {
  42.                 if (!collision.CompareTag ("Player"))
  43.                         isDestroy = true;
  44.         }

  45. }
点击此处复制文本



       ②Dustbox.cs 代码如下:
  1. using UnityEngine;

  2. public class Dustbox : MonoSingleton<Dustbox>
  3. {
  4.         public void StopFishes ()
  5.         {
  6.                 foreach (FishController fish  in GetComponentsInChildren<FishController>()) {
  7.                         fish.Stop ();
  8.                 }
  9.         }
  10.        
  11.         public void StopBullet()
  12.         {
  13.                 foreach (BulletController bullet  in GetComponentsInChildren<BulletController>()) {
  14.                         bullet.Stop();
  15.                 }
  16.         }
  17. }
点击此处复制文本



    10.好吧!也许博客写得不是很清晰,但是我们还是一起来看一下运行的效果噢!





    欢迎加我的学习交流群:575561285

源码:
尊敬的游客,如果您要查看本帖关注 或 回复可见内容请关注回复后刷新页面查看!

   
   

6_1.png
参与人数 3 元素币 +3 活跃度 +43

本帖被以下画板推荐:

还没有设置签名!您可以在此展示你的链接,或者个人主页!

使用道具 举报 登录

回复 <
元素战争  发表于 2017-1-4 12:15:56  
2#
{:1_141:} learn
回复 收起回复
使用道具
qq000000  发表于 2017-1-4 12:56:14  
3#
6666
回复 收起回复
使用道具
CHRISHAO  发表于 2017-1-4 13:28:20  
4#
zan
回复 收起回复
使用道具
CWwwer  发表于 2017-1-4 13:39:31  
5#
666666太喜欢了,楼主好人!
回复 收起回复
使用道具
小小橘子  发表于 2017-1-4 15:29:13  
6#
讲道理,我并没有什么耐心去看这些代码
回复 收起回复
使用道具
CWwwer  发表于 2017-1-4 16:11:07  
7#

6666666666
回复 收起回复
使用道具
CWwwer  发表于 2017-1-4 16:11:24  
8#
6666666
回复 收起回复
使用道具
CWwwer  发表于 2017-1-4 16:11:44  
9#

666666666
回复 收起回复
使用道具
苦行者  发表于 2017-1-4 16:19:34  
10#
为了元素币,拼了!
回复 收起回复
使用道具
CHRISHAO  发表于 2017-1-4 16:33:50  
11#

6
回复 收起回复
使用道具
啊实打实宝贝  发表于 2017-1-4 17:12:31  
12#
不错!
回复 收起回复
使用道具
啊实打实宝贝  发表于 2017-1-4 17:13:05  
13#

不错!
回复 收起回复
使用道具
baokebk  发表于 2017-1-4 17:43:49  
14#
许逗推荐过来看看1231232
回复 收起回复
使用道具
魔法禁书目录  发表于 2017-1-4 19:31:42  
15#
这个太666了
回复 收起回复
使用道具
pincers  发表于 2017-1-5 08:56:41  
16#
感谢楼主分享、
回复 收起回复
使用道具
我佛现慈悲  发表于 2017-1-5 10:52:02  
17#
{:1_144:}
回复 收起回复
使用道具
我佛现慈悲  发表于 2017-1-5 10:52:18  
18#
{:1_144:}
回复 收起回复
使用道具
太阳l  发表于 2017-1-5 14:23:07  
19#
·············································································
回复 收起回复
使用道具
376569522  发表于 2017-1-7 00:48:32  
20#
从业不识微元素,做遍项目也枉然
回复 收起回复
使用道具
123下一页

快来发表你宝贵的意见吧!

教练 实名

通过了实名认证的内容创造者

  

主题
18
精华
0
超神
0
扩散
0
微金
153
智慧
57
余额
1
在线时间
30 小时

长枪

快速回复 返回顶部 返回列表