videogames development

Unity Game Engine – Stealth Game – Player Health – JS Script

Unity Game Engine – Stealth Game – Player Health – JS Script

Select the player object and assign:

PlayerHealth.js


#pragma strict

public var health : float = 100f;                           // How much health the player has left.
public var resetAfterDeathTime : float = 5f;                // How much time from the player dying to the level reseting.
public var deathClip : AudioClip;                           // The sound effect of the player dying.


private var anim : Animator;                                // Reference to the animator component.
private var playerMovement : PlayerMovement;                // Reference to the player movement script.
private var hash : HashIDs;                                 // Reference to the HashIDs.
private var sceneFadeInOut : SceneFadeInOut;                // Reference to the SceneFadeInOut script.
private var lastPlayerSighting : LastPlayerSighting;        // Reference to the LastPlayerSighting script.
private var timer : float;                                  // A timer for counting to the reset of the level once the player is dead.
private var playerDead : boolean;                           // A bool to show if the player is dead or not.


function Awake ()
{
    // Setting up the references.
    anim = GetComponent(Animator);
    playerMovement = GetComponent(PlayerMovement);
    hash = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent(HashIDs);
    sceneFadeInOut = GameObject.FindGameObjectWithTag(Tags.fader).GetComponent(SceneFadeInOut);
    lastPlayerSighting = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent(LastPlayerSighting);
}


function Update ()
{
    // If health is less than or equal to 0...
    if(health <= 0f)
    {
        // ... and if the player is not yet dead...
        if(!playerDead)
            // ... call the PlayerDying function.
            PlayerDying();
        else
        {
            // Otherwise, if the player is dead, call the PlayerDead and LevelReset functions.
            PlayerDead();
            LevelReset();
        }
    }
}


function PlayerDying ()
{
    // The player is now dead.
    playerDead = true;
    
    // Set the animator's dead parameter to true also.
    anim.SetBool(hash.deadBool, playerDead);
    
    // Play the dying sound effect at the player's location.
    AudioSource.PlayClipAtPoint(deathClip, transform.position);
}


function PlayerDead ()
{
    // If the player is in the dying state then reset the dead parameter.
    if(anim.GetCurrentAnimatorStateInfo(0).nameHash == hash.dyingState)
        anim.SetBool(hash.deadBool, false);
    
    // Disable the movement.
    anim.SetFloat(hash.speedFloat, 0f);
    playerMovement.enabled = false;
    
    // Reset the player sighting to turn off the alarms.
    lastPlayerSighting.position = lastPlayerSighting.resetPosition;
    
    // Stop the footsteps playing.
    audio.Stop();
}


function LevelReset ()
{
    // Increment the timer.
    timer += Time.deltaTime;
    
    //If the timer is greater than or equal to the time before the level resets...
    if(timer >= resetAfterDeathTime)
        // ... reset the level.
        sceneFadeInOut.EndScene();
}


public function TakeDamage (amount : float)
{
    // Decrement the player's health by amount.
    health -= amount;
}

By |Unity3D, Video Games Development|Commenti disabilitati su Unity Game Engine – Stealth Game – Player Health – JS Script

Unity 3D – Stealth Game – Player Movement – JS Script

Unity 3D – Stealth Game – Player Movement – JS Script

Select the player object and assign:

PlayerMovement.js

#pragma strict

public var shoutingClip : AudioClip;        // Audio clip of the player shouting.
public var turnSmoothing : float = 15f;     // A smoothing value for turning the player.
public var speedDampTime : float = 0.1f;    // The damping for the speed parameter


private var anim : Animator;                // Reference to the animator component.
private var hash : HashIDs;                 // Reference to the HashIDs.


function Awake ()
{
    // Setting up the references.
    anim = GetComponent(Animator);
    hash = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent(HashIDs);
    
    // Set the weight of the shouting layer to 1.
    anim.SetLayerWeight(1, 1f);
}


function FixedUpdate ()
{
    // Cache the inputs.
    var h : float = Input.GetAxis("Horizontal");
    var v : float = Input.GetAxis("Vertical");
    var sneak : boolean = Input.GetButton("Sneak");
    
    MovementManagement(h, v, sneak);
}


function Update ()
{
    // Cache the attention attracting input.
    var shout : boolean = Input.GetButtonDown("Attract");
    
    // Set the animator shouting parameter.
    anim.SetBool(hash.shoutingBool, shout);
    
    AudioManagement(shout);
}


