programming

Unity 3D Game Engine – Pathfinding – Offmesh Links

Unity 3D Game Engine – Pathfinding – Offmesh Links

With Offmesh Links you can link two or more NavMesh.

1. Create EmptyObject, name it ‘targetNavigation’

2. Create a Sphere, name it ‘enemy’ with:
– NavMeshAgent
– SimpleAgentScript.js

SimpleAgentScript.js:


#pragma strict


    public var target : Transform; // inside Inspector assign the Target object
	private var agent: NavMeshAgent;
	
	function Start () {
		agent = GetComponent.<NavMeshAgent>();
	}
	function Update () {

				agent.SetDestination(target.position);
					
	}

Inspector> DRAG AND DROP over variable Target the ‘targetNavigation’ object

Automatic

3. Create 2 Box

4. Select the 2 Box (CTRL+LMB)>

> Navigation> Object> check OffMeshLink Generation

> Navigation> Bake> Generated Off Mesh Links>

– Jump Distance = 10 (maximum agent jump distance)

– Drop Height = 10 (maximum agent drop height)

> Bake

Manually

3. Create 2 Box, name it ‘start’ and ‘end’

4. Select the 2 Box (CTRL+LMB)>

> Navigation> Object> uncheck OffMeshLink Generation

> Navigation> Bake> Generated Off Mesh Links>

– Jump Distance = 10 (maximum agent jump distance)

– Drop Height = 10 (maximum agent drop height)

> Bake

4. Inspector> Select ‘start’> ‘Add Component’> Navigation> OffMesh Links>

OffMesh Link> Hierarchy

– DRAG AND DROP ‘start’ game object over public variable ‘Start’

– DRAG AND DROP ‘end’ game object over public variable ‘End’

> you do not need to re-Bake

The Character not jumping!

Try to re-setup Navigation> Bake> General> – Height
– Step Height

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D Game Engine – Pathfinding – Offmesh Links

Unity 3D – Stealth Game – The lift – JS

Unity 3D – Stealth Game – The lift – JS

Load prefab:
-> (parent) ‘prop_lift_exit’
|Box Collider, check ‘Is Trigger’, uncheck ‘Use Gravity’, check ‘Is Kinematic’ (to detect the player position)
|Audio Source, uncheck ‘Play on Awake’, check ‘Loop’ (lift raise noise)
|LiftDoorsTracking.js
|LiftTrigger.js

–> (child) ‘door_exit_inner’
—> (2nd child) ‘prop_lift_collider’
|Mesh Collider (to block the player penetration)

—> (2nd child) ‘door_exit_inner_left_001’
|Mesh Renderer, check ‘Use Light Probes’

—> (2nd child) ‘door_exit_inner_right_001’
|Mesh Renderer, check ‘Use Light Probes’

–> (child) ‘door_lift_exit_carriage’
|Mesh Renderer, check ‘Use Light Probes’

–> (child) ‘door_lift_exit_mechanism’
|Mesh Renderer, check ‘Use Light Probes’

–> (child) ‘door_lift_exit_wires’
|Mesh Renderer, check ‘Use Light Probes’

LiftDoorsTracking.js


#pragma strict

public var doorSpeed : float = 7f;          // How quickly the inner doors will track the outer doors.


private var leftOuterDoor : Transform;      // Reference to the transform of the left outer door.
private var rightOuterDoor : Transform;     // Reference to the transform of the right outer door.
private var leftInnerDoor : Transform;      // Reference to the transform of the left inner door.
private var rightInnerDoor : Transform;     // Reference to the transform of the right inner door.
private var leftClosedPosX : float;         // The initial x component of position of the left doors.
private var rightClosedPosX : float;        // The initial x component of position of the right doors.


function Awake ()
{
    // Setting up the references.
    leftOuterDoor = GameObject.Find("door_exitOuter_left_001").transform;
    rightOuterDoor = GameObject.Find("door_exitOuter_right_001").transform;
    leftInnerDoor = GameObject.Find("door_exitInner_left_001").transform;
    rightInnerDoor = GameObject.Find("door_exitInner_right_001").transform;
    
    // Setting the closed x position of the doors.
    leftClosedPosX = leftInnerDoor.position.x;
    rightClosedPosX = rightInnerDoor.position.x;
}


