Malcolm Tanti Malcolm Tanti - 25 days ago 6
Android Question

Unity Android Touch Controls Not Working - 2D

I have this script which i created to detect UP and DOWN swipes. All it needs to do is change the UI text..

The script is below:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class TouchControls : MonoBehaviour
{
private Vector2 startPos;

Text instruction;

void start() {
instruction = GetComponent<Text>();
}

float swipeValue = 0.0f;
void Update()
{
#if UNITY_ANDROID
if (Input.touchCount > 0){
Touch touch = Input.touches[0];
if(touch.phase == TouchPhase.Began){
startPos = touch.position;
}
else if(touch.phase == TouchPhase.Ended){

swipeValue = Mathf.Sign(touch.position.y - startPos.y);

if (swipeValue > 0){//up swipe

instruction.text="UP";
}
else if (swipeValue < 0){//down swipe

instruction.text="DOWN";
}
}
}
#endif
}
}


It is not working and I cannot understand why? Any help please?

Answer

This is the solution to the problem I had managed on Unity version 5.1.1

void Update () {

        #if UNITY_IOS || UNITY_ANDROID
        //iOS Controls (same as Android because they both deal with screen touches)
        //if the touch count on the screen is higher than 0, then we allow stuff to happen to control the player.

                if(Input.touchCount > 0){
                    foreach(Touch touch1 in Input.touches) {
                        if (touch1.phase == TouchPhase.Began) {
                            firstPosition = touch1.position;
                            lastPosition = touch1.position;
                        }
                        if (touch1.phase == TouchPhase.Moved) {
                            lastPosition = touch1.position;
                        }
                        if (touch1.phase == TouchPhase.Ended) {             

                            if (firstPosition.y - lastPosition.y < -80) {
                                //Up
                            }  else {
                                //Down
                            }

                        }   

                    }

            #endif