51 lines
1.6 KiB
C#
51 lines
1.6 KiB
C#
using DG.Tweening;
|
|
using UnityEngine;
|
|
using UnityEngine.EventSystems;
|
|
|
|
/// <summary>
|
|
/// 按下缩小、抬起还原。
|
|
/// 只实现 IPointerDownHandler / IPointerUpHandler,不实现 IDragHandler 等拖动接口,
|
|
/// 所以挂在 ScrollRect 内的按钮上不会抢走 ScrollRect 的滑动。
|
|
/// </summary>
|
|
public class UIPressScale : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
|
|
{
|
|
[Tooltip("缩放目标,留空则缩放自身")]
|
|
public Transform target;
|
|
public float pressScale = 0.95f; // 按下时缩放比例
|
|
public float duration = 0.1f; // 缩放动画时长
|
|
|
|
private Vector3 _standardScale;
|
|
private bool _captured;
|
|
private bool _isPressing;
|
|
|
|
private Transform Target => target != null ? target : transform;
|
|
|
|
public void OnPointerDown(PointerEventData eventData) => SetPressing(true);
|
|
public void OnPointerUp(PointerEventData eventData) => SetPressing(false);
|
|
|
|
private void SetPressing(bool pressing)
|
|
{
|
|
if (_isPressing == pressing) return;
|
|
_isPressing = pressing;
|
|
|
|
var t = Target;
|
|
if (!_captured)
|
|
{
|
|
_standardScale = t.localScale; // 首次使用时记录原缩放
|
|
_captured = true;
|
|
}
|
|
t.DOKill();
|
|
t.DOScale(pressing ? _standardScale * pressScale : _standardScale, duration)
|
|
.SetEase(Ease.OutQuad);
|
|
}
|
|
|
|
// 被隐藏时立即还原,避免按下瞬间目标被关掉而停在缩小状态
|
|
private void OnDisable()
|
|
{
|
|
_isPressing = false;
|
|
if (!_captured) return;
|
|
Target.DOKill();
|
|
Target.localScale = _standardScale;
|
|
}
|
|
}
|