unity3d

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

Unity 3D Game Engine – Long Touch – Draw Line – JavaScript

Unity 3D Game Engine – Long Touch – Draw Line – JavaScript

1. Main Camera attach ‘FingerLine.js’

FingerLine.js:


#pragma strict

// It automatically adds Add Component> Effects> Line Renderer
@script RequireComponent(LineRenderer)

var lineRenderer : LineRenderer;
var myPoints : Vector3[];

function Start () {
    // Setup of LineRenderer Component
    lineRenderer = GetComponent(LineRenderer);
    lineRenderer.SetWidth(0.2,0.2);
}

function Update () {

    if(myPoints){
        lineRenderer.SetVertexCount(myPoints.Length);
        for(var i = 0;i<myPoints.Length;i++){
            lineRenderer.SetPosition(i,myPoints[i]);    
        }
    }
    else
    lineRenderer.SetVertexCount(0);
    
    if(Input.touchCount > 0){
    if(Input.touches[0].phase == TouchPhase.Began)
        // it is only drawing 10 points per second, as per the line
        InvokeRepeating("AddPoint",.1,.1);
    } 
    else{
        CancelInvoke();
        myPoints = null;
    }
}

function AddPoint(){
   
    var tempPoints : Vector3[];

    if(!myPoints)
        tempPoints = new Vector3[1];
    else{
        tempPoints = new Vector3[myPoints.Length+1];
               
    	for(var j = 0; j < myPoints.Length; j++)
        	tempPoints[j] = myPoints[j];
    }
        var tempPos : Vector3 = Input.mousePosition;
    tempPos.z = 10;
    
   tempPoints[j] = Camera.main.ScreenToWorldPoint(tempPos);
   myPoints = new Vector3[tempPoints.Length]; 
   myPoints = tempPoints;   
}

NOTICE: it seems to be a little sluggish.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Long Touch – Draw Line – JavaScript

Unity 3D Game Engine – Android – Swipe – Screen – Move Object

Unity 3D Game Engine – Android – Swipe – Screen – Move Object

Translate a GameObject swiping screen

Hierarchy, create a scene with:

– Main Camera
– Cube (Game Object), attach the script ‘TouchController.js’

TouchController.js


#pragma strict

// Moves object according to finger movement on the screen
	var speed : float = 3.0;
	function Update () {
	    // Se si sta toccando lo schermo e la fase è Moved (il dito sta strisciano)
		if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Moved) {
		
			// Get movement of the finger since last frame
			var touchDeltaPosition:Vector2 = Input.GetTouch(0).deltaPosition;
			
			// Move object across XY plane
			// Time.deltaTime it move xxx meters per second instead of xxx meters per frame
			transform.Translate (touchDeltaPosition.x * Time.deltaTime * speed, touchDeltaPosition.y * Time.deltaTime * speed, 0);
		}
	}

Hierarchy> Cube> Inspector> TouchController.js setup public var speed:

> speed > movement
< speed < movement

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

Unity 3D Game Engine – Android – Tap Single – New Object – Instantiate – JS

Unity 3D Game Engine – Android – Tap Single – New Object – Instantiate – JS

Instantiate new objects by tapping on Android Devices (Unity JavaScript).

1. Hierarchy create the structure:

– Cube (Game Object)
– Main Camera X=0 Y=0 Z=-10, attach the ‘TapInstantiate.js’

TapInstantiate.js


// Main Camera> Inspector> assign a Gameobject of Prefab
var bullet : Transform;

function Update () {  
    
		// Se c'è un tocco  AND  la fase è il primo contatto del dito con il display
		if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began) {
		// Your 2D vector
		var touchPos = Input.GetTouch(0).position;

		// New 3D vector with the Z co-ordinate
		// As your camera's Z is at -10, setting it to 10 will create it at 0 in the world
		// Change z value to instantiate the object near or far the Camera 
		var createPos = Camera.main.ScreenToWorldPoint(Vector3(touchPos.x, touchPos.y, 10));

		Instantiate(bullet, createPos, Quaternion.identity);
        }
}

2. Hierarchy> Main Camera> Inspector> TapInstantiate.js> DRAG AND DROP Cube over public var bullet

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Android – Tap Single – New Object – Instantiate – JS

Unity 3D Game Engine – Android – Tap Single – JS

Unity 3D Game Engine – Android – Tap Single – JS

Simple Android application, if you touch the screen it will change the GUI Text content, No Touch -> Touched!

1. Inside 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;

function Start () {
        scoreText.text = "No Touch";
}

function Update() {
    if (Input.touchCount == 1) {
        // Do something
        scoreText.text = "Touched!";
    }
}

2. Hierarchy> GameController> TouchController.js> DRAG AND DROP ‘GUI Text’ Object over var ‘scoreText’

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Android – Tap Single – JS