Example #1
0
    //Update HP bar rotations

    protected virtual void Navigate()
    {
        //FROM DEAD EARTH TUTORIAL
        //**************************************************************************************
        HasPath     = navAgent.hasPath;
        PathPending = navAgent.pathPending;
        PathStale   = navAgent.isPathStale;
        PathStatus  = navAgent.pathStatus;

        Vector3 localDesiredVelocity = transform.InverseTransformVector(navAgent.desiredVelocity);
        float   angle = Mathf.Atan2(localDesiredVelocity.x, localDesiredVelocity.z) * Mathf.Rad2Deg;

        smoothAngle = Mathf.MoveTowardsAngle(smoothAngle, angle, 80.0f * Time.deltaTime);

        float speed = localDesiredVelocity.z;

        animator.SetFloat(angleHash, smoothAngle);
        animator.SetFloat(speedHash, speed, 0.1f, Time.deltaTime);

        if (navAgent.desiredVelocity.sqrMagnitude > Mathf.Epsilon)
        {
            if (!MixedMode || (MixedMode && Mathf.Abs(angle) < 80f && animator.GetCurrentAnimatorStateInfo(0).IsName("Base Layer.Locomotion")))
            {
                Quaternion lookRotation = Quaternion.LookRotation(navAgent.desiredVelocity, Vector3.up);
                transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, 5.0f * Time.deltaTime);
            }
        }

        if (PathStatus == NavMeshPathStatus.PathInvalid && !PathPending || PathStatus == NavMeshPathStatus.PathPartial && !PathPending)
        {
            navAgent.SetDestination(target);
        }
    }
Example #2
0
 public void Update()
 {
     pathStatus = navMeshAgent.pathStatus;
     HandleRotation();
     MoveAgent();
     EnemyStateMachine();
 }
	// Update is called once per frame
	void Update () {
		if (agent.enabled) agent.SetDestination (targetPosition.position);
		//destination = agent.destination; //For debugging with the Inspector
		destination = agent.path.corners[1];
		status = agent.path.status;
		data = agent.nextOffMeshLinkData;

		if (agent.isOnOffMeshLink && linkTime == 0) {
			linkTime = Time.time;
		}

		if (controller.controllable) {
			if (Vector3.Distance (targetPosition.position, gameObject.transform.position) > agent.stoppingDistance) {
				//controller.xin = (targetPosition.position.x - gameObject.transform.position.x);
				//controller.zin = (targetPosition.position.z - gameObject.transform.position.z);
				controller.xin = Mathf.Max (Mathf.Min ((agent.path.corners [1].x - gameObject.transform.position.x), 1f), -1f);
				controller.zin = Mathf.Max (Mathf.Min ((agent.path.corners [1].z - gameObject.transform.position.z), 1f), -1f);
			} else
				controller.xin = controller.zin = 0;
			
			if (agent.path.corners [1].y - gameObject.transform.position.y > 0.5) {
				agent.enabled = false;
				controller.jumpin = 1;

			} else if (controller.GroundCheck ()) {
				agent.enabled = true;
				controller.jumpin = 0;
			}

			if (Time.time - linkTime >= .5 && linkTime != 0) {
				agent.enabled = false;
				linkTime = 0;
			}
		} else {
			controller.xin = controller.zin = 0;
		}

		var nav = GetComponent<NavMeshAgent>(); //Debug Path Line
		if( nav == null || nav.path == null )
			return;
		
		var line = this.GetComponent<LineRenderer>();
		if( line == null )
		{
			line = this.gameObject.AddComponent<LineRenderer>();
			line.material = new Material( Shader.Find( "Sprites/Default" ) ) { color = Color.yellow };
			line.SetWidth( 0.5f, 0.5f );
			line.SetColors( Color.yellow, Color.yellow );
		}
		
		var path = nav.path;
		
		line.SetVertexCount( path.corners.Length );
		
		for( int i = 0; i < path.corners.Length; i++ )
		{
			line.SetPosition( i, path.corners[ i ] );
		}

	}
Example #4
0
 // Update is called once per frame
 void Update()
 {
     if (DestinationPicker.newDestination)
     {
         state = State.WALKING;
         // Debug.Log("dest ? " + DestinationPicker.newDestination + " " + DestinationPicker.destination);
         navMeshAgent.destination = DestinationPicker.destination;
     }
     if (state == State.WALKING)
     {
         NavMeshPathStatus status = navMeshAgent.pathStatus;
         float             dist   = navMeshAgent.remainingDistance;
         if (!navMeshAgent.pathPending &&
             status == NavMeshPathStatus.PathComplete &&
             dist <= navMeshAgent.stoppingDistance * 2)
         {
             state = State.READY;
             DestinationPicker.newDestination = false;
             if (PointNClickable.clicked != null)
             {
                 PointNClickable.clicked.PreClick();
                 AudioSource sfx = PointNClickable.clicked.Interact();
                 if (sfx != null)
                 {
                     sfx.transform.position = PointNClickable.clicked.transform.position;
                     sfx.Play();
                 }
                 PointNClickable.clicked = null;
             }
         }
     }
 }
Example #5
0
    protected virtual void Update()
    {
        status = agent.pathStatus;
//		switch(currentState)
//		{
//		case UnitState.Standby: StandbyState(); break;
//		case UnitState.Move: MoveState(); break;
//		case UnitState.Chase: ChaseState(); break;
//		case UnitState.Attack: AttackState(); break;
//		case UnitState.Dead: DeadState(); break;
//		}

        switch (currentState)
        {
        case UnitState.Standby: StandbyState(); break;

        case UnitState.Hold: HoldState(); break;

        case UnitState.Move: MoveState(); break;

        case UnitState.Chase: ChaseState(); break;

        case UnitState.Attack: AttackState(); break;

        case UnitState.Dead: DeadState(); break;

        case UnitState.None: break;
        }
    }
