Unity滑鼠懸停實現圖片的浮動效果
阿新 • • 發佈:2019-02-15
[RequireComponent(typeof(LayoutElement))]
public class EventTriggerListener : EventTrigger
{
public delegate void VoidDelegate(GameObject obj);
//點選
public VoidDelegate onClick;
//滑鼠按下
public VoidDelegate onDown;
//滑鼠擡起
public VoidDelegate onUp;
//滑鼠移入
public VoidDelegate onEnter;
//滑鼠移出
public VoidDelegate onExit;
private Vector2 currentSize;
private Vector2 targetSize;
private float speed = 4.0f;
public static EventTriggerListener GetComponent(GameObject obj)
{
EventTriggerListener listener = obj.GetComponent<EventTriggerListener>();
if (listener == null)
{
listener = obj.AddComponent<EventTriggerListener>();
}
return listener;
}
public override void OnPointerClick(PointerEventData eventData)
{
if (onClick != null)
{
onClick(gameObject);
}
}
public override void OnPointerDown(PointerEventData eventData)
{
if (onDown != null) onDown(gameObject);
}
public override void OnPointerUp(PointerEventData eventData)
{
if (onUp != null) onUp(gameObject);
}
public override void OnPointerEnter(PointerEventData eventData)
{
if (onEnter != null) onEnter(gameObject);
}
public override void OnPointerExit(PointerEventData eventData)
{
if (onExit != null) onExit(gameObject);
}
private void Start()
{
targetSize = currentSize = new Vector2(this.GetComponent<LayoutElement>().preferredWidth, this.GetComponent<LayoutElement>().preferredHeight);
}
private void Update()
{
if (currentSize != targetSize)
{
currentSize = Vector2.Lerp(currentSize, targetSize, Time.deltaTime * speed);
if (Vector2.Distance(currentSize, targetSize) <= 0.01)
{
currentSize = targetSize;
}
this.GetComponent<LayoutElement>().preferredWidth = currentSize.x;
this.GetComponent<LayoutElement>().preferredHeight = currentSize.y;
}
}
public void UpdateSize(Vector2 size,float speed)
{
this.targetSize = size;
this.speed = speed;
}
}