unity3d

Unity 3D – JS Script – gameController

Unity 3D – JS Script – gameController

BG Music multiple tracks management

1. MAIN TOP MENU> GameObject> Create Empty, name it ‘gameController’
2. ‘Add Component’> Audio> Audio Source>
– Audio Clip, DRAG AND DROP the background music
– Play On Awake: check
– Loop: check

3. 1. MAIN TOP MENU> GameObject> Create Empty, name it ‘secondaryMusic’
4. ‘Add Component’> Audio> Audio Source>
– Audio Clip, DRAG AND DROP the secondary music
– Play On Awake: check
– Loop: check
– Volume = 0 if the volume will be >0 you listen 2 audio source at the same time!

5. Hierarchy DRAG AND DROP ‘secondaryMusic’ over ‘gameController’, now:
‘gameController'(parent)
|->’secondaryMusic’ (child)

Sighting (avvistamento)

Hierarchy> env_stealth_static> props> select CTRL + All prop_megaphone_00etc…> Inspector> Tag ‘Siren’
Open the 3D megaphone game objects and assign Tag ‘Siren’.
Se ci sarà un avvistamento tutti i megafoni 3D dovranno suonare contemporaneamente.

Con ancora tutti gli elementi selezionati assegnare il suono dell’allarme con
Inspector> Add Component> Audio> Audio Source> Audio Clip> DRAG AND DROP from Project> Audio> alarm_triggered
– Play On Awake: uncheck
– Loop: check
– 3D Sound Settings> Min Distance> 5, l’audio si sentirà se si entra nel raggio di 5 unità dall’oggetto 3D, l’area delimitata nella viewport dalla sfera azzurra.

6. Hierarchy ‘gameController’> Inspector> ‘Add Component’> LastPlayerSighting.js

#pragma strict

public var position : Vector3 = new Vector3(1000f, 1000f, 1000f);       // The last global sighting of the player.
public var resetPosition : Vector3 = new Vector3(1000f, 1000f, 1000f);  // The default position if the player is not in sight.
public var lightHighIntensity : float = 0.25f;                          // The directional light's intensity when the alarms are off.
public var lightLowIntensity : float = 0f;                              // The directional light's intensity when the alarms are on.
public var fadeSpeed : float = 7f;                                      // How fast the light fades between low and high intensity.
public var musicFadeSpeed : float = 1f;                                 // The speed at which the 


private var alarm : AlarmLight;                                         // Reference to the AlarmLight script.
private var mainLight : Light;                                          // Reference to the main light.
private var panicAudio : AudioSource;                                   // Reference to the AudioSource of the panic msuic.
private var sirens : AudioSource[];                                     // Reference to the AudioSources of the megaphones.


function Awake ()
{
    // Setup the reference to the alarm light.
    alarm = GameObject.FindGameObjectWithTag(Tags.alarm).GetComponent(AlarmLight);
    
    // Setup the reference to the main directional light in the scene.
    mainLight = GameObject.FindGameObjectWithTag(Tags.mainLight).light;
    
    // Setup the reference to the additonal audio source.
    panicAudio = transform.Find("secondaryMusic").audio;
    
    // Find an array of the siren gameobjects.
    var sirenGameObjects : GameObject[] = GameObject.FindGameObjectsWithTag(Tags.siren);
    
    // Set the sirens array to have the same number of elements as there are gameobjects.
    sirens = new AudioSource[sirenGameObjects.Length];
    
    // For all the sirens allocate the audio source of the gameobjects.
    for(var i = 0; i < sirens.Length; i++)
    {
        sirens[i] = sirenGameObjects[i].audio;
    }
}


function Update ()
{
    // Switch the alarms and fade the music.
    SwitchAlarms();
    MusicFading();
}


function SwitchAlarms ()
{
    // Set the alarm light to be on or off.
    alarm.alarmOn = position != resetPosition;
    
    // Create a new intensity.
    var newIntensity : float;
    
    // If the position is not the reset position...
    if(position != resetPosition)
        // ... then set the new intensity to low.
        newIntensity = lightLowIntensity;
    else
        // Otherwise set the new intensity to high.
        newIntensity = lightHighIntensity;
    
    // Fade the directional light's intensity in or out.
    mainLight.intensity = Mathf.Lerp(mainLight.intensity, newIntensity, fadeSpeed * Time.deltaTime);
    
    // For all of the sirens...
    for(var i = 0; i < sirens.Length; i++)
    {
        // ... if alarm is triggered and the audio isn't playing, then play the audio.
        if(position != resetPosition && !sirens[i].isPlaying)
            sirens[i].Play();
        // Otherwise if the alarm isn't triggered, stop the audio.
        else if(position == resetPosition)
            sirens[i].Stop();
    }
}