Example #6
0
    // ---------------------------------------------------------
    // Name	:	Update
    // Desc	:	Called each frame by Unity
    // ---------------------------------------------------------
    void Update()
    {
        // Copy NavMeshAgents state into inspector visible variables
        HasPath     = _navAgent.hasPath;
        PathPending = _navAgent.pathPending;
        PathStale   = _navAgent.isPathStale;
        PathStatus  = _navAgent.pathStatus;

        // If agent is on an offmesh link then perform a jump
        if (_navAgent.isOnOffMeshLink)
        {
            StartCoroutine(Jump(1.0f));
            return;
        }

        // If we don't have a path and one isn't pending then set the next
        // waypoint as the target, otherwise if path is stale regenerate path
        if ((_navAgent.remainingDistance <= _navAgent.stoppingDistance && !PathPending) || PathStatus == NavMeshPathStatus.PathInvalid /*|| PathStatus==NavMeshPathStatus.PathPartial*/)
        {
            SetNextDestination(true);
        }
        else
        if (_navAgent.isPathStale)
        {
            SetNextDestination(false);
        }
    }
Example #7
0
    // Update is called once per frame
    void Update()
    {
        HasPath     = _navAgent.hasPath;
        PathPending = _navAgent.pathPending;
        PathStale   = _navAgent.isPathStale;
        PathStatus  = _navAgent.pathStatus;
        float stopDistance       = _navAgent.stoppingDistance;
        bool  destinationReached = _navAgent.remainingDistance <= stopDistance; // Distance to destination is zero. Needs new path

        if (_navAgent.isOnOffMeshLink)
        {
            StartCoroutine(Jump(1.0f));
            return;
        }


        if ((destinationReached && !PathPending) || (PathStatus == NavMeshPathStatus.PathInvalid))
        {
            SetNextDestination(true);
        }
        else if (_navAgent.isPathStale)
        {
            SetNextDestination(false);
        }
    }
Example #8
0
    // Update is called once per frame
    void Update()
    {
        HasPath     = _navAgent.hasPath;
        PathPending = _navAgent.pathPending;
        PathStale   = _navAgent.isPathStale;
        PathStatus  = _navAgent.pathStatus;

        if (_navAgent.isOnOffMeshLink)
        {
            StartCoroutine(Jump(1.0f));
            return;
        }

        // If we don't have a path and one isn't pending then set the next
        // waypoint as the target, otherwise if path is stale regenerate path
        if ((_navAgent.remainingDistance <= _navAgent.stoppingDistance && !PathPending) || PathStatus == NavMeshPathStatus.PathInvalid)
        {
            SetNextDestination(true);
        }
        else
        // regenerate destination if path is stale
        if (_navAgent.isPathStale)
        {
            SetNextDestination(false);
        }
    }
Example #9
0
    // ---------------------------------------------------------
    // Name	:	Update
    // Desc	:	Called each frame by Unity
    // ---------------------------------------------------------
    void Update()
    {
        int turnOnSpot;

        // Copy NavMeshAgents state into inspector visible variables
        HasPath     = _navAgent.hasPath;
        PathPending = _navAgent.pathPending;
        PathStale   = _navAgent.isPathStale;
        PathStatus  = _navAgent.pathStatus;

        // Perform corss product on forard vector and desired velocity vector. If both inputs are Unit length
        // the resulting vector's magnitude will be Sin(theta) where theta is the angle between the vectors.
        Vector3 cross = Vector3.Cross(transform.forward, _navAgent.desiredVelocity.normalized);

        // If y component is negative it is a negative rotation else a positive rotation
        float horizontal = (cross.y < 0) ? -cross.magnitude : cross.magnitude;

        // Scale into the 2.32 range for our animator
        horizontal = Mathf.Clamp(horizontal * 2.32f, -2.32f, 2.32f);

        // If we have slowed down and the angle between forward vector and desired vector is greater than 10 degrees
        if (_navAgent.desiredVelocity.magnitude < 1.0f && Vector3.Angle(transform.forward, _navAgent.steeringTarget - transform.position) > 10.0f)
        {
            // Stop the nav agent (approx) and assign either -1 or +1 to turnOnSpot based on sign on horizontal
            _navAgent.speed = 0.1f;
            turnOnSpot      = (int)Mathf.Sign(horizontal);
        }
        else
        {
            // Otherwise it is a small angle so set Agent's speed to normal and reset turnOnSpot
            _navAgent.speed = _originalMaxSpeed;
            turnOnSpot      = 0;
        }

        // Send the data calculated above into the animator parameters
        _animator.SetFloat("Horizontal", horizontal, 0.1f, Time.deltaTime);
        _animator.SetFloat("Vertical", _navAgent.desiredVelocity.magnitude, 0.1f, Time.deltaTime);
        _animator.SetInteger("TurnOnSpot", turnOnSpot);

        // If agent is on an offmesh link then perform a jump

        /*if (_navAgent.isOnOffMeshLink)
         *      {
         *              StartCoroutine( Jump( 1.0f) );
         *              return;
         *      }*/

        // If we don't have a path and one isn't pending then set the next
        // waypoint as the target, otherwise if path is stale regenerate path
        if ((_navAgent.remainingDistance <= _navAgent.stoppingDistance && !PathPending) || PathStatus == NavMeshPathStatus.PathInvalid /*|| PathStatus==NavMeshPathStatus.PathPartial*/)
        {
            SetNextDestination(true);
        }
        else
        if (_navAgent.isPathStale)
        {
            SetNextDestination(false);
        }
    }
    static int IntToEnum(IntPtr L)
    {
        int arg0            = (int)LuaDLL.lua_tonumber(L, 1);
        NavMeshPathStatus o = (NavMeshPathStatus)arg0;

        LuaScriptMgr.Push(L, o);
        return(1);
    }
