Unity3D實現彈幕的效果,unity3d彈幕
孫廣東 2015.6.15
對於逗比的遊戲、無厘頭、可以讓大家吐糟的遊戲,如果有彈幕的功能是極好的。
使用U5和 UGUI 目前實現的很簡陋而已。
/// <summary> /// 實現看視頻時的彈幕效果 /// </summary> public class DanMu : MonoBehaviour { //public Text[] texts; public GameObject textPrefab; [Tooltip("滿屏的個數")] public int num; private Queue<GameObject> Texts = new Queue<GameObject>(); private bool isDanmuOn = true; private IEnumerator coroutine; // Use this for initialization void Start() { for (int i = 0; i < num; i++) { GameObject obj = Instantiate(textPrefab, transform.position, Quaternion.identity) as GameObject; obj.SetActive(false); obj.transform.SetParent(transform); obj.transform.localScale = Vector3.one; Texts.Enqueue(obj); } coroutine = DanmuAnimation(); StartCoroutine(coroutine); } private IEnumerator DanmuAnimation() { while (true) { GameObject obj = Texts.Dequeue(); if (obj) { obj.transform.localPosition = new Vector3(1071, Random.Range(-512, 512)); obj.GetComponent<Text>().text = DanMuStrings[Random.Range(0, DanMuStrings.Length)]; obj.GetComponent<Text>().color = TextColors[Random.Range(0, TextColors.Length)]; obj.SetActive(true); obj.GetComponent<DanMuText>().Reset(Texts); } yield return new WaitForSeconds(0.2f); } } /// <summary> /// 彈幕的開關 /// </summary> public void DanMuToggle(Toggle toggle) { if (toggle.isOn) { isDanmuOn = true; StartCoroutine(coroutine); MyDebugLog.Log("彈幕開!!!!!"); } else { isDanmuOn = false; DOTween.KillAll(); StopCoroutine(coroutine); // Texts.Clear(); foreach (var text in transform.GetComponentsInChildren<DanMuText>()) // 只能得到被啟用的對象而已, 得不到全部? 所以不用Clear()直接把這些在外面的入隊就行 { Texts.Enqueue(text.gameObject); text.gameObject.SetActive(false); } MyDebugLog.Log("彈幕關!!!!!個數: " + Texts.Count); } } [HideInInspector] public string[] DanMuStrings = { "這個劇情也太雷人了吧!", "還是好萊塢的電影經典啊,這個太次了", "是電鋸驚魂的主角,尼瑪", "這個遊戲還是很良心的麼", "臥槽還要花錢,這一關也太難了", "這個遊戲好棒偶", "全是傻逼", "求約:13122785566", "最近好寂寞啊,還是這個遊戲好啊", "難道玩遊戲還能擼", "辦證:010 - 888888", "為什麼女主角沒有死?", "好帥呦,你這個娘們兒", "欠揍啊,東北人不知道啊", "我去都是什麼人啊,請文明用語", "這個還是不錯的", "要是胸再大點就更好了", "這個遊戲必須頂啊", "怎麼沒有日本動作愛情片中的角色呢?", "好吧,這也是醉了!", "他只想做一個安靜的美男子!" }; public Color[] TextColors; }
和掛在 Text預製體上的 指令碼:
/// <summary> /// /// </summary> public class DanMuText : MonoBehaviour { public void Reset(Queue<GameObject> Texts) { transform.DOLocalMoveX(-1366, 4f).OnComplete(() => { gameObject.SetActive(false); Texts.Enqueue(gameObject); }); } }