function MoveDoors (newLeftXTarget : float, newRightXTarget : float)
{
    // Create a float that is a proportion of the distance from the left inner door's x position to it's target x position.
    var newX : float = Mathf.Lerp(leftInnerDoor.position.x, newLeftXTarget, doorSpeed * Time.deltaTime);
    
    // Move the left inner door to it's new position proportionally closer to it's target.
    leftInnerDoor.position = new Vector3(newX, leftInnerDoor.position.y, leftInnerDoor.position.z);
    
    // Reassign the float for the right door's x position.
    newX = Mathf.Lerp(rightInnerDoor.position.x, newRightXTarget, doorSpeed * Time.deltaTime);
    
    // Move the right inner door similarly.
    rightInnerDoor.position = new Vector3(newX, rightInnerDoor.position.y, rightInnerDoor.position.z);
}


public function DoorFollowing ()
{
    // Move the inner doors towards the outer doors.
    MoveDoors(leftOuterDoor.position.x, rightOuterDoor.position.x);
}


public function CloseDoors ()
{
    // Move the inner doors towards their closed position.
    MoveDoors(leftClosedPosX, rightClosedPosX);
}

LiftTrigger.js


#pragma strict

public var timeToDoorsClose : float = 2f;           // Time since the player entered the lift before the doors close.
public var timeToLiftStart : float = 3f;            // Time since the player entered the lift before it starts to move.
public var timeToEndLevel : float = 6f;             // Time since the player entered the lift before the level ends.
public var liftSpeed : float = 3f;                  // The speed at which the lift moves.


private var player : GameObject;                    // Reference to the player.
private var playerAnim : Animator;                  // Reference to the players animator component.
private var hash : HashIDs;                         // Reference to the HashIDs script.
private var camMovement : CameraMovement;           // Reference to the camera movement script.
private var sceneFadeInOut : SceneFadeInOut;        // Reference to the SceneFadeInOut script.
private var liftDoorsTracking : LiftDoorsTracking;  // Reference to LiftDoorsTracking script.
private var playerInLift : boolean;                 // Whether the player is in the lift or not.
private var timer : float;                          // Timer to determine when the lift moves and when the level ends.


function Awake ()
{
    // Setting up references.
    player = GameObject.FindGameObjectWithTag(Tags.player);
    playerAnim = player.GetComponent(Animator);
    hash = GameObject.FindGameObjectWithTag(Tags.gameController).GetComponent(HashIDs);
    camMovement = Camera.main.gameObject.GetComponent(CameraMovement);
    sceneFadeInOut = GameObject.FindGameObjectWithTag(Tags.fader).GetComponent(SceneFadeInOut);
    liftDoorsTracking = GetComponent(LiftDoorsTracking);
}


function OnTriggerEnter (other : Collider)
{
    // If the colliding gameobject is the player...
    if(other.gameObject == player)
        // ... the player is in the lift.
        playerInLift = true;
}


function OnTriggerExit (other : Collider)
{
    // If the player leaves the trigger area...
    if(other.gameObject == player)
    {
        // ... reset the timer, the player is no longer in the lift and unparent the player from the lift.
        playerInLift = false;
        timer = 0;
    }
}


function Update ()
{
    // If the player is in the lift...
    if(playerInLift)
        // ... activate the lift.
        LiftActivation();
    
    // If the timer is less than the time before the doors close...
    if(timer < timeToDoorsClose)
        // ... the inner doors should follow the outer doors.
        liftDoorsTracking.DoorFollowing();
    else
        // Otherwise the doors should close.
        liftDoorsTracking.CloseDoors();
}


function LiftActivation ()
{
    // Increment the timer by the amount of time since the last frame.
    timer += Time.deltaTime;
    
    // If the timer is greater than the amount of time before the lift should start...
    if(timer >= timeToLiftStart)
    {
        // ... stop the player and the camera moving and parent the player to the lift.
        playerAnim.SetFloat(hash.speedFloat,0f);
        camMovement.enabled = false;
        player.transform.parent = transform;
        
        // Move the lift upwards.
        transform.Translate(Vector3.up * liftSpeed * Time.deltaTime);
        
        // If the audio clip isn't playing...
        if(!audio.isPlaying)
            // ... play the clip.
            audio.Play();
        
        // If the timer is greater than the amount of time before the level should end...
        if(timer >= timeToEndLevel)
            // ... call the EndScene function.
            sceneFadeInOut.EndScene();
    }
}

Notice: when the lift raises, the player will be child of the lift.

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D – Stealth Game – The lift – 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