鸟语天空
UGUI—文字弹跳效果
post by:追风剑情 2021-10-21 11:14

示例:文字弹跳效果

工程截图

222222.png

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 文字弹跳效果
/// </summary>
public class UITextWaveEffect : MonoBehaviour
{
    [SerializeField]
    private List<RectTransform> childs = new List<RectTransform>();
    private List<UIWaveEffect> effects = new List<UIWaveEffect>();
    [SerializeField]
    private float delayPlay = 0.2f;
    [SerializeField]
    private float delayCycle = 0.2f;
    [SerializeField]
    private float speed = 10;
    [SerializeField]
    private float amplitude = 10; //幅度
    private float t;

    void Awake()
    {
        for (int i=0; i< childs.Count; i++)
        {
            UIWaveEffect effect = new UIWaveEffect();
            effect.rectTransform = childs[i];
            effect.delayPlay = i * delayPlay;
            effect.speed = speed;
            effect.amplitude = amplitude;
            effects.Add(effect);
        }
    }

    public void Reset()
    {
        for (int i = 0; i < effects.Count; i++)
        {
            var effect = effects[i];
            effect.Reset();
        }
        t = 0;
    }

    private void OnEnable()
    {
        Reset();
    }

    void Update()
    {
        for (int i=0; i< effects.Count; i++)
        {
            var effect = effects[i];
            effect.Update();
        }

        //最后一个对象弹跳完成后,延迟一定时间再重置播放
        if (effects[effects.Count - 1].IsPause)
        {
            t += Time.deltaTime;
            if (t >= delayCycle)
            {
                Reset();
            }
        }
    }

    public class UIWaveEffect
    {
        public RectTransform rectTransform;
        public float delayPlay;
        public float speed;
        public float amplitude;
        private float t0,t1;
        private bool pause;

        public float Y
        {
            get
            {
                Vector2 pos = rectTransform.anchoredPosition;
                return pos.y;
            }
            set
            {
                Vector2 pos = rectTransform.anchoredPosition;
                pos.y = value;
                rectTransform.anchoredPosition = pos;
            }
        }

        public bool IsPause
        {
            get { return pause; }
        }

        public void Reset()
        {
            t0 = 0;
            t1 = 0;
            Y = 0;
            pause = false;
        }

        public void Update()
        {
            if (pause)
                return;
            //延迟播放
            if (t0 < delayPlay)
            {
                t0 += Time.deltaTime;
                return;
            }
            t1 += Time.deltaTime * speed;
            Y = Mathf.Lerp(0, amplitude, Mathf.Sin(t1));
            //播放一次弹跳后暂停
            if (t1 >= Mathf.PI)
                pause = true;
        }
    }
}

运行效果

11115.gif

评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容