videogames development

Unity 3D Games – Video Surveillance – CCTV Camera – JS Script

Unity 3D Games – Video Surveillance – CCTV Camera – JS Script

1. Inserire il modello 3D della camera di sorveglianza nella scena
2. Imparentare come figlio un oggetto con un ‘Mesh Collider’ come ‘Trigger’ a piramide che simula l’area di visione della camera.
3. Gestisce la collisione tra il ‘Playe’r e il ‘Trigger’ assegnado al ‘Mesh Collider’:


#pragma strict

private var player : GameObject;                                // Reference to the player. Assegnare in Inspector l'oggetto da rilevare
private var lastPlayerSighting : LastPlayerSighting;            // Reference to the global last sighting of the player.


function Awake ()
{
    // Setting up the references.
    // Rileva l'oggetto Player in base al tag -player-
    player = GameObject.FindGameObjectWithTag(Tags.player); 
    // Rileva l'oggetto Game Controller in base al tag -gameControllerr- e ottiene lo script LastPlayerSighting
    lastPlayerSighting = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent(LastPlayerSighting);
}


function OnTriggerStay (other : Collider)
{
    // If the colliding gameobject is the player...
    // Se collide l'oggetto player...
    if(other.gameObject == player)
    {
        // ... raycast from the camera towards the player.
        // Emetti Raycast, in questo modo il plyaer viene rilevato solo se si trova di fronte alla camera
        // CONSIDERAZIONE: come soluzione semplificata avrei creato un piccolo 'Mesh Collider' a forma di cubo per simulare il RayCast,
        // avrei risolto tutto con una sola collisione, risparmiando il calcolo Raycasting!
        var relPlayerPos : Vector3 = player.transform.position - transform.position;
        var hit : RaycastHit;
        
        if(Physics.Raycast(transform.position, relPlayerPos, hit))
            // If the raycast hits the player...
            // se il Raycast colpisce il player
            if(hit.collider.gameObject == player)
                // ... set the last global sighting of the player to the player's position.
                // fai partire l'allarme
                lastPlayerSighting.position = player.transform.position;
    }
}

CONSIDERAZIONE E OTTIMIZZAZIONE: come soluzione semplificata avrei creato un piccolo ‘Mesh Collider’ a forma di cubo per simulare il RayCast, avrei risolto tutto con una sola collisione, risparmiando il calcolo Raycasting!

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Games – Video Surveillance – CCTV Camera – JS Script

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