function MusicFading ()
{
    // If the alarm is not being triggered...
    if(position != resetPosition)
    {
        // ... fade out the normal music...
        audio.volume = Mathf.Lerp(audio.volume, 0f, musicFadeSpeed * Time.deltaTime);
        
        // ... and fade in the panic music.
        panicAudio.volume = Mathf.Lerp(panicAudio.volume, 0.8f, musicFadeSpeed * Time.deltaTime);
    }
    else
    {
        // Otherwise fade in the normal music and fade out the panic music.
        audio.volume = Mathf.Lerp(audio.volume, 0.8f, musicFadeSpeed * Time.deltaTime);
        panicAudio.volume = Mathf.Lerp(panicAudio.volume, 0f, musicFadeSpeed * Time.deltaTime);
    }
}
By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D – JS Script – gameController

Unity 3D – JS Script – Screen Fader

Unity 3D – JS Script – Screen Fader

1. MAIN TOP MENU> GameObject> Create Other> GUI TEXTURE> Inspector, rename it ‘ScreenFader’
2. Inspector> Transform> Position X=0 Y=0 Z=0 (così viene posizionata in basso a sinistra dello schermo)
3. Pixel Inset, X=0 Y=0 W=0 H=0 (non vogliamo che ci siano dei rientri)
4. Inspector> GUI Texture> DRAG E DROP a black bitmap Texture
5. Assign to ‘ScreenFader’ GameObject this JS Script:

SceneFadeInOut.js

#pragma strict

public var fadeSpeed : float = 1.5f;            // Speed that the screen fades to and from black.
private var sceneStarting : boolean = true;     // Whether or not the scene is still fading in.

function Awake ()
{
    // Set the texture so that it is the size of the screen and covers it.
    // Per prima cosa ricopro tutto lo schermo creando un rettangolo di dimensione dello schermo
    guiTexture.pixelInset = new Rect(0f, 0f, Screen.width, Screen.height);
}


function Update ()
{
    // If the scene is starting...
    // Controlla il valore booleano -sceneStarting- se è vero esegue le istruzioni all'interno di -if-
    if(sceneStarting)
        // ... call the StartScene function.
        // richiama la funzione
        StartScene();
}


function FadeToClear ()
{
    // Lerp (interpolate 2 values) the colour of the texture between itself and transparent.
    // Esegue un fading - colore della texture -> completamente trasparente -
    guiTexture.color = Color.Lerp(guiTexture.color, Color.clear, fadeSpeed * Time.deltaTime);
}


function FadeToBlack ()
{
    // Lerp (interpolate 2 values) the colour of the texture between itself and black.
    guiTexture.color = Color.Lerp(guiTexture.color, Color.black, fadeSpeed * Time.deltaTime);
}


function StartScene ()
{
    // Fade the texture to clear.
    FadeToClear();
    
    // If the texture is almost clear...
    // Se il colore è quasi completamente trasparente
    if(guiTexture.color.a <= 0.05f)
    {
        // ... set the colour to clear and disable the GUITexture.
        // Rendi il colore completamente trasparente e disabilita la GUI Texture
        guiTexture.color = Color.clear;
        guiTexture.enabled = false;
        
        // The scene is no longer starting.
        // Imposta la variabile booleana a falso per interrompere il ciclo
        sceneStarting = false;
    }
}


public function EndScene ()
{
    // Make sure the texture is enabled.
    guiTexture.enabled = true;
    
    // Start fading towards black.
    FadeToBlack();
    
    // If the screen is almost black...
    if(guiTexture.color.a >= 0.95f)
        // ... reload the level.
        Application.LoadLevel(0);
}

Inspector> SceneFadeInOut.js> ‘Fade Speed’ variable, assign 0.5 (valore basso -> tempo di fading alto)

NOTICE:

Application.LoadLevel(0);

Setup the correct level number, you can find it inside MAIN TOP MENu> File> Build Settings…
If you have only one scene in your project, just reload it -> .LoadLevel(0)

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D – JS Script – Screen Fader

Unity – Advanced Tags Management

In order to minimize errors we can put our Tags inside a script.
Oper the Project> Script Folder> Create New Js Script

#pragma strict

// A list of tag strings.
public static var player : String = "Player";
public static var alarm : String = "AlarmLight";
public static var siren : String = "Siren";
public static var gameController : String = "GameController";
public static var mainLight : String = "MainLight";
public static var fader : String = "Fader";
public static var enemy : String = "Enemy";
By |Unity3D, Video Games Development|Commenti disabilitati su Unity – Advanced Tags Management

Unity 3D – Stealth Game – Alarm Light

Unity 3D – Stealth Game – Alarm Light

1. MAIN TOp MENU> Create Other> Directional Light renami it ‘light_alarm_directional’

