工程截图
QRScanLine.cs
using UnityEngine; using UnityEngine.UI; /// <summary> /// QR扫描线 /// </summary> public class QRScanLine : MonoBehaviour { [SerializeField] private RectTransform m_rectTransform; [SerializeField] private Image m_line; [SerializeField] private float m_speed = 10;//扫描速度 [SerializeField] private float m_interval = 0.5f;//扫描间隔时间 private float m_lineHeight; private float m_parentHeight; private float m_parentHeightQrt1;//四分之一 private float m_parentHeightQrt3;//四分之三 private float m_currentY = 0; private float m_pauseTime = 0; private bool m_pause = false; private void Awake() { if (m_rectTransform == null) m_rectTransform = this.GetComponent<RectTransform>(); if (m_line == null) m_line = this.GetComponent<Image>(); m_lineHeight = m_rectTransform.rect.height; RectTransform parentRT = transform.parent.GetComponent<RectTransform>(); m_parentHeight = parentRT.rect.height; m_parentHeightQrt1 = m_parentHeight / 4; m_parentHeightQrt3 = m_parentHeightQrt1 * 3; } void Update() { if (m_pause) { m_pauseTime += Time.deltaTime; if (m_pauseTime >= m_interval) m_pause = false; return; } m_currentY += m_speed * Time.deltaTime; if (m_currentY > m_parentHeight + m_lineHeight) { m_pause = true; m_pauseTime = 0; m_currentY = -m_lineHeight; } float y = -m_currentY; float alpha = CalculateAlpha(); SetYAlpha(y, alpha); } private void OnEnable() { m_currentY = -m_lineHeight; m_pauseTime = 0; m_pause = false; } //计算alpha private float CalculateAlpha() { float t = 0; if (m_currentY <= m_parentHeightQrt1) { t = m_currentY / m_parentHeightQrt1; } else if (m_currentY >= m_parentHeightQrt3) { t = (m_parentHeight + m_lineHeight - m_currentY) / m_parentHeightQrt1; } else { t = 1; } float alpha = Mathf.LerpUnclamped(0, 1, t); return alpha; } private void SetYAlpha(float y, float alpha) { m_rectTransform.anchoredPosition = new Vector2(0, y); Color color = m_line.color; color.a = alpha; m_line.color = color; } }
运行效果