unity3d

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 Game Engine – Pathfinding – NavMesh Agent

Unity 3D Game Engine – Pathfinding – NavMesh Agent

1. Create a NavMesh

2. Create EmptyObject, name it ‘targetNavigation’

3. Create a Sphere, Inspector> TOP RIGHT uncheck ‘Static’, name it ‘enemy’> Inspector> ‘Add Component’> Navigation> NavMeshAgent, setup:

– Radius: l’ingombro dell’agente

– Speed: massima velocità dell’agente (utile per i giochi di corsa!)

– Acceleration: accelerazione massima dell’agente

– Angular Speed: velocità con la quale è in grado di girare

– Stopping Distance: distanza alla quale inizia a rallentare in prossimità di ‘targetNavigation’

– Auto Traverse Off Mesh Link:

– Auto Braking: se attivo l’agente si ferma automaticamento al raggiungimento di ‘targetNavigation’

– Auto Repath: se attivo l’agente ricalcola il percorso se quello precedente non è più valido

– Height: l’altezza dell’agente

– Base Offset: offset verticale del collider dell’agente

– Obstacle Aviodance Type: High Quality – Low Quality – precisione del calcolo per schivare gli ostacoli (meno è accurato, meno risorse occupa)

– Avoidance Priority: priorità nella navigazione, un personaggio con priorità 1 avrà la precedenza (passa prima) rispetto un personaggio con priorità 2

– NavMesh Walkable: quale ‘Navigation Layer’ può attraversare

4. Select the Sphere and assign:

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

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

Unity 3D – Pathfinding – NavMesh Baking

Unity 3D Game Engine – Pathfinding – NavMesh Baking

Pathfinding or pathing is the plotting, by a computer application, of the shortest route between two points. It is a more practical variant on solving mazes.

Scene

1. MAIN TOP MENU> Gameobject> Create Other> Plane, name it ‘ground’

2. MAIN TOP MENU> Gameobject> Create Other> Sphere, name it ‘enemy’

3. MAIN TOP MENU> Gameobject> Create Other> Cube, name it ‘wall’> DRAG AND DROP inside ‘Prefab’ Folder> Duplicate to create a little labyrinth

Baking – create

To speedup Pathfinding Unity creates a simplified mesh that represents the walkable area.

4. MAIN TOP MENU> Window> Navigation

5. Hierarchy> select all walls e ground> Navigation> Object> check ‘Navigation Static’

OR

Hierarchy> select wall> Inspector> TOP RIGHT check ‘Static’

IMPORTANT: the ‘enemy’ has to have ‘Static’ unchecked.

Notice: it is necessary define the static game objects in the scene

6. Navigation> Object> Navigation Layer> Default, Not Walkable, Jump

7. Navigation> Layers> define:
– name
– cost: maggiore è il costo, più diffice è il percorso, ad esempio un marciapiede avrà cost=1, un terreno fangoso cost=3, quando verrà calcolato il percorso migliore il player guidato dal computer preferirà il percorso con un cost più basso.

8. Navigation> Bake> setup parameters:

General>
– Radius: how close a navigating character can get to a wall (quanto si può avvicinare al muro il personaggio)
– Height: the height of the area may not be reachable (altezza massima dell’area raggiungibile)
– Max Slope: the threshold of steepness where a ramp becomes a wall (oltre la pendenza definita l’area è considerata un muro)
– Step Height: any step greater than this height results in a disconnected walkable area (oltre questa altezza il personaggio viene bloccato)

General Off Mesh Links>
– Drop Height:
– Jump Distance:

Advanced
– Min Region Area: superficie minima che verra inclusa nell’area calpestabile, questo parametro è per evitare eccessivi frazionamenti della NavMesh
– With Inaccurancy%: precisione nel calcolo della larghezza
– Height Inaccurancy%: precisione nel calcolo dell’altezza
– Height Mesh:

7. Navigation> BOTTOM RIGHT> ‘Bake’, a blue NavMesk appears!

Baking – delete

Navigation> BOTTOM RIGHT> ‘Clear’, it removes the NavMesh!

By |Unity3D, Video Games Development|Commenti disabilitati su Unity 3D – Pathfinding – NavMesh Baking

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 Game Engine – Stealth Game – Double Doors – JS

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

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

–> (child) ‘door_exit_outer_left_001’
|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)

–> (child) ‘door_exit_outer_right_001’
|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)
– check ‘Require Key’, you will open this door only with a key

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