Window 7 Unity3D 3.4 MB525 defy / Android 2.1-update1
這是初學 Unity 時寫成的小遊戲 Demo,姑且叫它「躲避方塊」。玩法很單純,但骨架可以無限擴充:加更多障礙、道具、關卡,甚至做成連線對戰。原本只是照著 Unity 腳本文件練習,寫著寫著就成一個小遊戲了。本文挑幾個對開發最關鍵的腳本來講,完整專案另附下載。
遇到看不懂的 API,直接翻 Unity 的 Script Reference 最有效,上面寫得比多數教學都清楚。另外有兩個環境上的坑:升級到 Unity 3.4 之後,.NET 環境必須是 3.5 以上,否則腳本編輯器 Monodevelop 會打不開;再者本遊戲由兩個 Scene 組成,自製時務必到 Build Settings 中確認 Scene 的順序,因為 Application.LoadLevel 用的是索引,順序錯了就會跳錯場景。
Unity 真正的強項在於對遊戲的優化,例如 Occlusion Culling 讓場景可以做更大而不增加負擔,這類技巧值得花時間研究。
觸控是手機平台最主要的操作方式,因此先看菜單腳本 Menu_New:
function Update()
{
for (var touch : Touch in Input.touches)
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved || Input.GetTouch(0).phase == TouchPhase.Began)
{
if(touch.position.x>90 && touch.position.x<540 && touch.position.y>250 && touch.position.y<400)
{
renderer.material.color = Color.red;
}
else
{
renderer.material.color = Color.white;
}
}
else if (touch.phase == TouchPhase.Ended)
{
if(touch.position.x>90 && touch.position.x<540 && touch.position.y>250 && touch.position.y<400)
{
renderer.material.color = Color.red;
Application.LoadLevel(1);
}
}
}
}
Input 是 Unity 取得輸入的統一入口,從裡面可以讀到觸控點數、觸控階段(Began/Moved/Ended)、各種感應器資料,甚至能分辨是第幾個手指。相比過去自己寫 Android 原生多點觸控判斷,這裡輕鬆不少。場景跳轉與結束遊戲同樣透過 Application 類別處理。
要提醒的是,範例把座標寫死成 90–540、250–400,這在實機上幾乎必然失效。正確做法是改用 Input.mousePosition 換算螢幕寬高的比例,或用 Screen.width/Screen.height 正規化,才能對不同解析度都成立。
很多人分不清 Trigger 與 Collider。可以這樣理解:勾成 Trigger 的物體等於「沒有了實體」,東西會直接穿過去,但你能收到事件;Collider 則是實心障礙,會阻擋運動。無論哪一種,都必須由 Rigidbody 帶動,所以兩者相遇時,至少有一方要掛 Rigidbody,OnTriggerEnter 才會被呼叫。
collider.isTrigger = true;
var explosionPrefab : Transform;
// Destroy everything that enters the trigger
function OnTriggerEnter (other : Collider) {
if(other.gameObject.tag == "Player")
{
Destroy(other.gameObject);
Destroy(gameObject);
Instantiate(explosionPrefab, transform.position, Quaternion.identity);
Begin.hasOne = true;
Begin.life--;
GameObject.Find("Life").guiText.text = Begin.life + "";
}
}
這段腳本讓火球與雷球彼此相遇時不會誤觸自爆——因為遊戲節奏會越來越快,同類物件相撞難以避免,用 tag 過濾掉自己人即可。撞到 Player 才扣命、生成爆炸特效並更新 UI 上的生命數字。
另外提醒,直接對靜態變數 Begin.life 做增減,在多場景或重機遊戲時容易出錯;把生命值放進一個專門的 GameManager 物件並用 DontDestroyOnLoad 保留,會乾淨很多。
本次工程原始碼可於 Linux 公社的 FTP 下載:ftp://www.linuxidc.com(帳號 www.linuxidc.com),目錄為 2011年LinuxIDC.com\10月\Android Unity3D游戲開發之躲避方塊附源碼。