本文主要是介绍Unity 跑马灯抽奖 DOTween实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Item代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
using Unity.VisualScripting;public class RotateCells : MonoBehaviour
{[SerializeField]private int _id;[HideInInspector]public Image _selObj;private void Awake(){_selObj = this.transform.GetChild(0).GetComponent<Image>();}/// <summary>/// 选中/// </summary>/// <param name="ontime"></param>/// <param name="offtime"></param>public void selON(float ontime, float offtime){_selObj.DOFade(1, ontime).OnComplete(()=>selOff(offtime)); // 渐显再渐隐}/// <summary>/// 渐隐/// </summary>/// <param name="time"></param>public void selOff(float time){_selObj.DOFade(0, time); // 渐隐}}
抽奖代码
using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;/// <summary>
/// 跑马灯抽奖
/// </summary>
public class RotateController : MonoBehaviour
{[SerializeField]private List<RotateCells> cells = new List<RotateCells>();[Header("渐显时间")]public float onTime = 0.5f;[Header("渐隐时间")]public float offTime = 0.2f;[Header("转盘时间")]public float animTime = 5f;[Header("先转几圈再抽奖")]public int laps = 3;private int _index; // 抽奖的结果private int _selIndex = 0; // 当前选中Itemprivate int cellsCount;private void Awake(){DG.Tweening.DOTween.SetTweensCapacity(tweenersCapacity: 800, sequencesCapacity: 200);// 应该在这里获取抽奖列表cellsCount = cells.Count;}public int SelIndex{get { return _selIndex; }set{cells[value % cellsCount].selON(onTime, offTime); // Index 选中时点亮Item_selIndex = value % cellsCount;}}/// <summary>/// 开始抽奖/// </summary>public void Rotate(){_selIndex = 0;_index = Random.Range(0, cells.Count); // 抽奖的结果Debug.Log($"抽中的index是{_index}"); // => 抽出index的时候就要保存结果.// 先转{laps}圈,再转到选中的index, 再结算 => int endNum = cellsCount * laps + _index;DOTween.To(()=>SelIndex, x => SelIndex = x, endNum, animTime).SetEase(Ease.InOutQuad).OnComplete(()=>FinishAnim());}public void FinishAnim(){Debug.Log("抽奖动画结束,更新UI");RotateCells selCell = cells[_index];Sequence sequence = DOTween.Sequence();sequence.AppendInterval(onTime + offTime); // 等转盘动画播完sequence.Append(selCell._selObj.DOFade(1, 0.2f));sequence.Append(selCell._selObj.DOFade(0, 0.2f));sequence.Append(selCell._selObj.DOFade(1, 0.2f));sequence.Append(selCell._selObj.DOFade(0, 0.2f));sequence.Append(selCell._selObj.DOFade(1, 0.2f));sequence.Append(selCell._selObj.DOFade(0, 0.2f));}}
应该抽奖时禁用按钮的,动画结束再恢复,测试就没加.
这篇关于Unity 跑马灯抽奖 DOTween实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!