Home > Mobile >  Unity 2D: physics-based pathfinding package/library
Unity 2D: physics-based pathfinding package/library

Time:10-07

I'm working on a small project where the goal is to defend yourself from mass enemy hordes in a 2d environment. The goal is to have the game be physics based, with enemies pushing against eachother to create a feeling of chaos.

Now I have a setup with enemies, a player and multiple obstacles all with a Rigidbody2D and 2D-colliders (mixed types, including polygon2D collider). Now I want to have the enemies chase the player. The obstacles however are polygon shaped rigidbodies, and thus are able to move.

So I want the "navigation" mesh of some sort to update on the fly, and calculate a navigation path for many entities. Note: I don't know how many entities yet, but let's say ~100.

The things I tried to far:

  • Using the built-in NavMesh package from Unity. This package does not properly support the 2D configuration of Unity
  • Using the NavMeshPlus package. This implements a NavMeshSurface2D component to work with the 2D environment. I got this to work, but the NavMeshAgent component to steer the enemy does not use the force attribute of the rigidbody component, but rather just sets the speed or position of the transform. If someone knows how to use the NavMeshAgent or the NavMesh API in a way to get the target direction/speed via script, that would also be a solution
  • I tried the A* package. Which also works, but creates a very jagged line as it only can move in 8 directions (up,down,left,right and diagonals). It also cuts the corners of the obstacles, and does not take into account the size of the object (enemy) itself, so it hangs at the corners.

If anyone knows a good package/extension or the location of documentation of the NavMesh part, that would be great!

Thank you in advance.

CodePudding user response:

So I got it to work and will share the solution I took:

  1. Using the NavMeshPlus package, I created a navmesh.
  2. Instead of using a NavMeshAgent, I configured an agent type in the navigation window with the right physical dimensions.
  3. Next I added a script on the enemy to function as a custom NavMeshAgent.
  4. Add a NavMeshSurface2D reference to the script (Serialized)
  5. Using UnityEngine.AI, call NavMesh.CalculatePath(), with the AI.NavMeshQueryFilter. This has 2 components, the agent and area setters. Both of those I get from the NavMeshSurface2D reference.

Now you have the path the agent has to follow!

By the way, I'm also aware this could be done by a custom Agent inheriting the NavMeshAgent class, I'm also looking into that. Time will tell which one will have better performance.

  • Related