function MovementManagement (horizontal : float, vertical : float, sneaking : boolean)
{
    // Set the sneaking parameter to the sneak input.
    anim.SetBool(hash.sneakingBool, sneaking);
    
    // If there is some axis input...
    if(horizontal != 0f || vertical != 0f)
    {
        // ... set the players rotation and set the speed parameter to 5.5f.
        Rotating(horizontal, vertical);
        anim.SetFloat(hash.speedFloat, 5.5f, speedDampTime, Time.deltaTime);
    }
    else
        // Otherwise set the speed parameter to 0.
        anim.SetFloat(hash.speedFloat, 0);
}


function Rotating (horizontal : float, vertical : float)
{
    // Create a new vector of the horizontal and vertical inputs.
    var targetDirection : Vector3 = new Vector3(horizontal, 0f, vertical);
    
    // Create a rotation based on this new vector assuming that up is the global y axis.
    var targetRotation : Quaternion = Quaternion.LookRotation(targetDirection, Vector3.up);
    
    // Create a rotation that is an increment closer to the target rotation from the player's rotation.
    var newRotation : Quaternion = Quaternion.Lerp(rigidbody.rotation, targetRotation, turnSmoothing * Time.deltaTime);
    
    // Change the players rotation to this new rotation.
    rigidbody.MoveRotation(newRotation);
}


function AudioManagement (shout : boolean)
{
    // If the player is currently in the run state...
    if(anim.GetCurrentAnimatorStateInfo(0).nameHash == hash.locomotionState)
    {
        // ... and if the footsteps are not playing...
        if(!audio.isPlaying)
            // ... play them.
            audio.Play();
    }
    else
        // Otherwise stop the footsteps.
        audio.Stop();
    
    // If the shout input has been pressed...
    if(shout)
        // ... play the shouting clip where we are.
        AudioSource.PlayClipAtPoint(shoutingClip, transform.position);
}
By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D – Stealth Game – Player Movement – JS Script

Unity 3D – Stealth Game – Player Animator Controller

Unity 3D – Stealth Game – Player Animator Controller

1. Projects> Animator folder> Create> Animator Controller> name it ‘PlayerAnimator’

2. MAIN TOP MENU> Window> Animator

3. Animator> BOTTOM LEFT> Parameters

– Speed -> float (velocità)
– Sneaking -> bool (spiare)
– Dead -> bool (morte)
– Shouting -> bool (urlare)

4. Project> Animations> Humanoid> humanoid_idle (inattivo) (box blu)> Idle (animazione) DRAG AND DROP inside Animator window

5. Hierarchy> char_ethan> Inspector> Animator> Controller DRAG ‘PlayerAnimator’ was created at 1.

6. Play

Idle -> Walk -> Run | Run -> Walk -> Idle

7. Animator> RMB> Create State> From New Blend Tree> Inspector> rename it ‘Locomotion’

8. Animator> LMB Double Click> Blend Tree (notare che il layer attuale è Base Layer> Locomotion)

> Inspector, rename it ‘Locomotion’

> Inspector> + Add Motion Field> little circle icon> Walk

> Inspector> + Add Motion Field> little circle icon> Run

> Inspector> Automate Threshold uncheck (soglia automatica)

> Inspector> Compute Threshold> Speed

9. Animator>

> Base Layer (torno al livello base)> ‘Idle’ RMB> Make Transition> DRAG over ‘Locomotion’

> LMB over the Transition Line to select it> Inspector>

>Conditions> Speed> Greater> 0.1

>Conditions> +> Sneaking> false

10. Animator>

> Base Layer (torno al livello base)> ‘Locomotion’ RMB> Make Transition> DRAG over ‘Idle’

> LMB over the Transition Line to select it> Inspector>

>Conditions> Speed> Less> 0.1

Any State -> Die

Create a Transition from ‘Any State’ -> ‘Dying’

Conditions> Dead> true

NOTA BENE:
‘Any State’ significa che si può arrivare alla morte da qualsiasi stato, senza dover creare transizioni complicate dagli altri stati.

Avatar Mask

The Avatar Mask is an additional layer of animation.

1. Project> Animations folder> Create> Avatar Mask, name it ‘PlayerShoutingMask’> Inspector> Humanoid> deselect (they will turn red) the body parts you do not want modify with the Avatar Mask.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D – Stealth Game – Player Animator Controller

Unity 3D – Stealth Game – Player Setup

Unity 3D – Stealth Game – Player Setup

1. DRAG the model into the scene from Projects to Hierarchy

