programming

Unity 3D Game Engine – Particles follow Cursor Pointer

Unity 3D Game Engine – Particles follow Cursor Pointer

1. MAIN TOP MENU> Main Object> Create Other> Particle System

2. Inspector> Particle System> Add Component> New Script> FollowMouse.JS

3. FollowMouse.JS


#pragma strict
 
function Start () 
{ 
 Screen.showCursor = false; 
} 
 
// -------------------------------
// FOLLOW MOUSE POSITION START
// -------------------------------
public var depth = 10.0; 
 
function FollowMousePosition()
{ 
 var mousePos = Input.mousePosition; 
     var wantedPos = Camera.main.ScreenToWorldPoint (Vector3 (mousePos.x, mousePos.y, depth)); 
     transform.position = wantedPos; 
}
// -------------------------------
// FOLLOW MOUSE POSITION END
// -------------------------------
 
function Update () 
{ 
 FollowMousePosition();  
}

4. Inspector> Setup the Partycle System to create a fairy dust effect:

Particle System

– Start Size: 0.3
– Gravity Multiplier: 1
– Simulation Space: World -> really important!!!

Emission: check it

– Rate: 30

Shape: check it

– Shape: Sphere
– Radius 0.1

Limit Velocity over Lifetime: check it

– Speed: 3
– Dampen: 1

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Particles follow Cursor Pointer

Unity 3D Game Engine – Scripting Javascript – ExecuteInEditMode

Unity 3D Game Engine – Scripting Javascript – ExecuteInEditMode

In Unity gli script vengono eseguiti solamente se viene attivato il pulsante ‘Play’
@ExecuteInEditMode esegue a video lo script anche in fase di editing, senza dover cliccare su ‘Play’.
Usare questa funzione con attenzione perchè lo script risulta sempre attivo.


#pragma strict

@ExecuteInEditMode // esegui lo script anche in modalità di editing del progetto
function Start () 
{
    renderer.sharedMaterial.color = Color.red;
}

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Scripting Javascript – ExecuteInEditMode

Unity 3D Game Engine – Attributes Range – JavaScript

Unity 3D Game Engine – Attributes Range – JavaScript

@Range(-100, 100) // Aggiunge uno slide per il setup della variabile in Inspector


#pragma strict

@Range(-100, 100) // Aggiunge uno slide per il setup della variabile in Inspector
public var speed : int = 0;

function Update () 
{
    transform.Rotate(new Vector3(0, speed * Time.deltaTime, 0));
}

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

Unity 3D Game Engine – JavaScript – Coroutines

Unity 3D Game Engine – JavaScript – Coroutines

Coroutines permettono di gestire comportamenti complessi tra classi differenti.
Coroutines possono essere pensate come funzioni da eseguire a intervalli.
Le Coroutine vanno pecificate con Maiuscolanome+Coroutine, ad esempio MyCoroutine StopCoroutine etc…

Basic

1. Creo un Cube

2. Creo una Sphere ed assegno Coroutine.js

Coroutine.js:


#pragma strict

public var smoothing : float = 1f;
public var target : Transform; // Inspector DRAG over here another GameObject
    
function Start () 
{
    MyCoroutine(target);
}

function MyCoroutine (target : Transform)
{
    while(Vector3.Distance(transform.position, target.position) > 0.05f)
    {
        transform.position = Vector3.Lerp(transform.position, target.position, smoothing * Time.deltaTime);
        
        yield;
    }
    
    print("Reached the target.");
    
    yield WaitForSeconds(3f);
    
    print("MyCoroutine is now finished.");
}

3. Sphere> Inspector> Couroutine.js> DRAG AND DROP Cube GameObject over var target

4. Play: Sphere raggiungerà si muoverà con interpolazione lineare (Lerp) il Cubo-> print(“Reached the target.”)-> dopo 3 sec-> print(“MyCoroutine is now finished.”);

Come funziona?

1. Start() si avvia al caricamento dello script
2. Start() invia alla funzione MyCoroutine() il valore della variabile target, che è la posizione XYZ di Cube

Proprietà

Assegno a Sphere:

PropertiesAndCoroutines.js


#pragma strict

public var smoothing : float = 7f;
private var target : Vector3;

function  SetTarget(value : Vector3)
{
    target = value;
        
    StopCoroutine("Movement");
    StartCoroutine("Movement", target);
}

function Movement (target : Vector3)
{
    while(Vector3.Distance(transform.position, target) > 0.05f)
    {
        transform.position = Vector3.Lerp(transform.position, target, smoothing * Time.deltaTime);
        
        yield;
    }
}

