溧陽網(wǎng)站設(shè)計(jì)唐山seo排名
第一步驟安裝并導(dǎo)入Dotween插件(也可以不用導(dǎo)入之后直接下載我的安裝包)
官網(wǎng)DOTween - 下載
第二步: 制作跳字預(yù)制體
?建議把最佳適應(yīng)打開,這樣就不怕數(shù)字太大顯示不全了。
第三步:創(chuàng)建一個空對象并編寫腳本JumpNumber ,并將腳本拖到空對象上,將跳字預(yù)制體也拖上去。
?這個腳本會接受3個參數(shù),位置(世界坐標(biāo)),傷害多少,是否暴擊三個參數(shù)。然后在屏幕上生成傷害跳字。
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;public class JumpNumber : MonoBehaviour
{public GameObject Number; // 跳字預(yù)制體private Camera mainCamera;//主攝像機(jī)//單例模式public static JumpNumber instance;private void Awake(){// 單例模式的簡單實(shí)現(xiàn),確保JumpNumber在場景中為唯一實(shí)例if (instance == null){instance = this;}else{Destroy(gameObject);}// 自動獲取主攝像機(jī)mainCamera = GameObject.FindWithTag("MainCamera").GetComponent<Camera>();}//傳入目標(biāo)物體,跳字?jǐn)?shù)字,是否暴擊public void ShowJumpNumber(GameObject behitGameObject, float number, bool crit){if (mainCamera == null){Debug.LogError("Main Camera not found!");return;}// 使用目標(biāo)物體的位置Vector3 worldPosition = behitGameObject.transform.position;//將x軸左右偏移一點(diǎn)worldPosition.x += Random.Range(-1f, 1f);//世界坐標(biāo)轉(zhuǎn)屏幕坐標(biāo)Vector3 screenPosition = mainCamera.WorldToScreenPoint(worldPosition);//實(shí)例化預(yù)制體GameObject numberInstance = Instantiate(Number, screenPosition, behitGameObject.transform.rotation);numberInstance.transform.position = screenPosition;//查找畫布的位置GameObject Canvas = GameObject.Find("Canvas");numberInstance.gameObject.transform.SetParent(Canvas.transform);//將浮點(diǎn)型的number轉(zhuǎn)換為整型number = (int)number;// 設(shè)置為最頂層,防止玩家或怪物擋住跳字numberInstance.transform.SetAsLastSibling();numberInstance.GetComponent<Text>().text = number.ToString();//區(qū)分是否暴擊Color color = Color.white;//設(shè)置字體大小Number.GetComponent<Text>().fontSize = 25;if (crit) {//暴擊字體顏色color = Color.red;//設(shè)置字體大小Number.GetComponent<Text>().fontSize = 50;}numberInstance.GetComponent<Text>().color = color;// 使用 DOTween 讓number進(jìn)行移動從Y=0移動到y(tǒng)=800,然后銷毀//設(shè)置一個浮動范圍//OnComplete()是動畫完成后的回調(diào)函數(shù)int jumpfloat = Random.Range(0, 100);numberInstance.transform.DOMoveY(numberInstance.transform.position.y + 100, 0.5f).OnComplete(() => Destroy(numberInstance));}
}
?
第4步:創(chuàng)建一個2D對象,并編寫測試腳本加到這個2D對象上
這個測試腳本會在1——100生成隨機(jī)數(shù),并且大于50的時候?qū)潜粜Ч?
using UnityEngine;public class TextJumpNumber : MonoBehaviour
{void Update(){if (Input.GetKeyDown(KeyCode.Space)){int jumpNumbernum = Random.Range(1, 101);//生成隨機(jī)數(shù)字bool crit = jumpNumbernum > 50;//判斷是否爆擊JumpNumber.instance.ShowJumpNumber(gameObject, jumpNumbernum, crit);}}
}
?第五步:運(yùn)行游戲,按下空格就會看到生成了傷害跳字。
項(xiàng)目包?https://github.com/laozhupeiqia/JumpNumber.git
?如果這篇文章對你有幫助歡迎點(diǎn)贊支持哦!