Unity 3D Game Engine – Long Touch – Counter Increase Decrease

Unity 3D Game Engine – Long Touch – Counter Increase Decrease

The counter will increase if you tap or long touch the device
The counter will decrease if you do not touch the device

1. Inside the Hierarchy create the structure:

– Main Camera
– GUI Text
– GameController (Empty Object), attach the ‘TouchController.js’

TouchController.js:


#pragma strict

// Hierarchy DRAG E DROP over var GUI Text in Inspector
var scoreText : GUIText;
// touch counter, private because the users is not be able to change this value
private  var score : int;

function Start () {
        // The counter initial value is 0
        score = 0;
        scoreText.text = "No Touch:";
}

function Update() {

    // upper and lower limit for score
    LimitScore ();

    if (Input.touchCount == 1) {
        // var score will increase if you tap or long touch the device
        UpdateScore ();
    }
    
    // every frame score will decrease
    DecreaseScore ();
}

function UpdateScore () {
    // score var increment of +10
    // NOTICE!!!! UpdateScore() DEVE essere più veloce di DecreaseScore() altrimenti non si incrementa,
    // infatti si basano sulla stessa velocità di esecuzione
    // per rallentare DecreaseScore() si potrebbe creare un ritardo di esecuzione - yield WaitForSeconds (5);
    score += 10;
    // scoreText in assigned inside Inspector on GUI Text
    // change .text property and write it on the display 
    scoreText.text = "Touched: "  + score;
}

function DecreaseScore () {
    // per rallentare DecreaseScore() si potrebbe creare un ritardo di esecuzione - yield WaitForSeconds (5);
    // score var decrement of -1
    score -= 1;
    // scoreText in assigned inside Inspector on GUI Text
    // change .text property and write it on the display 
    scoreText.text = "Touched: "  + score;
}

function LimitScore () {
    if(score < 1)    // minimum score value
    	score = 1; 
    if(score > 1000) // maximum score value, at the end it can reach 999+10=1009
    	score = 1000;
    scoreText.text = "Touched: "  + score;
}

Hierarchy> GameController> TouchController.js assign over var Score Text the GUI Text Object

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Long Touch – Counter Increase Decrease

Unity 3D Game Engine – Long Touch – Counter Increase

Unity 3D Game Engine – Long Touch – Counter Increase

The counter will increase if you tap or long touch the device

1. Inside the Hierarchy create the structure:

– Main Camera
– GUI Text
– GameController (Empty Object), attach the ‘TouchController.js’

TouchController.js:


#pragma strict

// Hierarchy DRAG E DROP over var GUI Text in Inspector
var scoreText : GUIText;
// touch counter, private because the users is not be able to change this value
private  var score : int;

function Start () {
        // The counter initial value is 0
        score = 0;
        scoreText.text = "No Touch:";
}

function Update() {
    if (Input.touchCount == 1) {
        // var score will increase if you tap or long touch the device
        UpdateScore ();
    }
}

function UpdateScore () {
    // score var increment of +1
    score += 1;
    // scoreText in assigned inside Inspector on GUI Text
    // change .text property and write it on the display 
    scoreText.text = "Touched: "  + score;
}


Hierarchy> GameController> TouchController.js assign over var Score Text the GUI Text Object

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Long Touch – Counter Increase

Unity 3D Game Engine – Android – Multi Touch – Basics

Unity 3D Game Engine – Android – Multi Touch – Basics

With this JavaScript code you can check multi touch over an Android device.

1. Create a GUI Text
2. Main Camera, attach the script ‘MultiTouchDetector.js’

MultiTouchDetector.js


#pragma strict

// Rileva il numero di tocchi che avviene contemporaneamente sul dispositivo

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

function Update () {  
    
	// If there are 1 touches on the device...
    if (Input.touchCount == 1)   
    {
    TouchesCounter.text = "Touches: 1";
	}
    
	
	// If there are 2 touches on the device...
    if (Input.touchCount == 2)  
    {
     TouchesCounter.text = "Touches: 2";
	}
     

	// If there are 3 touches on the device...
    if (Input.touchCount == 3)
    {
    TouchesCounter.text = "Touches: 3";
	}
    
    
    	// If there are 4 touches on the device...
    if (Input.touchCount == 4)  
    {
    TouchesCounter.text = "Touches: 4";
	}
    
    
    	// If there are 5 touches on the device...
    if (Input.touchCount == 5)
    {
    TouchesCounter.text = "Touches: 5";
	}
    
}

Hierarchy> Main Camera> Inspector> MultiTouchDetector.js> DRAG GUI Text over public var TouchesCounter

In this example you can check if over the display you will have 1,2,3,4 or 5 fingers.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Android – Multi Touch – Basics

Unity 3D Game Engine – Android – Multi Touch – Pich to Zoom – JavaScript

Unity 3D Game Engine – Android – Multi Touch – Pich to Zoom – JavaScript

ZommIn ZoomOut the camera using pinch gesture.

Inside Hierarchy create:

1. Cube (Gameobject)

2. Main Camera, attach the script ‘PinchZoom.js’

PinchZoom.js:


#pragma strict

// Pinch to Zoom
// Attach this script to Main Camera

public var perspectiveZoomSpeed : float = 0.5f;  // The rate of change of the field of view in perspective mode. E' la velocità con la quale si avrà lo zoom
public var orthoZoomSpeed : float = 0.5f;        // The rate of change of the orthographic size in orthographic mode.  E' la velocità con la quale si avrà lo zoom