2. ‘Add Component’> Alarm Lights.js


#pragma strict

public var fadeSpeed : float = 2f;          // How fast the light fades between intensities.
public var highIntensity : float = 2f;      // The maximum intensity of the light whilst the alarm is on.
public var lowIntensity : float = 0.5f;     // The minimum intensity of the light whilst the alarm is on.
public var changeMargin : float = 0.2f;     // The margin within which the target intensity is changed.
public var alarmOn : boolean;               // Whether or not the alarm is on.


private var targetIntensity : float;        // The intensity that the light is aiming for currently.


function Awake ()
{
    // When the level starts we want the light to be "off".
    light.intensity = 0f;
    
    // When the alarm starts for the first time, the light should aim to have the maximum intensity.
    targetIntensity = highIntensity;
}


function Update ()
{
    // If the light is on...
    if(alarmOn)
    {
        // ... Lerp the light's intensity towards the current target.
        // Mathf.Lerp - static function Lerp(from: float, to: float, t: float): float; -
        // Interpolates between a and b by t. t is clamped between 0 and 1
        light.intensity = Mathf.Lerp(light.intensity, targetIntensity, fadeSpeed * Time.deltaTime);
        
        // Check whether the target intensity needs changing and change it if so.
        CheckTargetIntensity();
    }
    else
        // Otherwise fade the light's intensity to zero.
        light.intensity = Mathf.Lerp(light.intensity, 0f, fadeSpeed * Time.deltaTime);
}


function CheckTargetIntensity ()
{
    // If the difference between the target and current intensities is less than the change margin...
    // Mathf.Abs - static function Abs(f: float): float;
    // Returns the absolute value of f
    if(Mathf.Abs(targetIntensity - light.intensity) < changeMargin)
    {
        // ... if the target intensity is high...
        if(targetIntensity == highIntensity)
            // ... then set the target to low.
            targetIntensity = lowIntensity;
        else
            // Otherwise set the targer to high.
            targetIntensity = highIntensity;
    }
}

Inspector> Alarm Light.js> check ‘Alarm On’… wow it pulses!

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D – Stealth Game – Alarm Light

Unity 3D – Stealth Game – Environment Setup

Unity 3D – Stealth Game – Environment Setup

Geometry

1. Import .fbx file with hires Mesh ‘env_stealth_static’
2. ‘Add component’> Mesh Collider> Mesh> assign the lowres Mesh ‘env_stealth_collider’
3. Hierarchy> select + CTRL ‘env_stealth_static’ + ‘env_stealth_collider’> Inspector check ‘Static’ (Unity now knows this object will not move)

Camera

Hierarchy> Main Camera> Inspector> rename camera_main> Camera> Clipping Planes 0.3 – 100

Baked Lights – Points Light

Add Point Light> Inspector> Light> Lightmapping> Baked Only, in questo modo il calcolo NON E’ REALTIME ma calcolato una sola volta all’inizio della scena per megliorare le prestazioni del gioco.

Render Settings

MAIN TOP MENU> Edit> Render Setting> setup parameters

Quality Settings

MAIN TOP MENU> Edit>Project Settings> Quality> setup parameters

Light Mapping

Una LightMap è una mappa di ombre, il motore calcola i punti dove c’è possibilità che si crei un ombra o ci sia un punto di luce.
Il risultato finale non è altro che un’ immagine che andrà poi sulla texture, creando zone di luce e ombra precalcolate.

Se non si calcola la LightMap le luci con attributo ‘Baked Only’ non avranno nessun effetto sulla scena dopo il suo ‘Buil’.

1. MAIN TOP MENU> Window> Light Mapping> Inspector> |Bake|> Mode> Directional Lightmaps and other setups
2. BOTTOM RIGHT> ‘Bake Scene’
ATTENZIONE! Il processo partirà in batch ma il rendering potrebbe richiedere molto tempo perchè è un calcolo in Global Illumination!
3. At the end a Light Map will be applied to Meshes

Real Time Lights – Directional Lights

Unity ha creato un Light Mapping con le luci con il parametro ‘Baked Only’, queste non emettono ombre perchè sono tutte ‘Point light’.
Per generare delle ombre dinamiche devo creare delle ‘Directional Light’, le uniche in Unity in grado di emettere delle ombre.
Le risorse consumate saranno minime perchè useremo al massimo 2 o 3 ‘Directional Lights’ che emetteranno delle vere ombre in tempo reale.

Add Directional Light> Inspector> Light>
| Lightmapping> Real Time Only, in questo modo il calcolo NON VA MAI IN BAKE
| Shadows> Soft Shadows per avere un effetto viasuale di fusione migliore con la LightMap
| Culling Mask> selezionare i livelli che non saranno illuminati da questa luce

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D – Stealth Game – Environment Setup