javascript

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 – Java Script – Polymorphism – Upcasting – Downcasting

Unity 3D Game Engine – Java Script – Polymorphism – Upcasting – Downcasting

Polymorphism – Upcasting – Downcasting vengono utilizzate per creare funzioni dinamiche tra classi legate da parentela padre-figlio.

Fruit Class


#pragma strict

public class Fruit 
{
    public function Fruit ()
    {
        Debug.Log("1st Fruit Constructor Called");
    }
    
    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");
    }
    
    //Apple has its own version of Chop() and SayHello(). 
    //When running the scripts, notice when Fruit's version
    //of these methods are called and when Apple's version
    //of these methods are called.
    //In this example, the "new" keyword is used to supress
    //warnings from Unity while not overriding the methods
    //in the Apple class.
    public function Chop ()
    {
        Debug.Log("The apple has been chopped.");     
    }
    
    public function SayHello ()
    {
        Debug.Log("Hello, I am an apple.");
    }
}

FruitSalad Class


#pragma strict

function Start () 
{
    //Notice here how the variable "myFruit" is of type
    //Fruit but is being assigned a reference to an Apple. This
    //works because of Polymorphism. Since an Apple is a Fruit,
    //this works just fine. While the Apple reference is stored
    //in a Fruit variable, it can only be used like a Fruit
    var myFruit = new Apple();

    myFruit.SayHello();
    myFruit.Chop();
    
    //This is called downcasting. The variable "myFruit" which is 
    //of type Fruit, actually contains a reference to an Apple. Therefore,
    //it can safely be turned back into an Apple variable. This allows
    //it to be used like an Apple, where before it could only be used
    //like a Fruit.
    var myApple = myFruit as Apple;
    
    myApple.SayHello();
    myApple.Chop(); 
}

Come funziona?

1. Fruit Class
– al suo interno ha i costruttori pubblici Fruit() – Chop() – SayHello()

2. Apple Class
– è una classe figlia di Fruit Class ‘… class Apple extends Fruit …’
– ha il proprio costruttore Chop() – SayHello()

3. FruitSalad Class
– la funzione Start() è la prima che si avvia al caricamento dello script
– richiama Apple().SayHello – Apple().Chop()
– fa il Downcasting a:


var myApple = myFruit as Apple;

quindi sarà richiamata Fruit().SayHello – Fruit().Chop()

Apple appartiene di sicuro alla categoria Fruit, ma non è detto che sia vero il contrario.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Java Script – Polymorphism – Upcasting – Downcasting

Unity 3D Game Engine – JavaScripts – Statics

Unity 3D Game Engine – JavaScripts – Statics

Solitamente se una stessa variabile si trova all’interno di classi diverse, questa assume valori diversi per ogni classe.
Se una variabile è statica invece ha avrà lo stesso valore anche se appartiene a classi differenti.
Cambiare il valore di una variabile statica all’interno di una classe equivale a cambiarne il valore all’interno di tutte le altre classi.

Vediamo un esempio

Enemy


#pragma strict

public class Enemy
{
    //Static variables are shared across all instances
    //of a class.
    public static var enemyCount : int = 0;
    
    function Enemy()
    {
        //Increment the static variable to know how many
        //objects of this class have been created.
        enemyCount++;
    }
}

Game


#pragma strict

public class Game
{
    function Start () 
    {
        var enemy1 = new Enemy();
        var enemy2 = new Enemy();
        var enemy3 = new Enemy();
        
        //You can access a static variable by using the class name
        //and the dot operator.
        var x : int = Enemy.enemyCount;
    }
}

Player


#pragma strict

public class Player extends MonoBehaviour 
{
    //Static variables are shared across all instances
    //of a class. 
    public static var playerCount : int = 0;
    
    function Start()
    {
        //Increment the static variable to know how many
        //objects of this class have been created.
        playerCount++;
    }
}

PlayerManager


#pragma strict

function Start () 
{
    //You can access a static variable by using the class name
    //and the dot operator.
    var x : int = Player.playerCount;
}

Come funziona?

1. Enemy
– definisco una classe pubblica ‘Enemy’ perchè sia accessibile da qualunque script
– definisco una variabile statica ‘enemyCount’
– incremento di +1 ‘enemyCount’

2. Game
– definisco una classe pubblica ‘Game’
– all’inizio del gioco si avvia la funziona Start(), ogni variabile enemy1-2-3 avvia l’incremento del conteggio
– accedo alla variabile statica semplicemente con var x : int = Enemy.enemyCount; -> nomeclasse.nomevariabilestatica

3. Player
Funziona come Enemy definisce la variabile statica playerCount, poi la incrementa playerCount++

4. PlayerManager
– accedo alla variabile statica semplicemente con var x : int = Player.playerCount; -> nomeclasse.nomevariabilestatica

