Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.UI;
- using System.Collections;
- [RequireComponent (typeof (Image))]
- public class TouchButtonBehaviour : MonoBehaviour {
- [HideInInspector]
- public bool output; //Boolean output
- public bool normalize = false; //ButtonUp () if input position is outside graphics
- private RectTransform button; //Button transform
- private int latchedFinger = -1; //Latched finger to avoid other fingers to steal button
- private float distanceX = 0;
- private float distanceY = 0;
- private float canvasScale;
- void Start () {
- // Cache this component at startup instead of looking up every frame
- button = GetComponent <RectTransform> ();
- //Get canvas scale
- canvasScale = GetComponentInParent <Canvas> ().scaleFactor;
- }
- void ButtonDown () {
- output = true;
- }
- void ButtonUp () {
- output = false;
- latchedFinger = -1;
- }
- void Update () {
- //Graphics size /2 to calculate distance between input position and graphics position
- float sizeX = button.sizeDelta.x/2 * canvasScale;
- float sizeY = button.sizeDelta.y/2 * canvasScale;
- #if UNITY_EDITOR
- //Distance between button graphics and mouse position
- distanceX = button.position.x - Input.mousePosition.x;
- distanceY = button.position.y - Input.mousePosition.y;
- //Calculate if mouse position is inside button graphics
- bool containsMousePosition = distanceX >= -sizeX &&
- distanceX <= sizeX &&
- distanceY >= -sizeY &&
- distanceY <= sizeY ;
- //Allow click if it's inside button graphics
- if (Input.GetMouseButtonDown (0) && containsMousePosition)
- ButtonDown ();
- if (!containsMousePosition && output == true && normalize)
- ButtonUp ();
- // Reset button if click ended
- if (Input.GetMouseButtonUp (0))
- ButtonUp ();
- #else
- foreach (Touch touch in Input.touches){
- //Distance between button graphics snd touch position
- distanceX = button.position.x - touch.position.x;
- distanceY = button.position.y - touch.position.y;
- //Calculate if touch position is inside button graphics
- bool containsTouchPosition = distanceX >= -sizeX &&
- distanceX <= sizeX &&
- distanceY >= -sizeY &&
- distanceY <= sizeY ;
- //Allow click if it's inside button graphics & get latched finger id
- if (containsTouchPosition && touch.phase == TouchPhase.Began){
- latchedFinger = touch.fingerId;
- ButtonDown ();
- }
- if (!containsTouchPosition && output == true && normalize && touch.fingerId == latchedFinger)
- ButtonUp ();
- // Reset button if touch ended
- if (touch.fingerId == latchedFinger && (touch.phase == TouchPhase.Ended || touch.phase == TouchPhase.Canceled))
- ButtonUp ();
- }
- #endif
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement