Unity3D制作LED滚动字幕(跑马灯)效果

搭建场景

建立世界坐标的Canvas

在这里插入图片描述

新建LED模型

直接新建Cube,并将其缩放拖成条状,旋转按自己场景中的位置调整。
在这里插入图片描述

Text节点

Text节点建好后,新建一个空节点命名Content,并将Text设为Content的子节点,滚动效果直接移动Content。Text颜色设置红色:

在这里插入图片描述

Mask节点

超出模型范围的文字需要隐藏,所以新建image节点,然后新增mask组件,并将改节点移动到模型需要显示文字的一面,并将大小设置为与模型边界匹配。将Content设为其子节点。
在这里插入图片描述

查看效果

左右拖动Content节点,查看效果。
在这里插入图片描述

相对不好看

美化一下

上网找一张LED的图片,下载后,新建image并平铺模式,放大一定比例并缩小,将大小设置为与模型边界匹配。
在这里插入图片描述

编写代码

DOTween插件

这里的移动使用的是DOTween插件,请自行购买或者下载免费版。

设置属性

控制动画的属性:

 [Tooltip("LED屏的内容")]
    public string TextStr;
    [Tooltip("是否自动开始")]
    public bool isAutoStart = true;
    [Tooltip("是否滚动")]
    public bool isRoll = true;
    [Tooltip("滚动速度")]
public float Speed = 12;

编写文字滚动动画

    /// <summary>
    /// 文字滚动动画
    /// </summary>
    void RollWords()
    {
    
    
        if (text.preferredWidth > 0 && Speed > 0)
        {
    
    
            transform.GetComponent<RectTransform>().sizeDelta = new Vector2(text.preferredWidth, transform.GetComponent<RectTransform>().sizeDelta.y);
            transform.localPosition = new Vector3((Parent.sizeDelta.x + text.preferredWidth) / 2, 0, 0);
            float PosX = -(Parent.sizeDelta.x + text.preferredWidth) / 2;
            RollTw = transform.DOLocalMoveX(PosX, text.preferredWidth / Speed).SetId("WordsRoll").
                SetEase(Ease.Linear).OnComplete(() => {
    
     RollWords(); });
        }
        else
            Debug.LogWarning("内容长度或速度设置有问题!");
    }

text.preferredWidth获取文字的长度,SetId设置ID方便后面控制动画,OnComplete循环动画

一些控制接口

 /// <summary>
    /// 暂停动画
    /// </summary>
    public void Pause() {
    
    
        if (RollTw != null && RollTw.IsPlaying())
            DOTween.Pause("WordsRoll");
        else
            Debug.LogWarning("无动画或无动画在执行,无法暂停!");
    }

    /// <summary>
    /// 恢复动画
    /// </summary>
    public void Resume() {
    
    
        if (RollTw != null && !RollTw.IsPlaying())
            DOTween.Play("WordsRoll");
        else
            Debug.LogWarning("无动画或动画已在执行,无法恢复!");
    }

    /// <summary>
    /// 停止动画
    /// </summary>
    public void Stop() {
    
    
        if (RollTw != null && RollTw.IsPlaying())
        {
    
    
            DOTween.Kill("WordsRoll");
            RollTw = null;
            transform.localPosition = new Vector3((Parent.sizeDelta.x + text.preferredWidth) / 2, 0, 0);
        }
        else
            Debug.LogWarning("无动画或无动画在执行,无法停止!");
    }

测试脚本


    private void Update()
    {
    
    
        if (Input.GetKeyUp(KeyCode.P))
            Play();
        if (Input.GetKeyUp(KeyCode.O))
            SetText("新的文案测试哦!");
        if (Input.GetKeyUp(KeyCode.S))
            Stop();
        if (Input.GetKeyUp(KeyCode.Q))
            Pause();
        if (Input.GetKeyUp(KeyCode.R))
            Resume();
    }

最终效果

在这里插入图片描述

项目地址

https://download.csdn.net/download/qq_33789001/14374304

猜你喜欢

转载自blog.csdn.net/qq_33789001/article/details/112678275