前言:
這一篇章實現物理碰撞,就是游戲體碰撞減裝甲,這幾天想要試着做出兼具裝甲與血量的模式,可自動回復的裝甲與永久損傷的血量,在一些平台上找到了不少有意思的模型,有興趣的可以自己找找模型替換一下。
射擊類游戲實例
作為第一個用來發布講解的游戲,我立馬就想到了射擊類游戲,當然不是第一人稱射擊的那種,是打小飛機累計得分的那種類型,方便魔改參數以及自行制作一些敵人的模型。
游戲相關設定:
1.在游戲中,我們將操作戰艦擊墜敵人的飛船,游戲開始后戰艦會向前推進,消滅敵人取得分數,戰艦被擊落游戲才會結束。
2.戰艦擁有固定裝甲(血量),敵人有多種並擁有獨特的飛行軌跡與裝甲
3.屏幕上會顯示血量、得分等內容
4.待添加
涉及的英文:
enemy:敵人 box collider:盒碰撞器 physics:物理 Gravity: 重力 Rigidbody:剛體 Kinematic:運動學的 Trigger: 觸發
介紹:
1.UpdaMove函數用來執行敵人的移動,使用了Sin函數使數值在-1~1之間循環往復實現往復運動。
2.Time.time是游戲的進行時間。
3.other.tag=="PlayerRocket"比較字符串判斷碰撞體是否為主角子彈。
4.Rocket rocket=other.GetComponent<Rocket>()語句獲得了對方碰撞體的Rocket腳本組件。
5.m_life-=rocket.m_power語句會逐步減少裝甲,到0時使用Destory消除游戲體。
操作:
1.創建Enemy.cs腳本,編寫代碼實現敵人游戲體的移動
protected virtual void UpdateMove() { float rx = Mathf.Sin(Time.time) * Time.deltaTime; transform.Translate(new Vector3(rx, 0, -m_speed * Time.deltaTime)); }
2.建立敵人游戲體的prefab,並將Enemy腳本指定給它
3.給敵人游戲體添加碰撞體,【Component】—【Physics】—【Box Collider】,在Inspector窗口找到【Is Trigger】,勾選上
4.添加剛體組件,【Component】—【Physics】—【Rigidbody】,取消【Use Gravity】,勾選【Is Kinematic】
5.給主角重復上述操作
6.【Edit】—【Project Settings】—【Tags and Layers】,新建新的Tag,PlayerRocket和Enemy,選中敵人的prefab修改tag為Enemy,子彈的tag為PlayerRocket,主角的tag為Player(內置的沒有就自己創建)
7.打開Rocket.cs編寫代碼實現子彈的碰撞消失
private void OnTriggerEnter(Collider other) { if (other.tag != "Enemy") { return; } else { Destroy(this.gameObject); } }
8.打開Player.cs編寫代碼實現主角的碰撞消失
private void OnTriggerEnter(Collider other) { if (other.tag != "PlayerRocket"){ m_life -= 1; if (m_life <= 0) { Destroy(this.gameObject); } } }
9.打開Enemy.cs編寫代碼實現敵人的碰撞消失與飛出屏幕外自我消失
using System.Collections; using System.Collections.Generic; using UnityEngine; [AddComponentMenu("MyGame/Enemy")] public class Enemy : MonoBehaviour { public float m_speed = 1; public float m_life = 10; protected float m_rotspeed = 30; public Renderer m_renderer; internal bool m_isActiv = false; void OnTriggerEnter(Collider other) { if (other.tag == "PlayerRocket") { rocket rocket = other.GetComponent<rocket>(); if (rocket != null) { m_life -= rocket.m_power; if (m_life <= 0) { Destroy(this.gameObject); } } } else if (other.tag == "Player") { m_life = 0; Destroy(this.gameObject); } } // Start is called before the first frame update void Start() { m_renderer = this.GetComponent<Renderer>(); } private void OnBecameVisible() { m_isActiv = true; } // Update is called once per frame void Update() { UpdateMove(); if (m_isActiv && !this.m_renderer.isVisible) // 如果移動到屏幕外 { Destroy(this.gameObject); // 自我銷毀 } } protected virtual void UpdateMove() { float rx = Mathf.Sin(Time.time) * Time.deltaTime; transform.Translate(new Vector3(rx, 0, -m_speed * Time.deltaTime)); } }
再說一句:
突然發現很多簡單預置函數沒有說明,比如說Vector3,之后涉及多了另說明吧,另外像創建碰撞體時候涉及到重力之類的,后面有用到的具體實例說起來應該會很簡單,