Showing posts with label Unity. Show all posts
Showing posts with label Unity. Show all posts

Sunday, 30 March 2014

Unity Tips: Swipe controls for Android and iOS

I've been doing a bit of work in Unity lately, putting together a basic Android game to teach myself the basics. I wanted to use swipe controls to move the player, and I think I've come up with a pretty nice template I thought I'd share with any other beginners out there. It's based on this script by Sushanta Chakraborty, but I've made it a bit more powerful and responsive. A brief explanation is below for those still learning C#.

using UnityEngine;
using System.Collections;

public class SwipeControl : MonoBehaviour
{
    //First establish some variables
    private Vector3 fp; //First finger position
    private Vector3 lp; //Last finger position
    public float dragDistance;  //Distance needed for a swipe to register

    // Update is called once per frame
    void Update()
    {
        //Examine the touch inputs
        foreach (Touch touch in Input.touches)
        {
            if (touch.phase == TouchPhase.Began)
            {
                fp = touch.position;
                lp = touch.position;
            }
            if (touch.phase == TouchPhase.Moved)
            {
                lp = touch.position;
            }
            if (touch.phase == TouchPhase.Ended)
            {
                //First check if it's actually a drag
                if (Mathf.Abs(lp.x - fp.x) > dragDistance || Mathf.Abs(lp.y - fp.y) > dragDistance)
                {   //It's a drag
                    //Now check what direction the drag was
                    //First check which axis
                    if (Mathf.Abs(lp.x - fp.x) > Mathf.Abs(lp.y - fp.y))
                    {   //If the horizontal movement is greater than the vertical movement...
                        if (lp.x>fp.x)  //If the movement was to the right
                        {   //Right move
                            //MOVE RIGHT CODE HERE
                        }
                        else
                        {   //Left move
                            //MOVE LEFT CODE HERE
                        }
                    }
                    else
                    {   //the vertical movement is greater than the horizontal movement
                        if (lp.y>fp.y)  //If the movement was up
                        {   //Up move
                            //MOVE UP CODE HERE
                        }
                        else
                        {   //Down move
                            //MOVE DOWN CODE HERE
                        }
                    }
                }
                else
                {   //It's a tap
                    //TAP CODE HERE
                }

            }
        }
}

Ok, so what's happening here?