5. Utilities

Altri esempi

Utilities


#pragma strict

public static class Utilities 
{
    //A static method can be invoked without an object
    //of a class. Note that static methods cannot access
    //non-static member variables
    public static function Add(num1 : int, num2 : int) : int
    {
        return num1 + num2;
    }
}

UtilitiesExample


#pragma strict

function Start () 
{
    //You can access a static method by using the class name
    //and the dot operator.
    var x : int = Utilities.Add (5, 6);
}

Come funziona?

1. Utilities
– definisce una funzione statica

2. tilitiesExample
– spedisce i valori 5,6 alla classe pubblica statica Utilities.funzionepubblicastatica -> ritorna la somma 5+6 -> X = 11

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

Unity 3D Game Engine 4.x – Custom Web Player Preload

Unity 3D Game Engine 4.x – Custom Web Player Preload

unity3d-custom-preloader

Inside your Build folder you have:

– space_shooter.html
– space_shooter.unity3d

Copy here:

– MyLogo.png
– MyProgressBar.png
– MyProgressFrame.png

MyLogo
MyProgressBar
MyProgressFrame

Open space_shooter.html and add:

// Customizing the Unity Web Player START
// Copy png images in the same folder of this html and .unity3d file
var params = {
        backgroundcolor: "A0A0A0",
        bordercolor: "000000",
	textcolor: "FFFFFF",
	logoimage: "MyLogo.png",
	progressbarimage: "MyProgressBar.png",
	progressframeimage: "MyProgressFrame.png"
	};
// Customizing the Unity Web Player END

Remove…

var u = new UnityObject2(config);

… and replace with:

var u = new UnityObject2({ params: params });			

How does it work?
Easy! It create an array of parameters – var params = … – and pass them to UnityObject2 constructor.

Complete Code sample:

DEFAULT PLAYER:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Luce Digitale | Space Shooter</title>
		<script type='text/javascript' src='https://ssl-webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/jquery.min.js'></script>
		<script type="text/javascript">
		<!--
		var unityObjectUrl = "http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject2.js";
		if (document.location.protocol == 'https:')
			unityObjectUrl = unityObjectUrl.replace("http://", "https://ssl-");
		document.write('<script type="text\/javascript" src="' + unityObjectUrl + '"><\/script>');
		-->
		</script>
		<script type="text/javascript">
		<!--
			var config = {
				width: 600, 
				height: 900,
				params: { enableDebugging:"0" }
				
			};
			var u = new UnityObject2(config);

			jQuery(function() {

				var $missingScreen = jQuery("#unityPlayer").find(".missing");
				var $brokenScreen = jQuery("#unityPlayer").find(".broken");
				$missingScreen.hide();
				$brokenScreen.hide();
				
				u.observeProgress(function (progress) {
					switch(progress.pluginStatus) {
						case "broken":
							$brokenScreen.find("a").click(function (e) {
								e.stopPropagation();
								e.preventDefault();
								u.installPlugin();
								return false;
							});
							$brokenScreen.show();
						break;
						case "missing":
							$missingScreen.find("a").click(function (e) {
								e.stopPropagation();
								e.preventDefault();
								u.installPlugin();
								return false;
							});
							$missingScreen.show();
						break;
						case "installed":
							$missingScreen.remove();
						break;
						case "first":
						break;
					}
				});
				u.initPlugin(jQuery("#unityPlayer")[0], "space_shooter.unity3d");
			});
		-->
		</script>
		<style type="text/css">
		<!--
		body {
			font-family: Helvetica, Verdana, Arial, sans-serif;
			background-color: white;
			color: black;
			text-align: center;
		}
		a:link, a:visited {
			color: #000;
		}
		a:active, a:hover {
			color: #666;
		}
		p.header {
			font-size: small;
		}
		p.header span {
			font-weight: bold;
		}
		p.footer {
			font-size: x-small;
		}
		div.content {
			margin: auto;
			width: 600px;
		}
		div.broken,
		div.missing {
			margin: auto;
			position: relative;
			top: 50%;
			width: 193px;
		}
		div.broken a,
		div.missing a {
			height: 63px;
			position: relative;
			top: -31px;
		}
		div.broken img,
		div.missing img {
			border-width: 0px;
		}
		div.broken {
			display: none;
		}
		div#unityPlayer {
			cursor: default;
			height: 900px;
			width: 600px;
		}
		-->
		</style>
	</head>
	<body>
		<p class="header"><span>Se è la prima volta che si gioca | </span>Installare il plugin richiesto, chiudere e riavviare il browser</p>
		<div class="content">
			<div id="unityPlayer">
				<div class="missing">
					<a href="http://unity3d.com/webplayer/" title="Unity Web Player. Install now!">
						<img alt="Unity Web Player. Install now!" src="http://webplayer.unity3d.com/installation/getunity.png" width="193" height="63" />
					</a>
				</div>
				<div class="broken">
					<a href="http://unity3d.com/webplayer/" title="Unity Web Player. Install now! Restart your browser after install.">
						<img alt="Unity Web Player. Install now! Restart your browser after install." src="http://webplayer.unity3d.com/installation/getunityrestart.png" width="193" height="63" />
					</a>
				</div>
			</div>
		</div>
		<p class="footer">&laquo; avaiable on <a href="http://www.lucedigitale.com" title="Luce Digitale">www.lucedigitale.com</a> &raquo;</p>
		</body>