2. ‘Add Component’> Physic> Capsule Collider

3. ‘Add Component’> Audio> Audio Source> DRAG player_footsteps.wav
– ‘Play on Awake’ uncheck
– ‘Loop’ check
– ‘Volumes’ = 0.1 We don’t want footsteps to be too intrusive

– Remove the Audio Listener of camera_main
– Select the player> ‘Add Component’> Audio> Audio Listener

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

Unity 3D – Stealth Game – Laser Grids

Unity 3D – Stealth Game – Laser Grids

Laser Grid

1. Put the 3D ‘Laser Grid’ mesh inside the Scene, it needs:

– ‘Add component’> Physic> Box Collider> check ‘As Trigger’ to detect collision with the player

– ‘Add component’> AUdio> Audio Source to sote the SFX laser effect> check ‘Play an Awake’, check ‘Loop’, 3D Sound Settings> Min Distance> 1.5 (you will listen the SFX if the player reaches 1.5 unity of distance from the Laser Grid)

– ‘Add component’> Rendering> Light, to create a light effect, setup
– ‘Range’
– ‘Intensity’ to limitate the effect
– ‘Lightmapping’ Realtime Only, non deve rimanere impressa nella texture precalcolata

– Attach the scripts:

LaserBlinking.js

#pragma strict

public var onTime : float;          // Amount of time in seconds the laser is on for.
public var offTime : float;         // Amount of time in seconds the laser is off for.


private var timer : float;          // Timer to time the laser blinking.


function Update ()
{
    // Increment the timer by the amount of time since the last frame.
    timer += Time.deltaTime;
    
    // If the beam is on and the onTime has been reached...
    if(renderer.enabled && timer >= onTime)
        // Switch the beam.
        SwitchBeam();
    
    // If the beam is off and the offTime has been reached...
    if(!renderer.enabled && timer >= offTime)
        // Switch the beam.
        SwitchBeam();
}


function SwitchBeam ()
{
    // Reset the timer.
    timer = 0f;
    
    // Switch whether the beam and light are on or off.
    renderer.enabled = !renderer.enabled;
    light.enabled = !light.enabled;
}

LaserPlayerDetection.js

#pragma strict

private var player : GameObject;                            // Reference to the player.
private var lastPlayerSighting : LastPlayerSighting;        // Reference to the global last sighting of the player.


function Awake ()
{
    // Setting up references.
    player = GameObject.FindGameObjectWithTag(Tags.player);
    lastPlayerSighting = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent(LastPlayerSighting);
}


function OnTriggerStay(other : Collider)
{
    // If the beam is on...
    if(renderer.enabled)
        // ... and if the colliding gameobject is the player...
        if(other.gameObject == player)
            // ... set the last global sighting of the player to the colliding object's position.
            lastPlayerSighting.position = other.transform.position;
}

Inspector setup
– var OnTime = 1.5
– var OffTime = 1.5

2. Hierarchy> ‘Laser Grid’ GameObject DRAG AND DROP over Project> Prefabs

3. Delete the original ‘Laser Grid’ GameObject and you can start use Prefabs to instantiate.

Switch Unit

1. Add the Mesh of Switch Unit

2. Add Sphere Collider ‘As Trigger’ to detect the player

3. Attach LaserSwitchDeactivation.js

#pragma strict

public var laser : GameObject;              // Reference to the laser that can we turned off at this switch.
public var unlockedMat : Material;          // The screen's material to show the laser has been unloacked.

private var player : GameObject;            // Reference to the player.


function Awake ()
{
    // Setting up the reference.
    player = GameObject.FindGameObjectWithTag(Tags.player);
}


function OnTriggerStay (other : Collider)
{
    // If the colliding gameobject is the player...
    if(other.gameObject == player)
        // ... and the switch button is pressed...
        if(Input.GetButton("Switch"))
            // ... deactivate the laser.
            LaserDeactivation();
}


function LaserDeactivation ()
{
    // Deactivate the laser GameObject.
    laser.SetActive(false);
    
    // Store the renderer component of the screen.
    var screen : Renderer = transform.Find("prop_switchUnit_screen_001").renderer;
    
    // Change the material of the screen to the unlocked material.
    screen.material = unlockedMat;
    
    // Play switch deactivation audio clip.
    audio.Play();
}

Inspector DRAG AND DROP inside:
– var ‘laser’ -> the Laser Grid you want deactivate
– var ‘unlockedMat’ -> render Switch Unit material as unlocked

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