unity3d

Unity 3D Game Engine – Stealth Game – Single Doors – JS

Unity 3D Game Engine – Stealth Game – Single Doors – JS

Load prefab:
-> (parent) ‘door_generic_slide’
|Animator – Closed animation, Open animation inside are inside fbx file
|SingleDoorAnimator – uncheck Apply Root Motion – parameter bool: open – transitions: open->close close->open
|Sphere Collider – check ‘Is Trigger’ (to check player position)
|Audio Source Component (doorSwishClip + accessDeniedClip), uncheck ‘Play on Awake’
|DoorAnimation.js

–> (child) ‘door_generic_slide_panel’
|Mesh Renderer, check ‘Use Light Probes’
|Box Collider (to block the player penetration)
|Rigid Body, uncheck ‘Use Gravity’, check ‘Is Kinematic’ (to block the player penetration)

DoorAnimation.js:


#pragma strict

public var requireKey : boolean;                    // Whether or not a key is required.
public var doorSwishClip : AudioClip;               // Clip to play when the doors open or close.
public var accessDeniedClip : AudioClip;            // Clip to play when the player doesn't have the key for the door.


private var anim : Animator;                        // Reference to the animator component.
private var hash : HashIDs;                         // Reference to the HashIDs script.
private var player : GameObject;                    // Reference to the player GameObject.
private var playerInventory : PlayerInventory;      // Reference to the PlayerInventory script.
private var count : int;                            // The number of colliders present that should open the doors.


function Awake ()
{
    // Setting up the references.
    anim = GetComponent(Animator);
    hash = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent(HashIDs);
    player = GameObject.FindGameObjectWithTag(Tags.player);
    playerInventory = player.GetComponent(PlayerInventory);
}


function OnTriggerEnter (other : Collider)
{
    // If the triggering gameobject is the player...
    if(other.gameObject == player)
    {
        // ... if this door requires a key...
        if(requireKey)
        {
            // ... if the player has the key...
            if(playerInventory.hasKey)
                // ... increase the count of triggering objects.
                count++;
            else
            {
                // If the player doesn't have the key play the access denied audio clip.
                audio.clip = accessDeniedClip;
                audio.Play();
            }
        }
        else
            // If the door doesn't require a key, increase the count of triggering objects.
            count++;
    }
    // If the triggering gameobject is an enemy...
    else if(other.gameObject.tag == Tags.enemy)
    {
        // ... if the triggering collider is a capsule collider...
        if(typeof(other) == CapsuleCollider)
            // ... increase the count of triggering objects.
            count++;
    }
}


function OnTriggerExit (other : Collider)
{
    // If the leaving gameobject is the player or an enemy and the collider is a capsule collider...
    if(other.gameObject == player || (other.gameObject.tag == Tags.enemy && typeof(other) == CapsuleCollider))
        // decrease the count of triggering objects.
        count = Mathf.Max(0, count-1);
}


function Update ()
{
    // Set the open parameter.
    anim.SetBool(hash.openBool,count > 0);
    
    // If the door is opening or closing...
    if(anim.IsInTransition(0) && !audio.isPlaying)
    {
        // ... play the door swish audio clip.
        audio.clip = doorSwishClip;
        audio.Play();
    }
}

Inspector> DRAG AND DROP> variables:
– Door Swish Clip (Audio Clip)
– Access Denied Clip (Audio Clip)
– uncheck ‘Require Key’, you will open this door without a key

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Stealth Game – Single Doors – JS

Unity 3D – Stealth Game – Player Inventory – JS

Unity 3D – Stealth Game – Player Inventory – JS

Player

Select the player and attach:

PlayerInventory.js

#pragma strict

public var hasKey : boolean;

Key Card

Create a keycard object with:

– Box Collider ‘As Trigger’

– KeyPickup.js

#pragma strict

public var keyGrab : AudioClip;                         // Audioclip to play when the key is picked up.


private var player : GameObject;                        // Reference to the player.
private var playerInventory : PlayerInventory;          // Reference to the player's inventory.