Example #11
0
    private void Update()
    {
        NavMeshPathStatus status = agente.pathStatus;

        //tDistancia.text = "Distancia a la meta: " + agente.remainingDistance;
        tDistancia.text = "Distancia a la meta: " + Vector3.Distance(agente.pathEndPosition, transform.position);
        //Debug.Log("Estatus ruta: " +status.ToString());
        agente.SetDestination(meta.position);
    }
 public void In(
     [FriendlyName("Agent", "The NavMeshAgent agent.")] NavMeshAgent agent,
     [FriendlyName("Destination", "The Destination to navigate towards.")] out Vector3 destination,
     [FriendlyName("Stopping Distance", "Stop within this distance from the target position.")] out float stoppingDistance,
     [FriendlyName("Velocity", "The current velocity of the NavMeshAgent component.")] out Vector3 velocity,
     [FriendlyName("Next Position", "The next position on the path.")] out Vector3 nextPosition,
     [FriendlyName("Steering Target", "The current steering target - usually the next corner or end point of the current path. (Read Only)")] out Vector3 steeringTarget,
     [FriendlyName("Desired Velocity", "The  desired velocity of the agent including any potential contribution from avoidance. (Read Only)")] out Vector3 desiredVelocity,
     [FriendlyName("Remaining Distance", "Remaining distance along the current path - or infinity when not known. (Read Only)")] out float remainingDistance,
     [FriendlyName("Base Offset", "The relative vertical displacement of the owning GameObject.")] out float baseOffset,
     [FriendlyName("Is On Off Mesh Link", "Is agent currently positioned on an OffMeshLink. (Read Only)")] out bool isOnOffMeshLink,
     [FriendlyName("Current Off Mesh Link Data", "The current OffMeshLinkData.")] out OffMeshLinkData currentOffMeshLinkData,
     [FriendlyName("Auto Traverse Off Mesh Link", "Automate movement onto and off of OffMeshLinks.")] out bool autoTraverseOffMeshLink,
     [FriendlyName("Auto Repath", "Attempt to acquire a new path if the existing path becomes invalid or if the agent reaches the end of a partial and stale path.")] out bool autoRepath,
     [FriendlyName("Has Path", "Does the agent currently have a path. (Read Only)")] out bool hasPath,
     [FriendlyName("Path Pending", "A path is being computed, but not yet ready. (Read Only)")] out bool pathPending,
     [FriendlyName("Is Path Stale", "Is the current path stale. (Read Only) \n\nWhen true, the path may no longer be valid or optimal. This flag will be set if: there are any changes to the walkableMask, if any OffMeshLink is enabled or disabled, or if the costs for the NavMeshLayers have been changed.")] out bool isPathStale,
     [FriendlyName("Path Status", "Query the state of the current path.")] out NavMeshPathStatus pathStatus,
     [FriendlyName("Path", "Set or get a copy of the current path.")] out NavMeshPath path,
     [FriendlyName("Walkable Mask", "Specifies which NavMesh layers are passable (bitfield). Changing walkableMask will make the path stale (see isPathStale)")] out int walkableMask,
     [FriendlyName("Speed", "Maximum movement speed.")] out float speed,
     [FriendlyName("Angular Speed", "Maximum rotation speed in (deg/s).")] out float angularSpeed,
     [FriendlyName("Acceleration", "Maximum acceleration.")] out float acceleration,
     [FriendlyName("Update Position", "Should the agent update the transform position.")] out bool updatePosition,
     [FriendlyName("Update Rotation", "Should the agent update the transform orientation.")] out bool updateRotation,
     [FriendlyName("Radius", "Agent avoidance radius.")] out float radius,
     [FriendlyName("Height", "Agent height.")] out float height,
     [FriendlyName("Obstacle Avoidance Type", "The level of quality of avoidance.")] out ObstacleAvoidanceType obstacleAvoidanceType
     )
 {
     destination             = agent.destination;
     stoppingDistance        = agent.stoppingDistance;
     velocity                = agent.velocity;
     nextPosition            = agent.nextPosition;
     steeringTarget          = agent.steeringTarget;
     desiredVelocity         = agent.desiredVelocity;
     remainingDistance       = agent.remainingDistance;
     baseOffset              = agent.baseOffset;
     isOnOffMeshLink         = agent.isOnOffMeshLink;
     currentOffMeshLinkData  = agent.currentOffMeshLinkData;
     autoTraverseOffMeshLink = agent.autoTraverseOffMeshLink;
     autoRepath              = agent.autoRepath;
     hasPath               = agent.hasPath;
     pathPending           = agent.pathPending;
     isPathStale           = agent.isPathStale;
     pathStatus            = agent.pathStatus;
     path                  = agent.path;
     walkableMask          = agent.walkableMask;
     speed                 = agent.speed;
     angularSpeed          = agent.angularSpeed;
     acceleration          = agent.acceleration;
     updatePosition        = agent.updatePosition;
     updateRotation        = agent.updateRotation;
     radius                = agent.radius;
     height                = agent.height;
     obstacleAvoidanceType = agent.obstacleAvoidanceType;
 }
 void OnDestinationArrive()
 {
     if (onDestinationArrive != null)
     {
         onDestinationArrive();
     }
     // endEventPlayerPlay.EndPlay("end nav");
     // endEventPlayerPlay = null;
     pathStatus = NavMeshPathStatus.PathInvalid;
 }
        void FindRandomPointPatrol()
        {
            Vector3 randomPosition = Random.insideUnitSphere * wanderArea;

            randomPosition.y = transform.position.y;

            agent.SetDestination(randomPosition);

            navMeshPathStatus = agent.pathStatus;
            pathPending       = agent.pathPending;
        }
