Unity 3D Game Engine – Android – Get Finger Position – JS

Get Vector2 Finger Position in all Touch Phases.

1. Hiearchy> GUI Text

2. Hierarchy> Main Camera, attach ‘PositionDetector.js’

PositionDetector.js


#pragma strict

// Get Finger Position and write XY Vector2 values as: (23.0,24.9)  
// Attach this script to Main Camera
// Author: Andrea Tonin
// Web Site: www.blog.lucedigitale.com

var FingerPosText  : GUIText;  // to display position of finger, Hierarchy DRAG E DROP over var GUI Text in Inspector
var FingerPos: Vector2;        // finger position 

function Update() {

    if (Input.touchCount > 0) {
    
        var touch = Input.GetTouch(0);

        // scrive Input.GetTouch(0).phase == TouchPhase.Began
        switch (touch.phase) { 
            case TouchPhase.Began:
                // quando il tocco inizia rilevo la posizione del tocco              
                FingerPos = touch.position;
                // scrive la posizione in pixel X e Y del tocco es: (23.0,24.9) 
				FingerPosText.text = "Position: " + FingerPos;			    
                break;

            case TouchPhase.Moved:
                // quando il dito sta strisciando 
                FingerPos = touch.position;
                FingerPosText.text = "Position: " + FingerPos;
                break;

            case TouchPhase.Stationary:
                // se il dito è stazionario 
                FingerPos = touch.position;
                FingerPosText.text = "Position: " + FingerPos;
                break;

            case TouchPhase.Ended:
                // quando sollevo il dito 
                FingerPos = touch.position;
                FingerPosText.text = "Position: " + FingerPos;
                break;
        }
    }
}

Hierarchy> Main Camera> Inspector> PositionDetector.js, assign GUI Text