Created
August 17, 2017 10:25
-
-
Save KickStudio/60954baa061ed2b7a2b18ea2953f6d8b to your computer and use it in GitHub Desktop.
Unity C# click and longPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
using UnityEngine.Events; | |
using UnityEngine.EventSystems; | |
public class uGuiScript : MonoBehaviour, IPointerDownHandler, IPointerUpHandler { | |
public UnityEvent onLongPress = new UnityEvent(); | |
public UnityEvent onClick = new UnityEvent(); | |
[SerializeField] | |
private float longPressed; | |
[SerializeField] | |
private float diff; | |
private bool flgLongPressed = false; | |
private float timeElasped; | |
private Vector3 startPos; | |
private Vector3 nowPos; | |
private Vector3 endPos; | |
public bool pressed { | |
get; | |
private set; | |
} | |
void Update() { | |
nowPos = Input.mousePosition; | |
if(pressed) { | |
timeElasped += Time.deltaTime; | |
} | |
if (Mathf.Abs(startPos.x - nowPos.x) >= diff || Mathf.Abs(startPos.y - nowPos.y) >= diff) { | |
InitCount(); | |
return; | |
} | |
if (longPressed < timeElasped && pressed == true) { | |
flgLongPressed = true; | |
onLongPress.Invoke(); | |
InitCount(); | |
} | |
} | |
public void OnPointerDown(PointerEventData eventData) { | |
startPos = eventData.position; | |
pressed = true; | |
} | |
public void OnPointerUp(PointerEventData eventData) { | |
endPos = eventData.position; | |
if(Mathf.Abs(startPos.x - endPos.x) >= diff || Mathf.Abs(startPos.y - endPos.y) >= diff) { | |
return; | |
} | |
if (flgLongPressed) { | |
flgLongPressed = false; | |
}else { | |
onClick.Invoke(); | |
} | |
InitCount(); | |
} | |
private void InitCount() { | |
pressed = false; | |
timeElasped = 0f; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment