Search Unity

NavMesh agent zigzag movement

Discussion in 'Navigation' started by megaminx96, Jan 27, 2020.

  1. megaminx96

    megaminx96

    Joined:
    Mar 24, 2019
    Posts:
    1
    Hi,
    I've setup Unity navmesh for my agents, and they can move to destination successfully.
    I was wondering if it is possible to move the agent with a more complex pattern like something similar to a sin function or zigzag.
    Thanks for your help :)
     
  2. Gordon_G

    Gordon_G

    Joined:
    Jun 4, 2013
    Posts:
    372
    I have a method I use, and I'm working up a tutorial video for it. Here's a general outline::

    First, store the final destination point (the past point in the path array) - you want your objects to keep progressing toward that
    • Using a random timer to run a coroutine that does this when fired off:
      • calculate a a point on the current path ahead of the current position based on the current object forward and speed (i.e. look ahead some distance)
      • using a random angle (between some range), offset the point from the current forward along z (alternating positive or negative from the z axis each time the coroutine is executed - one zig, then one zag, and so on).
      • Set the new NavMeshAgent destination to this new point
    • Determine when the agent has reached this new destination, and then set back to saved, original destination (do not call the coroutine while in the process of a zig or zag!
    • Repeat until agent reaches the original end destination

    I also look head to any intervening points on the NavMeshAgent path and with some calculations determine if there are any immediate sharp corners ahead, because this causes some odd turing behavior - but I am still fine tuning the algorithm.

    Playing around with it, I get a nice wandering behavior that still moves to the goal destination.

    Hope it helps!
     
    softscience likes this.