DanmakuManager.cs 1.31 KB
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);
    }
}