Example #15
0
    // ---------------------------------------------------------
    // Name	:	Update
    // Desc	:	Called each frame by Unity
    // ---------------------------------------------------------
    void Update()
    {
        // Copy NavMeshAgents state into inspector visible variables
        hasPath     = agent.hasPath;
        pathPending = agent.pathPending;
        pathStale   = agent.isPathStale;
        pathStatus  = agent.pathStatus;

        // Transform agents desired velocity into local space
        Vector3 localDesiredVelocity = transform.InverseTransformVector(agent.desiredVelocity);

        // Get angle in degrees we need to turn to reach the desired velocity direction
        float angle = Mathf.Atan2(localDesiredVelocity.x, localDesiredVelocity.z) * Mathf.Rad2Deg;

        // Smoothly interpolate towards the new angle
        smoothangle = Mathf.MoveTowardsAngle(smoothangle, angle, 80.0f * Time.deltaTime);

        // Speed is simply the amount of desired velocity projected onto our own forward vector
        float speed = localDesiredVelocity.z;

        // Set animator parameters
        animator.SetFloat("Angle", smoothangle);
        animator.SetFloat("Speed", speed, 0.1f, Time.deltaTime);

        if (agent.desiredVelocity.sqrMagnitude > Mathf.Epsilon)
        {
            if (!mixedMode ||
                (mixedMode && Mathf.Abs(angle) < 80.0f && animator.GetCurrentAnimatorStateInfo(0).IsName("Base Layer.Locomotion")))
            {
                Quaternion lookRotation = Quaternion.LookRotation(agent.desiredVelocity, Vector3.up);
                transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, 5.0f * Time.deltaTime);
            }
        }

        // If agent is on an offmesh link then perform a jump

        /*if (_navAgent.isOnOffMeshLink)
         *      {
         *              StartCoroutine( Jump( 1.0f) );
         *              return;
         *      }*/

        // If we don't have a path and one isn't pending then set the next
        // waypoint as the target, otherwise if path is stale regenerate path
        if ((agent.remainingDistance <= agent.stoppingDistance && !pathPending) || pathStatus == NavMeshPathStatus.PathInvalid /*|| PathStatus==NavMeshPathStatus.PathPartial*/)
        {
            SetNextDestination(true);
        }
        else
        if (agent.isPathStale)
        {
            SetNextDestination(false);
        }
    }
Example #16
0
        private void Update()
        {
#if UNITY_EDITOR
            DebugRenderPath();
#endif

            _pathStatus  = _agent.pathStatus;
            _pathPending = _agent.pathPending;
            _hasPath     = _agent.hasPath;
            _isPathStale = _agent.isPathStale;
        }
Example #17
0
 public void DisableAgent()
 {
     if (sender != null)
     {
         pathStatus = NavMeshPathStatus.PathInvalid;
         ServerSend.ActivatePlayerMovement(sender.playerCharacter.id, sender.playerInstance.transform.position);
         player        = null;
         sender        = null;
         agent.enabled = false;
     }
 }
 public void In(
     [FriendlyName("Agent", "The NavMeshAgent you wish to get the current path from.")] NavMeshAgent agent,
     [FriendlyName("Path", "The agent's current NavMeshPath.")] out NavMeshPath path,
     [FriendlyName("Corners", "Corner points of path. (Read Only)"), SocketState(false, false)] out Vector3[] corners,
     [FriendlyName("Status", "Status of the path. (Read Only)"), SocketState(false, false)] out NavMeshPathStatus status
     )
 {
     path    = agent.path;
     corners = path.corners;
     status  = path.status;
 }