</html>

CUSTOM PLAYER:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Luce Digitale | Space Shooter</title>
		<script type='text/javascript' src='https://ssl-webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/jquery.min.js'></script>
		<script type="text/javascript">
		<!--
		var unityObjectUrl = "http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject2.js";
		if (document.location.protocol == 'https:')
			unityObjectUrl = unityObjectUrl.replace("http://", "https://ssl-");
		document.write('<script type="text\/javascript" src="' + unityObjectUrl + '"><\/script>');
		-->
		</script>
		<script type="text/javascript">
		// Customizing the Unity Web Player START
		// Copy png images in the same folder of this html and .unity3d file
		var params = {
			backgroundcolor: "A0A0A0",
			bordercolor: "000000",
			textcolor: "FFFFFF",
			logoimage: "MyLogo.png",
			progressbarimage: "MyProgressBar.png",
			progressframeimage: "MyProgressFrame.png"
		};
		// Customizing the Unity Web Player END
		<!--
			var config = {
				width: 600, 
				height: 900,
				params: { enableDebugging:"0" }
				
			};
			// Remove default settings -> var u = new UnityObject2(config);
			// Replace with custom settings START
			var u = new UnityObject2({ params: params });
			// Replace with custom settings END

			jQuery(function() {

				var $missingScreen = jQuery("#unityPlayer").find(".missing");
				var $brokenScreen = jQuery("#unityPlayer").find(".broken");
				$missingScreen.hide();
				$brokenScreen.hide();
				
				u.observeProgress(function (progress) {
					switch(progress.pluginStatus) {
						case "broken":
							$brokenScreen.find("a").click(function (e) {
								e.stopPropagation();
								e.preventDefault();
								u.installPlugin();
								return false;
							});
							$brokenScreen.show();
						break;
						case "missing":
							$missingScreen.find("a").click(function (e) {
								e.stopPropagation();
								e.preventDefault();
								u.installPlugin();
								return false;
							});
							$missingScreen.show();
						break;
						case "installed":
							$missingScreen.remove();
						break;
						case "first":
						break;
					}
				});
				u.initPlugin(jQuery("#unityPlayer")[0], "space_shooter.unity3d");
			});
		-->
		</script>
		<style type="text/css">
		<!--
		body {
			font-family: Helvetica, Verdana, Arial, sans-serif;
			background-color: white;
			color: black;
			text-align: center;
		}
		a:link, a:visited {
			color: #000;
		}
		a:active, a:hover {
			color: #666;
		}
		p.header {
			font-size: small;
		}
		p.header span {
			font-weight: bold;
		}
		p.footer {
			font-size: x-small;
		}
		div.content {
			margin: auto;
			width: 600px;
		}
		div.broken,
		div.missing {
			margin: auto;
			position: relative;
			top: 50%;
			width: 193px;
		}
		div.broken a,
		div.missing a {
			height: 63px;
			position: relative;
			top: -31px;
		}
		div.broken img,
		div.missing img {
			border-width: 0px;
		}
		div.broken {
			display: none;
		}
		div#unityPlayer {
			cursor: default;
			height: 900px;
			width: 600px;
		}
		-->
		</style>
	</head>
	<body>
		<p class="header"><span>Se è la prima volta che si gioca | </span>Installare il plugin richiesto, chiudere e riavviare il browser</p>
		<div class="content">
			<div id="unityPlayer">
				<div class="missing">
					<a href="http://unity3d.com/webplayer/" title="Unity Web Player. Install now!">
						<img alt="Unity Web Player. Install now!" src="http://webplayer.unity3d.com/installation/getunity.png" width="193" height="63" />
					</a>
				</div>
				<div class="broken">
					<a href="http://unity3d.com/webplayer/" title="Unity Web Player. Install now! Restart your browser after install.">
						<img alt="Unity Web Player. Install now! Restart your browser after install." src="http://webplayer.unity3d.com/installation/getunityrestart.png" width="193" height="63" />
					</a>
				</div>
			</div>
		</div>
		<p class="footer">&laquo; avaiable on <a href="http://www.lucedigitale.com" title="Luce Digitale">www.lucedigitale.com</a> &raquo;</p>
		</body>
