iT邦幫忙

2021 iThome 鐵人賽

DAY 30
0
自我挑戰組

從0開始的UnityAR手機遊戲開發系列 第 30

[第三十天]從0開始的UnityAR手機遊戲開發-另一個物體碰到小龍時會扣血的腳本和後記

打開PlayerController腳本撰寫程式碼

using UnityEngine;
using UnityEngine.UI;

public class PlayerController : MonoBehaviour
{
	private Rigidbody m_rigidbody;

	public string horizontalAxis = "Horizontal";
	public string verticalAxis = "Vertical";

	private float inputHorizontal;
	private float inputVertical;
    
    [Header("小龍的生命數值")]
	public float DragonHP;
	[Header("血條Image")]
	public Image HPimage;

	void Awake()
	{
		//抓取掛此腳本物件的Rigidbody
		m_rigidbody = GetComponent<Rigidbody>();
		////切換小龍的待機動畫
		GetComponent<Animation>().Play("sj001_wait");
	}

	void Update()
	{
		//抓取方向的數值
		inputHorizontal = SimpleInput.GetAxis(horizontalAxis);
		//抓取前進後退的數值
		inputVertical = SimpleInput.GetAxis(verticalAxis);

		//轉彎
		transform.Rotate(0f, inputHorizontal * 0.5f, 0f);
		//前進或後退
		m_rigidbody.AddRelativeForce(new Vector3(0f, 0f, inputVertical) * 30f);

		//前進的數值不等於0的話
		if (inputVertical != 0)
		{
			//rigidbody開始運作
			m_rigidbody.WakeUp();
			//切換小龍的奔跑動畫
			GetComponent<Animation>().Play("sj001_run");
		}
		else
		{
			//rigidbody停止運作
			m_rigidbody.Sleep();
		}
	}

	//2個碰撞器(Collider)碰到時所觸發的事件
    private void OnTriggerEnter(Collider other)
    {
		if (other.gameObject.tag == "Enemy") {
			DragonHP -= 0.1f;
			HPimage.fillAmount = DragonHP;
			GetComponent<Animation>().Play("sj001_hurt");
		}
    }

	//2個碰撞器(Collider)持續觸碰時所觸發的事件
	private void OnTriggerStay(Collider other)
    {
		if (DragonHP<=0) {
			GetComponent<Animation>().Play("sj001_die");
		}
    }

	//碰撞器(Collider)離開另一個碰撞器(Collider)時所觸發的事件
	private void OnTriggerExit(Collider other)
    {
		if (DragonHP <= 0)
		{
			GetComponent<Animation>().Play("sj001_die");
		}
	}
}

點擊Cube打開Inspector選擇Tag→Add Tag,然後按+號New Tag Name取名為Enemy後按Save儲存
https://ithelp.ithome.com.tw/upload/images/20211015/20140569eqyZ6V1nC6.png

回到Cube的Inspector將Tag改為Enemy並勾選Box Collider的Is Trigger
https://ithelp.ithome.com.tw/upload/images/20211015/20140569E0MlFskVPg.png

點擊SJ001打開Inspector把腳本的小龍的生命值改為1後把Hierary的血條Image拖曳到腳本的血條Image中
https://ithelp.ithome.com.tw/upload/images/20211015/20140569L6Xadr8piN.png

輸出之後,將Cube觸碰到小龍,小龍就會出現受傷動畫並扣血囉!

後記:
在這30天撰寫了有關Unity入門的許多相關資料,一開始由不用腳本的簡單專案再深入到需要寫程式這樣,現在看回前面自己發的文章,感覺我的文筆還需要再加強訓練,謝謝這幾天來有來觀看我的文章的人們,你們覺得我的文章有甚麼需要改進可以在下方留言跟我說歐。


上一篇
[第二十九天]從0開始的UnityAR手機遊戲開發-攻擊按鈕和UI血條
系列文
從0開始的UnityAR手機遊戲開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言