Example #19
0
    void Update()
    {
        int turnOnSpot;

        // Rendo visibili queste variabili nell'inspector per vedere come si
        // comporta lo stato del NavMeshAgent
        HasPath     = _navAgent.hasPath;
        PathPending = _navAgent.pathPending;
        PathStale   = _navAgent.isPathStale;
        PathStatus  = _navAgent.pathStatus;

        // Eseguo il prodotto matriciale tra i vettori forward e speed (spazio tempo)
        // Se entrambi i valori dei due input corrispondono la magnitude del vettore risultante
        // sarà Sin(theta) dove Theta è l'angolo tra i vettori
        Vector3 cross = Vector3.Cross(transform.forward, _navAgent.desiredVelocity.normalized);

        // Se Y è negativo allora la anche rotazione è negativa
        float horizontal = (cross.y < 0)? -cross.magnitude : cross.magnitude;

        horizontal = Mathf.Clamp(horizontal * 2.32f, -2.32f, 2.32f);

        if (_navAgent.desiredVelocity.magnitude < 1.0f && Vector3.Angle(transform.forward, _navAgent.steeringTarget - transform.position) > 10.0f)
        {
            // Ferma il navAgent e assegna -1 o +1 a turnOnSpot in base a horizontal
            _navAgent.speed = 0.1f;
            turnOnSpot      = (int)Mathf.Sign(horizontal);
        }
        else
        {
            // Altrimenti l'angolo è ridotto e omposto la velocità del navAgent
            // su Normal e resetto turnOnSpot
            _navAgent.speed = _originalMaxSpeed;
            turnOnSpot      = 0;
        }

        // Setto i dati che sono stati calcolati nei parametri dell'animator
        _animator.SetFloat("Horizontal", horizontal, 0.1f, Time.deltaTime);
        _animator.SetFloat("Vertical", _navAgent.desiredVelocity.magnitude, 0.1f, Time.deltaTime);
        _animator.SetInteger("TurnOnSpot", turnOnSpot);


        // Se non c'è un Path e PathPending è false allora imposto il Waypoint successivo come target
        // altrimenti se il Path è vecchio rigenero tutto il percorso
        if ((_navAgent.remainingDistance <= _navAgent.stoppingDistance && !PathPending) || PathStatus == UnityEngine.AI.NavMeshPathStatus.PathInvalid /*|| PathStatus==NavMeshPathStatus.PathPartial*/)
        {
            SetNextDestination(true);
        }
        else if (_navAgent.isPathStale)
        {
            SetNextDestination(false);
        }
    }
Example #20
0
    void Update()
    {
        status = agent.pathStatus;
        switch (currentState)
        {
        case UnitState.Idle: IdleState(); break;

        case UnitState.Move: MoveState(); break;

        case UnitState.Chase: ChaseState(); break;

        case UnitState.Attack: AttackState(); break;
        }
    }
    // ---------------------------------------------------------
    // Name	:	Update
    // Desc	:	Called each frame by Unity
    // ---------------------------------------------------------
    void Update()
    {
        int turnOnSpot;

        // Copy NavMeshAgents state into inspector visible variables
        HasPath     = _navAgent.hasPath;
        PathPending = _navAgent.pathPending;
        PathStale   = _navAgent.isPathStale;
        PathStatus  = _navAgent.pathStatus;

        Vector3 cross      = Vector3.Cross(transform.forward, _navAgent.desiredVelocity.normalized);
        float   horizontal = (cross.y < 0) ? -cross.magnitude : cross.magnitude;

        horizontal = Mathf.Clamp(horizontal * 2.32f, -2.32f, 2.32f);

        if (_navAgent.desiredVelocity.magnitude < 1.0f && (Vector3.Angle(transform.forward, _navAgent.desiredVelocity) > 10.0f || !HasPath))
        {
            _navAgent.speed = 0.1f;
            turnOnSpot      = (int)Mathf.Sign(horizontal);
        }
        else
        {
            _navAgent.speed = _originalMaxSpeed;
            turnOnSpot      = 0;
        }

        _animator.SetFloat("Horizontal", horizontal, 0.1f, Time.deltaTime);
        _animator.SetFloat("Vertical", _navAgent.desiredVelocity.magnitude, 0.1f, Time.deltaTime);
        _animator.SetInteger("TurnOnSpot", turnOnSpot);

        // If agent is on an offmesh link then perform a jump

        /*if (_navAgent.isOnOffMeshLink)
         * {
         *  StartCoroutine(Jump(1.0f));
         *  return;
         * }*/

        // If we don't have a path and one isn't pending then set the next
        // waypoint as the target, otherwise if path is stale regenerate path
        if ((_navAgent.remainingDistance <= _navAgent.stoppingDistance && !PathPending) || PathStatus == NavMeshPathStatus.PathInvalid /*|| PathStatus==NavMeshPathStatus.PathPartial*/)
        {
            SetNextDestination(true);
        }
        else
        if (_navAgent.isPathStale)
        {
            SetNextDestination(false);
        }
    }
Example #22
0
    void WaitForValidPath()
    {
        Quaternion lookAtPlayer = Quaternion.LookRotation(player.transform.position - transform.position, Vector3.up);

        transform.rotation = Quaternion.Euler(0, lookAtPlayer.eulerAngles.y, 0);

        // update path to player
        NMAgent.SetDestination(player.transform.position);

        pathStatus  = NMAgent.pathStatus;
        gotPath     = NMAgent.hasPath;
        pathPending = NMAgent.pathPending;

        // check if path is valid
        if (NMAgent.pathStatus == NavMeshPathStatus.PathComplete)
        {
            // if yes, figure out if enemy should be attacking or chasing
            if (Vector3.Distance(player.transform.position, transform.position) > attackDistance)
            {
                currentState      = State.ATTACKING;
                attackTimer       = 0;
                NMAgent.isStopped = true;
                animator.SetBool("isIdle", false);
                animator.SetBool("isAttacking", true);
            }
            else
            {
                currentState      = State.CHASING;
                attackTimer       = 0;
                NMAgent.speed     = chaseSpeed;
                NMAgent.isStopped = false;
                animator.SetBool("isIdle", false);
                animator.SetBool("isChasing", true);
            }
        }
        else if (pathPending == false)
        {
            /*Note: For some reason when the player enters an unreachable area, then becomes reachable again,
             * the path will not be recalculated until the player crosses into a second reachable pathing node.
             * This helps a little bit, I think. I re-baked the map after so it ended up not really mattering anyway.*/

            NavMeshPath path = new NavMeshPath();

            if (NMAgent.CalculatePath(player.transform.position, path))
            {
                NMAgent.SetPath(path);
            }
        }
    }
