1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Unity3d C#用UGUI系统实现类似于哔哩哔哩(B站)的弹幕效果功能(含源码)

Unity3d C#用UGUI系统实现类似于哔哩哔哩(B站)的弹幕效果功能(含源码)

时间:2024-02-16 17:14:04

相关推荐

Unity3d C#用UGUI系统实现类似于哔哩哔哩(B站)的弹幕效果功能(含源码)

前言

弹幕的功能在一些,需要滚动显示文字信息的场景下,还是很有需要。这里就模拟实现一下类似于B站弹幕的效果。

效果

如图的效果:

实现过程

实现的思路是一个管理脚本,加上一个移动文本的脚本,管理脚本随机颜色、位置等信息,移动文字的脚本就单纯的控制自身从右至左的移动,移动到最左侧时,更新弹幕文字内容和颜色,从最右边随机个上下位置,一直重复该过程。

编写弹幕文本脚本

using UnityEngine;using UnityEngine.UI;//弹幕Text对象[RequireComponent(typeof(Text))]public class DanMuText : MonoBehaviour{[Header("父节点和自己节点Rect")]public RectTransform PRect,MRect;[Header("Text组件")]public Text text;bool IsMove = false;float Posx, PosY;[Header("移动速度")]public float Speed = 180;// Start is called before the first frame updatevoid Start(){if (text == null)text = GetComponent<Text>();}private void FixedUpdate(){if (IsMove){transform.localPosition += Time.deltaTime * Vector3.left * Speed;if (transform.localPosition.x <= -Posx) {IsMove = false;StartMove();}}}//停止弹幕public void StopMove() {IsMove = false;transform.localScale = Vector3.zero;}//开始弹幕public void StartMove(){Posx = (PRect.rect.width + MRect.rect.width) / 2;PosY = PRect.rect.height / 2;float RandY = DanMuMgr.instance.GetRandPosY(PosY);text.text = DanMuMgr.instance.GetDanMuStr();text.color = DanMuMgr.instance.GetColor();transform.localPosition = new Vector3(Posx, RandY, 0);transform.localScale = Vector3.one;IsMove = true;}}

实现较简单,就提供了开始和停止的两个接口。

编写弹幕管理脚本

//更新弹幕列表void UpdateDanMuList() {if (ShowDanMuCount > DanMuTextList.Count){for (int i = DanMuTextList.Count; i < ShowDanMuCount; i++){GameObject go = GameObject.Instantiate(DanMuMod.gameObject);go.transform.SetParent(DanMuMod.transform.parent);go.transform.localScale = Vector3.one;go.transform.localEulerAngles = Vector3.zero;DanMuTextList.Add(go.GetComponent<DanMuText>());}}elsefor (int i = ShowDanMuCount; i < DanMuTextList.Count; i++){DanMuTextList[i].gameObject.SetActive(false);}SetDanMuMove(true);}//开始移动,让各个弹幕间隔几秒IEnumerator StartMove(){for (int i = 0; i < DanMuTextList.Count; i++){if (!DanMuTextList[i].gameObject.activeSelf)DanMuTextList[i].gameObject.SetActive(true);DanMuTextList[i].StartMove();yield return new WaitForSeconds(UnityEngine.Random.Range(1, 3));}}

UI搭建及配置

UI的搭建如图:

只有简单的Image,Text;并在同名的节点上添加对应脚本。

弹幕文本脚本的配置:

节点的关联,和移动速度的设置。

弹幕管理脚本的配置:

弹幕内容列表编制,设置弹幕条数。

源码地址

打不开的话,是未审核通过。

/download/qq_33789001/85292155

其它问题

如果弹幕有范围限制,将DanMuMgr节点新增Mask组件,不显示图片的内容要取消Show Mask Graphic 选项:

弹幕区域不影响其它UI节点或者场景的操作需要取消Image组件的Raycast Target:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。