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 – HashIDs

Unity 3D – Stealth Game – HashIDs

Here we store the hash tags for various strings used in our animators.

1. Hierarchy> ‘gameController’


#pragma strict

// Here we store the hash tags for various strings used in our animators.
public var dyingState : int;
public var locomotionState : int;
public var shoutState : int;
public var deadBool : int;
public var speedFloat : int;
public var sneakingBool : int;
public var shoutingBool : int;
public var playerInSightBool : int;
public var shotFloat : int;
public var aimWeightFloat : int;
public var angularSpeedFloat : int;
public var openBool : int;


function Awake ()
{
    dyingState = Animator.StringToHash("Base Layer.Dying");
    locomotionState = Animator.StringToHash("Base Layer.Locomotion");
    shoutState = Animator.StringToHash("Shouting.Shout");
    deadBool = Animator.StringToHash("Dead");
    speedFloat = Animator.StringToHash("Speed");
    sneakingBool = Animator.StringToHash("Sneaking");
    shoutingBool = Animator.StringToHash("Shouting");
    playerInSightBool = Animator.StringToHash("PlayerInSight");
    shotFloat = Animator.StringToHash("Shot");
    aimWeightFloat = Animator.StringToHash("AimWeight");
    angularSpeedFloat = Animator.StringToHash("AngularSpeed");
    openBool = Animator.StringToHash("Open");
}

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

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