Example #23
0
    // ---------------------------------------------------------
    // Name	:	Update
    // Desc	:	Called each frame by Unity
    // ---------------------------------------------------------
    void Update()
    {
        // Copy NavMeshAgents state into inspector visible variables
        HasPath     = _navAgent.hasPath;
        PathPending = _navAgent.pathPending;
        PathStale   = _navAgent.isPathStale;
        PathStatus  = _navAgent.pathStatus;

        Vector3 localDesiredVelocity = transform.InverseTransformVector(_navAgent.desiredVelocity);
        float   angle = Mathf.Atan2(localDesiredVelocity.x, localDesiredVelocity.z) * Mathf.Rad2Deg;

        _smoothAngle = Mathf.MoveTowardsAngle(_smoothAngle, angle, 80.0f * Time.deltaTime);

        float speed = localDesiredVelocity.z;

        _animator.SetFloat("Angle", _smoothAngle);
        _animator.SetFloat("Speed", speed, 0.1f, Time.deltaTime);

        if (_navAgent.desiredVelocity.sqrMagnitude > Mathf.Epsilon)
        {
            if (!MixedMode ||
                (MixedMode && Mathf.Abs(angle) < 80.0f && _animator.GetCurrentAnimatorStateInfo(0).IsName("Base Layer.Locomotion")))
            {
                Quaternion lookRotation = Quaternion.LookRotation(_navAgent.desiredVelocity, Vector3.up);
                transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, 5.0f * Time.deltaTime);
            }
        }

        // If agent is on an offmesh link then perform a jump

        /*if (_navAgent.isOnOffMeshLink)
         * {
         *  StartCoroutine(Jump(1.0f));
         *  return;
         * }*/

        // If we don't have a path and one isn't pending then set the next
        // waypoint as the target, otherwise if path is stale regenerate path
        if ((_navAgent.remainingDistance <= _navAgent.stoppingDistance && !PathPending) || PathStatus == NavMeshPathStatus.PathInvalid /*|| PathStatus==NavMeshPathStatus.PathPartial*/)
        {
            SetNextDestination(true);
        }
        else
        if (_navAgent.isPathStale)
        {
            SetNextDestination(false);
        }
    }
Example #24
0
        public virtual TaskStatus OnUpdate()
        {
            if (Object.op_Equality((Object)this._partner, (Object)null))
            {
                return((TaskStatus)1);
            }
            if (!Singleton <Resources> .IsInstance())
            {
                return((TaskStatus)3);
            }
            AgentProfile      agentProfile      = Singleton <Resources> .Instance.AgentProfile;
            LocomotionProfile locomotionProfile = Singleton <Resources> .Instance.LocomotionProfile;
            Vector3           destination       = this.DesiredPosition(this._partner);

            if ((double)agentProfile.RestDistance <= (double)Vector3.Distance(destination, this._merchant.Position))
            {
                this.SetDestination(destination);
                this._moved = true;
            }
            else
            {
                NavMeshPathStatus pathStatus = this._navMeshAgent.get_pathStatus();
                if (pathStatus == 1 || pathStatus == 2)
                {
                    if ((double)Vector3.Distance(this._merchant.Position, this._partner.Position) < (double)agentProfile.RestDistance)
                    {
                        this.Stop();
                        if (this._merchant.IsRunning)
                        {
                            this._merchant.IsRunning = false;
                        }
                    }
                }
                else if (!this._navMeshAgent.get_pathPending())
                {
                    if ((double)this._navMeshAgent.get_remainingDistance() < (double)agentProfile.RestDistance && this._merchant.IsRunning)
                    {
                        this._merchant.IsRunning = false;
                    }
                    if (this._moved && (double)this._navMeshAgent.get_remainingDistance() < (double)this._navMeshAgent.get_stoppingDistance())
                    {
                        this.Stop();
                        this._moved = false;
                    }
                }
            }
            return((TaskStatus)3);
        }
Example #25
0
        // Update is called once per frame
        private void Update()
        {
            NavMeshPathStatus pathStatus = _agent.pathStatus;

            // If current path is unable to be complete, get a new one
            if (pathStatus != NavMeshPathStatus.PathComplete)
            {
                GetNewPath();
            }

            // If walker has reached destination, get a new path
            if (Mathf.RoundToInt(_agent.remainingDistance) == 0)
            {
                GetNewPath();
            }
        }
Example #26
0
    private void Update()
    {
        hasPath     = agent.hasPath;
        pathPending = agent.pathPending;
        pathStale   = agent.isPathStale;
        pathStatus  = agent.pathStatus;

        if ((agent.remainingDistance <= agent.stoppingDistance && !pathPending) || pathStatus == NavMeshPathStatus.PathInvalid)
        {
            SetNextDestination(true);
        }
        else if (agent.isPathStale)
        {
            SetNextDestination(false);
        }
    }
