ButtonDepth.cs 1.2 KB

123456789101112131415161718
  1. using UnityEngine;
  2. using UnityEngine.EventSystems;
  3. using UnityEngine.UI;
  4. namespace DiamondArrow
  5. {
  6. // Move the face within its stable hit area, so a press never moves the touch target.
  7. public sealed class ButtonDepth : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
  8. {
  9. RectTransform[] faces;Vector2[] origins;float offset;bool held;
  10. void Start(){int n=transform.childCount;faces=new RectTransform[n];origins=new Vector2[n];for(int i=0;i<n;i++){faces[i]=transform.GetChild(i) as RectTransform;if(faces[i])origins[i]=faces[i].anchoredPosition;}}
  11. void Update(){if(faces==null)return;offset=Mathf.Lerp(offset,held?2.5f:0,1-Mathf.Exp(-Time.unscaledDeltaTime*30));for(int i=0;i<faces.Length;i++)if(faces[i])faces[i].anchoredPosition=origins[i]+Vector2.down*offset;}
  12. public void OnPointerDown(PointerEventData e){held=GetComponent<Button>().IsInteractable();}
  13. public void OnPointerUp(PointerEventData e){held=false;}
  14. public void OnPointerExit(PointerEventData e){held=false;}
  15. void OnDisable(){held=false;offset=0;if(faces!=null)for(int i=0;i<faces.Length;i++)if(faces[i])faces[i].anchoredPosition=origins[i];}
  16. }
  17. }