[第三十天]从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入门的许多相关资料,一开始由不用脚本的简单专案再深入到需要写程序这样,现在看回前面自己发的文章,感觉我的文笔还需要再加强训练,谢谢这几天来有来观看我的文章的人们,你们觉得我的文章有甚麽需要改进可以在下方留言跟我说欧。


<<:  Day 29 Sniffing & Spoofing 监听与欺骗 (dnschef)

>>:  【Day 29】学 Go 之路的小检讨 + concurrent merge sort

准备Django环境

我们再回到第一天提到的主题内容, 如下图. 我们已经完成training与tracking的部份, ...

不只懂 Vue 语法:什麽是 directive?请示范如何使用 directive?

问题回答 directive(指令)是我们在 Vue 自定义的指令。当我们要重复处理某些工作,例如转...

Day04 - Docker 简单指令操作

查看服务,进入Container 查看docker启用哪些service $ docker-comp...

Day 17 AWS云端实作起手式第七弹 让开机器变得很自动自发Auto Scaling-ReadNode设置

关於Auto Scaling的建置,我们预计会花两到三天的时间来做比较详细说明。 参考Udemy A...

Day#04 TableView

前言 承接昨天的内容,今天来加上viewDidLoad中的逻辑内容{ @•̀ꈊ•́@ } 学习资源 ...