Example #27
0
    void Update()
    {
        // Rendo visibili queste variabili nell'inspector per vedere come si
        // comporta lo stato del NavMeshAgent
        HasPath     = _navAgent.hasPath;
        PathPending = _navAgent.pathPending;
        PathStale   = _navAgent.isPathStale;
        PathStatus  = _navAgent.pathStatus;

        // Converto la l'agent speed in local space
        Vector3 localDesiredVelocity = transform.InverseTransformVector(_navAgent.desiredVelocity);

        // Ottengo l'angolo in gradi per quanto devo girare per raggiungere la DesiredVelocity
        float angle = Mathf.Atan2(localDesiredVelocity.x, localDesiredVelocity.z) * Mathf.Rad2Deg;

        _smoothAngle = Mathf.MoveTowardsAngle(_smoothAngle, angle, 80.0f * Time.deltaTime);

        // La Speed è la desiredVelocity proiettata dul nostro Forward Vector
        float speed = localDesiredVelocity.z;

        // Setto i parametri dell'animator
        _animator.SetFloat("Angle", _smoothAngle);
        _animator.SetFloat("Speed", speed, 0.1f, Time.deltaTime);

        if (_navAgent.desiredVelocity.sqrMagnitude > Mathf.Epsilon)
        {
            if (!MixedMode ||
                (MixedMode && Mathf.Abs(angle) < 80.0f && _animator.GetCurrentAnimatorStateInfo(0).IsName("Base Layer.Locomotion")))
            {
                Quaternion lookRotation = Quaternion.LookRotation(_navAgent.desiredVelocity, Vector3.up);
                transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, 5.0f * Time.deltaTime);
            }
        }


        // Se non c'è un Path e PathPending è false allora imposto il Waypoint successivo come target
        // altrimenti se il Path è vecchio rigenero tutto il percorso
        if ((_navAgent.remainingDistance <= _navAgent.stoppingDistance && !PathPending) || PathStatus == NavMeshPathStatus.PathInvalid)
        {
            SetNextDestination(true);
        }
        else
        if (_navAgent.isPathStale)
        {
            SetNextDestination(false);
        }
    }
Example #28
0
    // Update is called once per frame
    void Update()
    {
        HasPath     = _navAgent.hasPath;
        PathPending = _navAgent.pathPending;
        PathStale   = _navAgent.isPathStale;
        PathStatus  = _navAgent.pathStatus;

        if (_navAgent.isOnOffMeshLink)
        {
            if (_navAgent.isOnOffMeshLink)
            {
                StartCoroutine(Jump(1.0f));
                return;
            }
        }

        // if we don't have a path and one isn't pending then set the next
        // waypoint as the target, otherwise if the path is stale regenerate path
        if ((_navAgent.remainingDistance <= _navAgent.stoppingDistance && !PathPending) || PathStatus == NavMeshPathStatus.PathInvalid /*|| PathStatus == NavMeshPathStatus.PathPartial*/)
        {
            SetNextDestination(true);
        }
        else
        if (_navAgent.isPathStale)
        {
            SetNextDestination(false);
        }


        IEnumerator Jump(float duration)
        {
            OffMeshLinkData data     = _navAgent.currentOffMeshLinkData;
            Vector3         startPos = _navAgent.transform.position;
            Vector3         endPos   = data.endPos + (_navAgent.baseOffset * Vector3.up);
            float           time     = 0.0f;

            while (time < duration)
            {
                float t = time / duration;
                _navAgent.transform.position = Vector3.Lerp(startPos, endPos, t) + (JumpCurve.Evaluate(t) * Vector3.up);
                time += Time.deltaTime;
                yield return(null);
            }

            _navAgent.CompleteOffMeshLink();
        }
    }
    // Update is called once per frame
    void Update()
    {
        //* keep all of the agents navigation information current
        HasPath     = _navAgent.hasPath;
        PathPending = _navAgent.pathPending;
        PathStale   = _navAgent.isPathStale;
        PathStatus  = _navAgent.pathStatus;

        //set up OffMeshLink
        if (_navAgent.isOnOffMeshLink)
        {
            if (_navAgent.isOnOffMeshLink)
            {
                StartCoroutine(Jump(1.0f));
                return;
            }
        }

        if ((_navAgent.remainingDistance <= _navAgent.stoppingDistance && !PathPending) ||
            PathStatus == NavMeshPathStatus.PathInvalid)
        {
            SetNextDestination(true);
        }
        else if (_navAgent.isPathStale)
        {
            SetNextDestination(false);
        }

        IEnumerator Jump(float duration)
        {
            OffMeshLinkData data     = _navAgent.currentOffMeshLinkData;
            Vector3         startPos = _navAgent.transform.position;
            Vector3         endPos   = data.endPos + (_navAgent.baseOffset * Vector3.up);
            float           time     = 0.0f;

            while (time < duration)
            {
                float t = time / duration;
                _navAgent.transform.position = Vector3.Lerp(startPos, endPos, t) + (JumpCurve.Evaluate(t) * Vector3.up);
                time += Time.deltaTime;
                yield return(null);
            }

            _navAgent.CompleteOffMeshLink();
        }
    }