Assegno al piano dove si muoverà Sphere

ClickSetPosition.js


#pragma strict

public var coroutineScript : PropertiesAndCoroutines; // richiama lo script sopra
    

function OnMouseDown ()
{
    var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    var hit : RaycastHit;
    
    Physics.Raycast(ray, hit);
    
    if(hit.collider.gameObject == gameObject)
    {
        var newTarget : Vector3 = hit.point;
        // invia il parametro target allo script PropertiesAndCoroutines        
        coroutineScript.SetTarget(newTarget); 
    }
}

Come funziona?

1. ClickSetPosition.js
– al click il RayCast, calcolato da Camera.main definisce un valore Vector3 XYZ di posizione
– il valore viene mandato alla Coroutine con coroutineScript.SetTarget(newTarget)

2. PropertiesAndCoroutines.js
– riceve il valore XYZ
– ferma la Couroutine, se l’oggetto si sta muovendo viene arrestato
– avvia di nuovo la Courotine, l’oggetto si sposterà verso la nuova destinazione.

Other Examples

Ex 1

function MyCoroutine()
{
    DoSomething():
    yield;                  // wait one frame                        
    DoSomethingElse();
}

Ex 2

function MyCoroutine()
{
    DoSomething():          //Do this immediately
    yield;                  //Return control to the caller
    DoSomethingElse();      //This will be executed one frame later
}
 
void Start()
{
    MyCoroutine();
}

Ex 3

function MyCoroutine()
{
    print("This is printed second");
    yield;                 //Return control to the Start function
    print("This is printed one fourth, exactly one frame after the third");
}
 
void Start()
{
    print("This is printed first");
    MyCoroutine();
    print("This is printed third");
}

Ex 4

function MyCoroutine()
{
    DoSomething():              //Do this immediately
    yield WaitForSeconds(2);    //Return control to the caller
    DoSomethingElse();          //This will be executed 2 seconds after
}
 
void Start()
{
    MyCoroutine();
}

Ex 5

function MyCoroutine()
{
    DoSomething():              //Do this immediately
    yield MyOtherCoroutine();   //Go and execute MyOtherCoroutine!
    DoSomethingElse();          //This will be executed after MyOtherCoroutine finished execution
}
 
function MyOtherCoroutine()
{
    DoStuff():                  //Do this immediately
    yield WaitForSeconds(2);    //Return control to the caller (in this case the Start function)
    DoMoreStuff();              //This will be executed 2 seconds after
    //MyOtherCoroutine finishes execution here
}
 
void Start()
{
    MyCoroutine();
}

References:
– unity3d.com/
– http://www.blog.silentkraken.com/2010/01/22/coroutines-in-unity3d/

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

Unity 3D Game Engine – JavaScript – Interfaces

Unity 3D Game Engine – JavaScript – Interfaces

I ‘contratti’ di Interfaces permettono di aggiungere ad una classe nuove funzioni specificate all’interno di un’altra classe esterna.

Se 2 classi sono A padre->B figlio il figlio potrà usare le funzioni del padre
Se 2 classi hanno un contratto di Interface la classe A (interface) è estesa nelle funzioni dalla classe B (B implements A)

Le Interfaces vengono dichiarate con ‘I maiuscola+lettera maiuscola+nome’, ad esempio IKillable, IDamageable etc…

Le interfaces sono utili quando dobbiamo mettere in relazioni classi che non ha senso considerare padre-figlio. Ad esempio una classe Muro e una classe Auto non ha senso che siano padre-figlio, ma in comune potrebbero avere il fatto che entrambe possono essere danneggiate.

Interfaces.


#pragma strict

//This is a basic interface with a single required
//method.
public interface IKillable
{
    function Kill();
}

//Javascript does not allow generic types to
//be defined, so this version of IDamageable
//uses a float type
public interface IDamageable
{
    function Damage(damageTaken : float);
}

Avatar Class


#pragma strict

public class Avatar extends MonoBehaviour implements IKillable, IDamageable
{
    //The required method of the IKillable interface
    public function Kill()
    {
        //Do something fun
    }
    
    //The required method of the IDamageable interface
    public function Damage(damageTaken : float)
    {
        //Do something fun
    }
}

Come funziona?

1. Avatar Class
– classe pubblica Avatar implementa Interface IKillable
– funzione pubblica Kill() e Damage()

2. Interfaces
– public interface IKillable -> richiama la funzione Kill() da Avatar Class

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