function Update()
{
    // If there are two touches on the device...
    if (Input.touchCount == 2)
    {
        // Store both touches.
        var touchZero = Input.GetTouch(0);
        var touchOne = Input.GetTouch(1);

        // Find the position in the previous frame of each touch.
        var touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
        var touchOnePrevPos = touchOne.position - touchOne.deltaPosition;

        // Find the magnitude of the vector (the distance) between the touches in each frame.
        var prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
        var touchDeltaMag = (touchZero.position - touchOne.position).magnitude;

        // Find the difference in the distances between each frame.
        var deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;

        // If the camera is orthographic...
        if (camera.isOrthoGraphic)
        {
            // ... change the orthographic size based on the change in distance between the touches.
            camera.orthographicSize += deltaMagnitudeDiff * orthoZoomSpeed;

            // Make sure the orthographic size never drops below zero.
            camera.orthographicSize = Mathf.Max(camera.orthographicSize, 0.1f);
        }
        else
        {
            // Otherwise change the field of view based on the change in distance between the touches.
            camera.fieldOfView += deltaMagnitudeDiff * perspectiveZoomSpeed;

            // Clamp the field of view to make sure it's between 0 and 180.
            // Clam in inglese significa 'morsetto', significa limitare il valore ad un valore massimo ed un valore minimo prestabilito
            camera.fieldOfView = Mathf.Clamp(camera.fieldOfView, 0.1f, 179.9f);
        }
    }
}

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Android – Multi Touch – Pich to Zoom – JavaScript

Unity 3D Game Engine – Android – Swipe – Screen – Detection – JS

Unity 3D Game Engine – Android – Swipe – Screen – Detection – JS

How to detect swipe gesture on Android using JavaScript.

With this script you can obtain an effect as fruit ninja.

Hierarchy, create

– GUI Text Distance
– GUI Text Is Swipe
– GUI Text Start Position
– GUI Text Start Time
– GUI Text Swipe Time

– Main Camera attach the ‘SwipeDetector.js’

SwipeDetector.js


#pragma strict

// Swipe Detector
// Attach this script to Main Camera
// Author: Andrea Tonin
// Web Site: www.blog.lucedigitale.com

// Hierarchy DRAG E DROP over var GUI Text in Inspector
var StartPosText  : GUIText;  // to display start position of finger
var StartTimeText : GUIText;  // to display start time of finger
var SwipeTime  : GUIText;     // to display swipe time
var SwipeDistance : GUIText;  // to display swipe distance
var SwipeDetect : GUIText;    // to display if swipe is detect

var startTime: float;      // start time at first finger touch
var startPos: Vector2;     // start position at first finger touch
var couldBeSwipe: boolean; // NOTA BENE: Inspector> lasciarlo uncheck, il valore verrà stabilito dallo script
var minSwipeDist: float;   // da 200 in su, distanza minima che il dito deve percorrere per essere considerato uno swipe
var maxSwipeTime: float;   // da 0.5 in su, tempo massimo (in secondi) che il dito può utilizzare per percorrere la distanza minima minSwipeDist

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 e il tempo #######################
                couldBeSwipe = false;
                startPos = touch.position;
                startTime = Time.time;
                
                                    // Debug Text inizio #########################################
				    // scrive la posizione in pixel X e Y del tocco es: (23.0,24.9) 
				    StartPosText.text = "Start position: " + startPos;
				    // scrive i secondi trascorsi dall'avvio dell'app es: 61.71594
				    StartTimeText.text = "Start Time: " + startTime;
				    // Debug Text fine ###########################################
                break;

            case TouchPhase.Moved:
                // quando il dito sta strisciando non c'è swipe ##################################
                couldBeSwipe = false;
                break;

            case TouchPhase.Stationary:
                // se il dito è stazionario non c'è swipe ########################################
                couldBeSwipe = false;
                break;

            case TouchPhase.Ended:
                // quando sollevo il dito effettuo il controllo finale ###########################
                // potrebbe essere uno swipe
                couldBeSwipe = true;
                // calcolo la durata dello swipe
                var swipeTime = Time.time - startTime;
                // calcolo la distanza dello swipe
                var swipeDist = (touch.position - startPos).magnitude;
                
			    // Debug Text inizio #########################################
			    // scrive il tempo in secondi dello swipe es: 1.298765 
			    SwipeTime.text = "Swipe Time: " + swipeTime;
			    // scrive la distanza dello swipe in pixel es: 165.127
			    SwipeDistance.text = "Swipe Distance: " + swipeDist;
			    // Debug Text fine ###########################################
                
                // se è VERO   AND  rientra nel tempo massimo AND ricopre la distanza minima
                if (couldBeSwipe && swipeTime < maxSwipeTime && swipeDist > minSwipeDist) {
                    // è uno swipe! YEHHHHHH!
                    // qualcosa da fare se è uno swipe
                    SwipeDetect.text =  "Swipe!!!";
                    // resetto la variabile
                    couldBeSwipe = false;
                    // resetto la scritta a video
                    SwipeDetect.text =  "Waiting next Swipe";
                }
                break;
        }
    }
}

Hierarchy> Main Camera> Inspector> SwipeDetector.js assign:

– GUI Text Distance -> var SwipeDistance
– GUI Text Is Swipe -> var SwipeDetect
– GUI Text Start Position -> var StartPosText
– GUI Text Start Time -> var StartTimeText
– GUI Text Swipe Time -> var SwipeTime

– Start Time -> 0 (si arrangia lo script a gestirlo)
– Start Pos XY -> 0 0 (si arrangia lo script a gestirlo)
– Could Be Swipe -> uncheck (si arrangia lo script a gestirlo)

– Min Swipe Dist -> 200 (la minima distanza in pixel perchè il gesto sia uno swipe)
– Max Swipe Time -> 0.5 (il tempo massimo che può impiegare il dito a percorrere Min Swipe Dist)

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Android – Swipe – Screen – Detection – JS