function Awake ()
{
    // Setting up the references.
    player = GameObject.FindGameObjectWithTag(Tags.player);
    playerInventory = player.GetComponent(PlayerInventory);
}


function OnTriggerEnter (other : Collider)
{
    // If the colliding gameobject is the player...
    if(other.gameObject == player)
    {
        // ... play the clip at the position of the key...
        AudioSource.PlayClipAtPoint(keyGrab, transform.position);
        
        // ... the player has a key ...
        playerInventory.hasKey = true;
        
        // ... and destroy this gameobject.
        Destroy(gameObject);
    }
}
By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D – Stealth Game – Player Inventory – JS

Unity 3D – Stealth Game – Camera Movement

Unity 3D – Stealth Game – Camera Movement

Select the mainCamera and assign:

CameraMovement.js


#pragma strict

public var smooth : float = 1.5f;           // The relative speed at which the camera will catch up.


private var player : Transform;             // Reference to the player's transform.
private var relCameraPos : Vector3;         // The relative position of the camera from the player.
private var relCameraPosMag : float;        // The distance of the camera from the player.
private var newPos : Vector3;               // The position the camera is trying to reach.


function Awake ()
{
    // Setting up the reference.
    player = GameObject.FindGameObjectWithTag(Tags.player).transform;
    
    // Setting the relative position as the initial relative position of the camera in the scene.
    relCameraPos = transform.position - player.position;
    relCameraPosMag = relCameraPos.magnitude - 0.5f;
}


function FixedUpdate ()
{
    // The standard position of the camera is the relative position of the camera from the player.
    var standardPos : Vector3 = player.position + relCameraPos;
    
    // The abovePos is directly above the player at the same distance as the standard position.
    var abovePos : Vector3 = player.position + Vector3.up * relCameraPosMag;
    
    // An array of 5 points to check if the camera can see the player.
    var checkPoints : Vector3[] = new Vector3[5];
    
    // The first is the standard position of the camera.
    checkPoints[0] = standardPos;
    
    // The next three are 25%, 50% and 75% of the distance between the standard position and abovePos.
    checkPoints[1] = Vector3.Lerp(standardPos, abovePos, 0.25f);
    checkPoints[2] = Vector3.Lerp(standardPos, abovePos, 0.5f);
    checkPoints[3] = Vector3.Lerp(standardPos, abovePos, 0.75f);
    
    // The last is the abovePos.
    checkPoints[4] = abovePos;
    
    // Run through the check points...
    for(var i = 0; i < checkPoints.Length; i++)
    {
        // ... if the camera can see the player...
        if(ViewingPosCheck(checkPoints[i]))
            // ... break from the loop.
            break;
    }
    
    // Lerp the camera's position between it's current position and it's new position.
    transform.position = Vector3.Lerp(transform.position, newPos, smooth * Time.deltaTime);
    
    // Make sure the camera is looking at the player.
    SmoothLookAt();
}


function ViewingPosCheck (checkPos : Vector3) : boolean
{
    var hit : RaycastHit;
    
    // If a raycast from the check position to the player hits something...
    if(Physics.Raycast(checkPos, player.position - checkPos, hit, relCameraPosMag))
        // ... if it is not the player...
        if(hit.transform != player)
            // This position isn't appropriate.
            return false;
    
    // If we haven't hit anything or we've hit the player, this is an appropriate position.
    newPos = checkPos;
    return true;
}


function SmoothLookAt ()
{
    // Create a vector from the camera towards the player.
    var relPlayerPosition : Vector3 = player.position - transform.position;
    
    // Create a rotation based on the relative position of the player being the forward vector.
    var lookAtRotation : Quaternion = Quaternion.LookRotation(relPlayerPosition, Vector3.up);
    
    // Lerp the camera's rotation between it's current rotation and the rotation that looks at the player.
    transform.rotation = Quaternion.Lerp(transform.rotation, lookAtRotation, smooth * Time.deltaTime);
}

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

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