Maxime FRAPPAT

Hum …no thanks ! – Lordinaire

Tag: iOS

[Unity][iOS/WP8/Android] Slide gesture helper

In this post, we will see how to detect a slide gesture in 2D mobile games.

Slide gesture description

In our example, a slide can be in four directions : left, right, bottom and top.

using Assets.Scripts.Framework;

namespace Assets.Scripts.Gestures
{
    public enum GestureType
    {
        Left,
        Top,
        Right,
        Bottom,
        Unknow
    }
}

We define a minimum distance and a ratio between vertical and horizontal distance to make the gesture completely.

left-slide-gesture

Gesture manager

using Assets.Scripts.Framework;
using Assets.Scripts.Gestures;
using UnityEngine;

namespace Assets.Scripts.Managers
{
    public enum HandlePatternResponseType
    {
        None,
        Error,
        Waiting,
        Ok
    }

    public class GestureManager : MonoBehaviour
    {
        public float MinDistanceForHorizontalSlide = 200;
        public float MinDistanceForVerticalSlide = 300;
        public float HorizontalRatio = 5;
        public float VerticalRatio = 5;

        private Vector3 _startPosition;
        private Vector3 _endPosition;

        private bool _hasStartPosition;

        /// <summary>
        /// Handle slide gesture
        /// </summary>
        public HandlePatternResponseType HandleSlideGesture(GestureType gestureType)
        {
            var result = HandlePatternResponseType.Waiting;

			// The finger is down
            if (Input.touchCount == 1)
            {
				// Save start position
                if (!_hasStartPosition)
                    _startPosition = TouchHelper.GetTouchedPosition();

                _endPosition = TouchHelper.GetTouchedPosition();
                _hasStartPosition = true;
            }

			// The finger is up
            if (Input.touchCount == 0 && _hasStartPosition)
            {
                _hasStartPosition = false;

                var distHorizontal = _endPosition.x - _startPosition.x;
                var distVertical = _endPosition.y - _startPosition.y;

                switch (gestureType)
                {
                    case GestureType.Left:
                        if ((distHorizontal * -1) < MinDistanceForHorizontalSlide
                            || (distHorizontal * -1) < (Mathf.Abs(distVertical) * HorizontalRatio))
                            result = HandlePatternResponseType.Error;
                        else
                            result = HandlePatternResponseType.Ok;
                        break;

                    case GestureType.Right:
                        if (distHorizontal < MinDistanceForHorizontalSlide
                            || distHorizontal < (Mathf.Abs(distVertical) * HorizontalRatio))
                            result = HandlePatternResponseType.Error;
                        else
                            result = HandlePatternResponseType.Ok;
                        break;

                    case GestureType.Top:
                        if (distVertical < MinDistanceForVerticalSlide
                            || distVertical < (Mathf.Abs(distHorizontal) * VerticalRatio))
                            result = HandlePatternResponseType.Error;
                        else
                            result = HandlePatternResponseType.Ok;
                        break;

                    case GestureType.Bottom:
                        if ((distVertical * -1) < MinDistanceForVerticalSlide
                            || (distVertical * -1) < (Mathf.Abs(distHorizontal) * VerticalRatio))
                            result = HandlePatternResponseType.Error;
                        else
                            result = HandlePatternResponseType.Ok;
                        break;

                    default:
						result = HandlePatternResponseType.None;
                        break;
                }
            }

            return result;
        }

    }
}

Example

  1. Create an empty game object and add it in the scene
  2. Create a new script : GameManager.cs
  3. Add this script in the new game object
public class GameManager : MonoBehaviour
{
	private GestureManager _gestureManager;

	public void Start()
	{
		_gestureManager = GetComponent<GestureManager>();
		if (_gestureManager == null)
		{
			_gestureManager = gameObject.AddComponent<GestureManager>();
		}
	}

	public void Update()
	{
		var result = _gestureManager.HandleSlideGesture(GestureType.Left);
		if (result == HandlePatternResponseType.Ok)
		{
			Debug.Log("[GESTURE] Left slide detected");
		}
		else if (result == HandlePatternResponseType.Error)
		{
			Debug.Log("[GESTURE] Bad gesture detected");
		}
	}
}

Have fun ! :)

[Unity][iOS/WP8/Android] Tap gesture helper

An helper class to handle single tap gesture in 2D games. It uses the raycast mechanism to detect collisions.

using UnityEngine;

namespace Assets.Scripts.Framework
{
	public static class TapHelper
	{
		/// <summary>
		/// Get touch position
		/// </summary>
		/// <returns>Current touch position</returns>
		public static Vector3 GetTouchedPosition()
		{
			Input.simulateMouseWithTouches = true;
			if (Input.touchCount > 0 || Input.GetMouseButtonDown(0))
			{
#if UNITY_EDITOR
                return Input.mousePosition;
#else
				return Input.touches[0].position;

#endif
			}
			return Vector3.zero;
		}

		/// <summary>
		/// Return if a game object is touch
		/// </summary>
		/// <param name="name">game object name</param>
		/// <returns>true if touched, otherwise false</returns>
		public static bool IsGameObjectTouched(string name)
		{
			Input.simulateMouseWithTouches = true;
			if (Input.touchCount > 0 || Input.GetMouseButtonDown(0))
			{
#if UNITY_EDITOR
                var hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, 1f);
#else
				var hit = Physics2D.Raycast(Camera.main.ScreenPointToRay(Input.touches[0].position).origin, Vector2.zero, 1f);
#endif

				if (hit.collider != null)
				{
					return hit.collider.name == name;
				}
			}

			return false;
		}

		/// <summary>
		/// Return if a game object is touched
		/// </summary>
		/// <param name="objectToDetect">instance of a game object</param>
		/// <returns>true if touched, otherwise false</returns>
		public static bool IsGameObjectTouched(GameObject objectToDetect)
		{
			Input.simulateMouseWithTouches = true;
			if (Input.touchCount > 0 || Input.GetMouseButtonDown(0))
			{
#if UNITY_EDITOR
                var hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, 1f);
#else
				var hit = Physics2D.Raycast(Camera.main.ScreenPointToRay(Input.touches[0].position).origin, Vector2.zero, 1f);
#endif

				if (hit.collider != null)
				{
					return hit.collider.gameObject == objectToDetect;
				}
			}

			return false;
		}
	}
}

Powered by WordPress & Theme by Anders Norén

%d bloggers like this: