Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Agent stops on edges

Discussion in 'Navigation' started by AndreLangston, Aug 5, 2019.

  1. AndreLangston

    AndreLangston

    Joined:
    Jan 8, 2019
    Posts:
    1
    I'm using the following script to make the NPC wander around the nav mesh.

    using UnityEngine;
    using System.Collections;

    public class Wander : MonoBehaviour {

    public float wanderRadius;
    public float wanderTimer;

    private Transform target;
    private UnityEngine.AI.NavMeshAgent agent;
    private float timer;

    // Use this for initialization
    void OnEnable () {
    agent = GetComponent<UnityEngine.AI.NavMeshAgent> ();
    timer = wanderTimer;
    }

    // Update is called once per frame
    void Update () {
    timer += Time.deltaTime;

    if (timer >= wanderTimer) {
    Vector3 newPos = RandomNavSphere(transform.position, wanderRadius, -1);
    agent.SetDestination(newPos);
    timer = 0;
    }
    }

    public static Vector3 RandomNavSphere(Vector3 origin, float dist, int layermask) {
    Vector3 randDirection = Random.insideUnitSphere * dist;

    randDirection += origin;

    UnityEngine.AI.NavMeshHit navHit;

    UnityEngine.AI.NavMesh.SamplePosition (randDirection, out navHit, dist, layermask);

    return navHit.position;
    }
    }

    Can anyone tell me why they might be stopping at the edge of the nav mesh? I'm relatively new to navmeshes and I'm not sure if I'm using something wrong or what
     
  2. Yandalf

    Yandalf

    Joined:
    Feb 11, 2014
    Posts:
    491
    Well if you take random directions and your agent is already standing at an edge, it's very easy to keep moving in a direction outside of the navmesh.
    If you're looking to make a bit more of a controlled wander, maybe set a few target positions your agent can wander between?
     
  3. nattd

    nattd

    Joined:
    Jan 14, 2016
    Posts:
    1
    I agree with Yandalf, there's a high likelihood of picking a position outside the bounds. and as you're using a sphere, there's also a good chance of choosing a position too far above or below the navmesh. I assume that you've tried setting wanderDistance to a small value - a large radius (e.g. 50 meters) equates to a lot of empty space. I've got something similar working, but I'm using a circular radius with a limited range of height (as the map is relatively flat and NPCs don't move more than 1 "floor" at a time). It also greatly helps if the agent is "aware" of the map edges and/or as Yandalf suggests, constrain wandering around fixed positions or within a radius..