Example #30
0
    // Update is called once per frame
    void Update()
    {
        int turnOnSpot;

        hasPath     = _navAgent.hasPath;
        pathPending = _navAgent.pathPending;
        pathStale   = _navAgent.isPathStale;
        pathStatus  = _navAgent.pathStatus;

        Vector3 cross      = Vector3.Cross(transform.forward, _navAgent.desiredVelocity.normalized);
        float   horizontal = (cross.y < 0) ? -cross.magnitude : cross.magnitude; // figuring out if its a left or right turn

        horizontal = Mathf.Clamp(horizontal * 2.32f, -2.32F, 2.32f);

        if (_navAgent.desiredVelocity.magnitude < 0.75f && Vector3.Angle(transform.forward, _navAgent.desiredVelocity) > 10.0f)
        {
            _navAgent.speed = 0.1f;
            turnOnSpot      = (int)Mathf.Sign(horizontal);
        }
        else
        {
            _navAgent.speed = _originalMaxSpeed;
            turnOnSpot      = 0;
        }

        _animator.SetFloat("horizontal", horizontal, 0.1f, Time.deltaTime);
        _animator.SetFloat("vertical", _navAgent.desiredVelocity.magnitude, 0.1f, Time.deltaTime);
        _animator.SetInteger("turnOnSpot", turnOnSpot);


        //if (_navAgent.isOnOffMeshLink)
        //{
        //    StartCoroutine(Jump(1.0f));
        //    return;
        //}

        if ((_navAgent.remainingDistance <= _navAgent.stoppingDistance && !pathPending) || (pathStatus == NavMeshPathStatus.PathInvalid))
        {
            SetNextDestination(true);
        }
        else if (_navAgent.isPathStale)
        {
            SetNextDestination(false);
        }
    }
    void Update()
    {
        int turnOnSpot = 0;

        HasPath     = navAgent.hasPath;
        PathPending = navAgent.pathPending;
        PathStale   = navAgent.isPathStale;
        PathStatus  = navAgent.pathStatus;

        Vector3 cross      = Vector3.Cross(transform.forward, navAgent.desiredVelocity.normalized);
        float   horizontal = cross.y < 0 ? -cross.magnitude : cross.magnitude;

        horizontal = Mathf.Clamp(horizontal * 2.32f, -2.32f, 2.32f);

        if (navAgent.velocity.magnitude < 1.0f && Vector3.Angle(transform.forward, navAgent.desiredVelocity) > 10.0f)
        {
            navAgent.speed = 0.1f;
            turnOnSpot     = (int)Mathf.Sign(horizontal);
        }
        else
        {
            navAgent.speed = originalMaxSpeed;
            turnOnSpot     = 0;
        }

        animator.SetFloat("Horizontal", horizontal, 0.1f, Time.deltaTime);
        animator.SetFloat("Vertical", navAgent.desiredVelocity.magnitude, 0.1f, Time.deltaTime);
        animator.SetInteger("TurnOnSpot", turnOnSpot);

        /*
         * if (navAgent.isOnOffMeshLink) {
         *  StartCoroutine(Jump(1.0f, navAgent.destination, CurrentIndex));
         *  return;
         * }
         */

        if ((navAgent.remainingDistance <= navAgent.stoppingDistance && !PathPending && !OnOffMeshLink) || PathStatus == NavMeshPathStatus.PathInvalid)
        {
            SetNextDestination(true);
        }
        else if (PathStale)
        {
            SetNextDestination(false);
        }
    }
Example #32
0
    public static void CalculateNavigationMeshPath(Vector3 startPosition, Vector3 goalPosition, int passableMask)
    {
        ClearNavigationMeshPath ();

        switch (navigationMeshChoice)
        {

        default:
        case NavigationMeshChoice.USE_UNITY :

            NavMeshPath unityPath = new NavMeshPath();
            NavMesh.CalculatePath(startPosition,goalPosition, passableMask,unityPath);

            pathStatus = unityPath.status;

            if (pathStatus == NavMeshPathStatus.PathInvalid)
            {
                numberOfNodes = 0;
            }
            else
            {
                if ( unityPath.corners.Length >= maxNumberOfNodes)
                {
                    Debug.LogWarning("Navigation mesh path greater than maximum number of nodes");
                    numberOfNodes = maxNumberOfNodes;
                    pathStatus = NavMeshPathStatus.PathPartial;
                }
                else
                {
                    numberOfNodes = unityPath.corners.Length;
                }

                for(int i =0; i < numberOfNodes; i++)
                {
                    // MAKING SURE LAST WAYPOINT IS THE GOAL
                    if ( i == numberOfNodes - 1)
                        path[i] = goalPosition;
                    else
                    path[i] = unityPath.corners[i];

                    // computing path cost
                    if (i==0)
                        pathCost[i] = 0.0f;
                    else
                    {
                        // assuming that all off mesh links will override cost
                        if (CentralizedManager.IsOffMeshLink(path[i]))
                            pathCost[i] = CentralizedManager.GetOffMeshLinkInformation(path[i]).offMeshLink.costOverride;
                        else
                            pathCost[i] = Vector3.Distance(path[i],path[i-1]);
                    }

                    totalPathCost += pathCost[i];

                }
            }

            break;

        case NavigationMeshChoice.USE_RECAST:

            if (recastSteeringManager == null)
                recastSteeringManager = GameObject.Find("ADAPTPrefab").GetComponentInChildren<SteeringManager>();

            numberOfNodes = recastSteeringManager.FindPath(startPosition,goalPosition,path,maxNumberOfNodes);

            if( numberOfNodes > 0)
                path[numberOfNodes-1] = goalPosition;

            // computing path cost
            for (int i=1; i < numberOfNodes; i++)
            {
                // TODO : incorporate number of obstacles from centralized manager here
                pathCost[i] = Vector3.Distance(path[i],path[i-1]);
                totalPathCost += pathCost[i];
            }

            if (numberOfNodes == 0)
                pathStatus = NavMeshPathStatus.PathInvalid;
            else if ( numberOfNodes == maxNumberOfNodes)
                pathStatus = NavMeshPathStatus.PathPartial;
            else
                pathStatus = NavMeshPathStatus.PathComplete;

            break;

        }
    }
Example #33
0
 public static void ClearNavigationMeshPath()
 {
     numberOfNodes = 0;
     pathStatus = NavMeshPathStatus.PathInvalid;
     totalPathCost = 0.0f;
 }