programming

Unity 3D Game Engine – JavaScript – Overriding

Unity 3D Game Engine – JavaScript – Overriding

Overriding è una pratica che consente di sovrascrivere un metodo della classe padre con un metodo della classe figlia.

Fruit Class


#pragma strict

public class Fruit 
{
    public function Fruit ()
    {
        Debug.Log("1st Fruit Constructor Called");
    }
    
    //Overriding members happens automatically in 
    //Javascript and doesn't require additional keywords
    public function Chop ()
    {
        Debug.Log("The fruit has been chopped.");     
    }
    
    public function SayHello ()
    {
        Debug.Log("Hello, I am a fruit.");
    }
}

Apple Class


#pragma strict

public class Apple extends Fruit 
{
    public function Apple ()
    {
        Debug.Log("1st Apple Constructor Called");
    }
    
    //Overriding members happens automatically in 
    //Javascript and doesn't require additional keywords
    public function Chop ()
    {
        super.Chop();
        Debug.Log("The apple has been chopped.");     
    }
    
    public function SayHello ()
    {
        super.SayHello();
        Debug.Log("Hello, I am an apple.");
    }
}

FruitSalad Class


#pragma strict

function Start () 
{
    var myApple = new Apple();
    
    //Notice that the Apple version of the methods
    //override the fruit versions. Also notice that
    //since the Apple versions call the Fruit version with
    //the "base" keyword, both are called.
    myApple.SayHello();
    myApple.Chop(); 
    
    //Overriding is also useful in a polymorphic situation.
    //Since the methods of the Fruit class are "virtual" and
    //the methods of the Apple class are "override", when we 
    //upcast an Apple into a Fruit, the Apple version of the 
    //Methods are used.
    var myFruit = new Apple();
    myFruit.SayHello();
    myFruit.Chop();
}

Come funziona?

1. Fruit Class
– una classe pubblica Fruit con le funzioni Fruit() – Chop() – SayHello()

2. Apple Class
– classe figlia di Fruit con le funzioni
– Apple()
– Chop()-> super.Chop()
– SayHello()-> super.SayHello()

3. FruitSalad Class
– la funzione Start() si avvia la caricamento dello script
– richiama Apple().SayHello() e Apple().Chop() -> che vanno in ovverride su Fruit().SayHello() e Fruit().Chop()

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – JavaScript – Overriding

Unity 3D Game Engine – be or not be kinematic

Unity 3D Game Engine – be or not be kinematic, this is the problem…

When we will create a pick up game object, do we need a kinematic or a non-kinematic object?

PickUp Object

1. Create a Cube (PickUp) as ‘Prefab’ to easy duplicate it, with:

SOLUZIONE 1: senza ‘Rigid Body’, lo considera un ‘Collider Statico’, come un muro, e quindi calcola e salva in cache la posizione una volta per tutte, questo ha senso per risparmiare calcoli in caso di un oggetto che non si muove. Se il nostro cubo ruota Unity salva in cache ogni volta la nuova posizione per ogni frame occupando risorse di sistema.
– Box Collider -> check ‘Is Trigger’ -> così non si effettuano calcoli fisici perchè il ‘Trigger’ rileva solo le collisioni senza causare reazioni fisiche

OPPURE

SOLUZIONE 2: applicando un ‘Rigid Body’, lo considera un Collider dinamico, e non salverà dati in cache, occupando meno risorse.
a. Rigid Body> Disabilitare ‘Use Gravity’ per non far cadere l’oggetto. L’oggetto risponde ancora alle sollecitazioni provenienti da altri Collider.
b. Rigid Body> Abilitare ‘Is Kinematic’ per non far calcolare a Unity le reazioni alle sollecitazioni provenienti da altri Collider e ottimizzare il consumo di CPU. Un oggetto ‘Is Kinematic’ può essere spostato utilizzando la funzione ‘Transform’. Questo setup è tipico delle piattaforme mobili di un videogioco ‘platform’.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – be or not be kinematic

Unity 3D Game Engine – Android – Accelerometer – RAW Data – Translate and Object

Unity 3D Game Engine – Android – Accelerometer – RAW Data – Translate and Object

Inside Hierarchy create:

– Main Camera
– GUI Text X
– GUI Text Y
– GUI Text Z
– Cube (Game Object), attach ‘AccelerometerTest.js’

AccelerometerTest.js


#pragma strict

// Hierarchy DRAG E DROP over var GUI Text in Inspector
var scoreTextX : GUIText;
var scoreTextY : GUIText;
var scoreTextZ : GUIText;

	function Update () {
		var dir : Vector3 = Vector3.zero; // Shorthand for writing Vector3(0, 0, 0)
		
		dir.x = Input.acceleration.x;
		dir.y = Input.acceleration.y;
		dir.z = Input.acceleration.z;
		
		scoreTextX.text = "acceleration.x: "  + dir.x;
		scoreTextY.text = "acceleration.y: "  + dir.y;
		scoreTextZ.text = "acceleration.z: "  + dir.z;
		
	}

Hierarchy> Cube> Inspector> AccelerometerTest.js assign GUI Text to public var scoreText

Here the final result:

dir.x = Input.acceleration.x; from 1 to -1 -> example: 0.1234567 or -0.1234567
dir.y = Input.acceleration.y; from 1 to -1
dir.z = Input.acceleration.z; from 1 to -1

unity-001

unity-002

unity-003

To translate the Cube using Accelerometer data (basic):

AccelerometerTest.js


#pragma strict

function Update () 
{
    transform.Translate(Input.acceleration.x, 0, -Input.acceleration.z);
}

To translate the Cube using Accelerometer data (advanced):

AccelerometerTest.js


#pragma strict

	// Move object using accelerometer
	var speed = 10.0;

// Hierarchy DRAG E DROP over var GUI Text in Inspector
var scoreTextX : GUIText;

	function Update () {
		var dir : Vector3 = Vector3.zero; // Shorthand for writing Vector3(0, 0, 0)
		
		dir.x = Input.acceleration.x;
		
		scoreTextX.text = "acceleration.x: "  + dir.x;
		
		// clamp acceleration vector to unit sphere
		if (dir.sqrMagnitude > 1)
			dir.Normalize();
		
		// Make it move 10 meters per second instead of 10 meters per frame...
		dir *= Time.deltaTime;
			
		// Move object
		transform.Translate (dir * speed);
		
	}

unity-004

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Android – Accelerometer – RAW Data – Translate and Object

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

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

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Android – Get Finger Position – JS

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