</html>

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine 4.x – Custom Web Player Preload

Unity 3D – Game Engine – Responsive and Adaptive Apps

Unity 3D – Game Engine – Responsive and Adaptive Apps

Responsive Web Design (RWD) is a Apps design approach aimed at crafting sites to provide an optimal viewing experience—easy reading and navigation with a minimum of resizing, panning, and scrolling—across a wide range of devices (from mobile phones to desktop computer monitors)

Basics Screen.width and Screen.height

Inside Hierarchy create:

– Main Camera
– GUI Text
– GUI Texture> Inspector> W=200(width pix) H=200(height pix), attach ‘Adaptive.js’

Adaptive.js


#pragma strict

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

function Update () {   
        // it will check resolution every frame 
        screenres = Screen.width + " " + Screen.height;                            
        scoreTextX.text = "Screen width & height (pix) "+ screenres;
        }

Hierarchy> GUI Texture> Adaptive.js DRAG AND DROP over public var ‘scoreTextX’ the ‘GUI Text’ game object.

The result on my Samsung SmartPhone (Landscape) is: Screen width & height (pix) 800 480

GUI Texture – Full Screen

Adaptive.js


#pragma strict

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

function Update () {   
        // it will check resolution every frame 
        screenres = Screen.width + " " + Screen.height;                            
        scoreTextX.text = "Screen width & height (pix) "+ screenres;
        // Move the object to (0, 0, 0)
	transform.position = Vector3(0, 0, 0); // equal than Inspector> Position X=0 Y=0 Z=0
        guiTexture.pixelInset = new Rect(0f, 0f, Screen.width, Screen.height); // equal than Inspector> W=800 H=480
        }

Notice:
Position X=0 Y=0 Z=0
Inspector> W=800 H=480

GUI Texture – Half Left Screen

Adaptive.js


#pragma strict

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

function Update () {   
        // it will check resolution every frame 
        screenres = Screen.width + " " + Screen.height;                            
        scoreTextX.text = "Screen width & height (pix) "+ screenres;
        // Move the object to (0, 0, 0)
	transform.position = Vector3(0, 0, 0);
        guiTexture.pixelInset = new Rect(0f, 0f, Screen.width*0.5, Screen.height);
        }



GUI Texture – Half Right Screen

Adaptive.js


#pragma strict

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

function Update () {   
        // it will check resolution every frame 
        screenres = Screen.width + " " + Screen.height;                            
        scoreTextX.text = "Screen width & height (pix) "+ screenres;
        // Move the object 
	transform.position = Vector3(0.5, 0, 0);
        guiTexture.pixelInset = new Rect(0f, 0f, Screen.width*0.5, Screen.height);
        }


GUI Texture – Square – bottom left


#pragma strict

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

function Update () {   
        // it will check resolution every frame 
        screenres = Screen.width + " " + Screen.height;                            
        scoreTextX.text = "Screen width & height (pix) "+ screenres;
        // Move the object, these values are fronm 0 to 1 
	transform.position = Vector3(0, 0, 0);
	// Create a square based on Screen.height*0.5 (half of screen height)
        guiTexture.pixelInset = new Rect(0f, 0f, Screen.height*0.5, Screen.height*0.5);
        }

GUI Texture – Square – top left


#pragma strict

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

function Update () {   
        // it will check resolution every frame 
        screenres = Screen.width + " " + Screen.height;                            
        scoreTextX.text = "Screen width & height (pix) "+ screenres;
        // Move the object, these values are fronm 0 to 1 
	transform.position = Vector3(0, 0.5, 0);
	// Create a square based on Screen.height*0.5 (half of screen height)
        guiTexture.pixelInset = new Rect(0f, 0f, Screen.height*0.5, Screen.height*0.5);
        }



GUI Texture – Square – center


#pragma strict

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

private var btnWidth : int;
private var btnHeight : int;
private var insetX : int;
private var insetY : int;

function Update () {   
        // debug code - it will check resolution every frame 
        screenres = Screen.width + " " + Screen.height;                            
        scoreTextX.text = "Screen width & height(pix) "+ screenres;
        
        // texture size is based on display resolution (pixel)
        btnWidth  = Screen.height*0.5;
        btnHeight = Screen.height*0.5; // if you want change aspect ratio here
        
        // calcolate inset (pixel)
        insetX = -1*(btnWidth/2); // we need negative value (pixel)
        insetY = -1*(btnHeight/2);
        
        // center position X Y (Z is used to create layers of textures (values from 0 to 1)
	transform.position = Vector3(0.5, 0.5, 0);
	// GUI Texture responsive size and position
        guiTexture.pixelInset = new Rect(insetX, insetY, btnWidth, btnHeight);
        }

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D – Game Engine – Responsive and Adaptive Apps