Adventure Creator Wikia
Advertisement

This script allows you to run events when pinching or spreading two fingers on mobile devices beyond a set distance. When testing in the Editor, such input can be simulated by moving the mouse vertically while holding the middle-mouse button.

To use it:

  1. Create a new C# file named PinchInput and paste in the code below.
  2. Attach the new Pinch Input component to an object in the scene, and fill in its Inspector.
  3. To have ActionLists run when the events fire, invoke their Interact functions.

PinchInput.cs:

#if (UNITY_IOS || UNITY_ANDROID) && !UNITY_EDITOR
#define MOBILE_INPUT
#endif
using UnityEngine;
using UnityEngine.Events;

namespace AC
{

	public class PinchInput : MonoBehaviour
	{

		[SerializeField] private float pinchThreshold = 0.6f;
		[SerializeField] private bool eventsOnRelease = true;
		[SerializeField] private GameState reactDuringGameState;
		[SerializeField] private UnityEvent onPinch;
		[SerializeField] private UnityEvent onSpread;
		public bool IsPinching { get; private set; }
		public float RelativePinchDistance { get; private set; }
		private float startPinchDistance;

		private void LateUpdate ()
		{
			if (KickStarter.stateHandler.gameState != reactDuringGameState)
			{
				IsPinching = false;
				return;
			}

			if (Input_StartPinch)
			{
				IsPinching = true;
				startPinchDistance = Input_PinchDistance;
			}
			
			if (IsPinching)
			{
				if (Input_EndPinch)
				{
					IsPinching = false;
				}
				else
				{
					float pinchDistance = (Input_PinchDistance - startPinchDistance) / Screen.dpi;
					RelativePinchDistance = pinchDistance / pinchThreshold;
				}

				if ((IsPinching && !eventsOnRelease) || (!IsPinching && eventsOnRelease))
				{
					if (RelativePinchDistance >= 1f)
					{
						// Spread
						onSpread.Invoke ();
						IsPinching = false;
					}
					else if (RelativePinchDistance <= -1f)
					{
						// Pinch
						onPinch.Invoke ();
						IsPinching = false;
					}
				}
			}
		}


		private float Input_PinchDistance
		{
			get
			{
				#if MOBILE_INPUT
				return (Input.GetTouch (0).position - Input.GetTouch (1).position).magnitude;
				#else
				return Input.mousePosition.y;
				#endif
			}
		}


		private bool Input_StartPinch
		{
			get
			{
				if (IsPinching) return false;

				#if MOBILE_INPUT
				return Input.touchCount == 2 && Input.GetTouch (1).phase == TouchPhase.Began;
				#else
				return Input.GetMouseButtonDown (2);
				#endif
			}
		}


		private bool Input_EndPinch
		{
			get
			{
				if (!IsPinching) return false;
				
				#if MOBILE_INPUT
				return (Input.touchCount != 2);
				#else
				return !Input.GetMouseButton (2);
				#endif
			}
		}

	}

}
Advertisement