DanmakuManager.cs
1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System.Collections;
public class DanmakuManager : MonoBehaviour
{
public RectTransform danmakuPanel; // 弹幕pannel
public GameObject danmakuPrefab;
public float speed = 100f; // px/sec
public int maxLines = 5; // 最多几行
private int currentLine = 0;
public void AddDanmaku(string text)
{
StartCoroutine(SpawnDanmaku(text));
}
IEnumerator SpawnDanmaku(string text)
{
// 实例化
GameObject obj = Instantiate(danmakuPrefab, danmakuPanel);
var tmp = obj.GetComponent<TextMeshProUGUI>();
tmp.text = text;
// 初始位置在屏幕右侧外面
RectTransform rt = obj.GetComponent<RectTransform>();
float panelHeight = danmakuPanel.rect.height;
float lineHeight = panelHeight / maxLines;
//起始位置
float y = -(panelHeight / 2);
y+= lineHeight * (currentLine % maxLines);
currentLine++;
rt.anchoredPosition = new Vector2(danmakuPanel.rect.width, y);
float width = tmp.preferredWidth;
// 移动
while (rt.anchoredPosition.x > -width)
{
rt.anchoredPosition += Vector2.left * speed * Time.deltaTime;
yield return null;
}
Destroy(obj);
}
}