How to Write Custom UE4 AI C++ Pathing Code, How to get All Nav Polys For Custom Code

Dear Community,

I recently wrote a wiki on how to add to the UE4 C++ AI path following system, to add in custom pathing coding!

UE4 Wiki Link: Writing Custom C++ AI Code

Well I now have my best demo yet of the effectiveness of this coding structure!

I prove to you in the video that I am using just multi-threaded C++ to dynamically calculate AI Jump paths for my AI units to follow the player through many complex jumping sequences!

  1. I am using just C++ coding, no helpers in the editor!

2.** In this thread I share my own UE4 C++ code with you** for how to get all the nav polys, the actual portions of the nav mesh so that you can do your own fancy custom UE4 C++ AI pathing code!

  1. In this thread I also show you how I know when the UE4 pathing system can’t find a way to the player without doing jumps!

**Video: 's Multi-Threaded C++ AI Jump Pathing**

https://youtube.com/watch?v=sMMSQdnyt6o

Once again, I am doing all the jumping calculations **dynamically via C++** using the nav areas and my custom path following component!

Mult-Threaded

The code I use in this video is multi-threaded using the UE4 C++ Task Graph system:

UE4 Wiki Link: UE4 Multi-threading


**C++ Code For You**

I inject my custom AI jump pathing code in this way:



```


/*
        Custom UE4 C++ AI Path Follow Component

	By 

*/

#pragma once

//Super
#include "Navigation/PathFollowingComponent.h"		

UCLASS() 
class UJoyPathFollowComp : public UPathFollowingComponent
{
	GENERATED_BODY()
public:
	UJoyPathFollowComp(const FObjectInitializer& ObjectInitializer);

/** follow current path segment */
virtual void FollowPathSegment(float DeltaTime) override;

};


```





```


void UJoyPathFollowComp::FollowPathSegment(float DeltaTime)
{
	//Pointer Safety Checks
	if (MovementComp == NULL || !Path.IsValid())
	{
		return;
	}
	//~~~~~~~~~~~~~~~~~~~~~~~~~
	 
	
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//Use Jump/Fall Pathing?
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~
	if(Path->IsPartial()) //AI could not reach player, try using jump pathing!
	{
                //I send out instructions to my custom character class here
		JoyChar->ReceiveJumpFallPathingRequest();
	
		return;
		//~~~
	}
	
	
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//Proceed normally (no jump pathing)
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	Super::FollowPathSegment(DeltaTime);
}


```



Explanation

FollowPathSegment is the main UE4 Path Follow tick function, and so when you want to add completely custom coding you can use this function as your starting point to adjust normal UE4 pathing behavior!

Path is Partial

The way I tell whether I need to try using custom jump pathing code is whether or not the UE4 Pathing system has detected a partial path!

Then my AI jump code runs and teaches the AI to get to the player using C++ calculated Jumps!



if(Path->IsPartial()) //AI could not reach player, try using jump pathing!



**How to Get all the UE4 Nav Polys**

In the video above you will see I get all the UE4 Nav Polys in order to do all my C++ AI Jump calculations!

Here's the function I wrote to do this, just for you!



```


**//  UE4 C++ AI Code for you!
//     add this to your custom path follow component!**

**//Nav Data Main**
FORCEINLINE const ANavigationData* **GetMainNavData**(FNavigationSystem::ECreateIfEmpty CreateNewIfNoneFound)
{
	UNavigationSystem* NavSys = GetWorld()->GetNavigationSystem();
	if(!NavSys) return NULL; 
	return NavSys->GetMainNavData(CreateNewIfNoneFound);
}

**//Choose Which Nav Data To Use**
FORCEINLINE const ANavigationData* **JoyGetNavData()** const
{
        if(!MovementComp)
        {
              return GetMainNavData();
        }

	const FNavAgentProperties& AgentProperties = MovementComp->GetNavAgentPropertiesRef() ;
	const ANavigationData* NavData = GetNavDataForProps(AgentProperties) ;
	if (NavData == NULL)
	{
		VSCREENMSG("ERROR USING MAIN NAV DATA"); 
		NavData = GetMainNavData();
	}
		   
	return NavData;
}

//VERY IMPORTANT FOR CRASH PROTECTION !!!!!
FORCEINLINE bool **TileIsValid**(const ARecastNavMesh* NavMesh,int32 TileIndex) const
{
	if(!NavMesh) return false;
	//~~~~~~~~~~~~~~
	const FBox TileBounds = NavMesh->GetNavMeshTileBounds(TileIndex);
	
	return TileBounds.IsValid != 0;
}


bool **NavPoly_GetAllPolys**(TArray<NavNodeRef>& Polys);


```





```


**//'s UE4 Nav code to get all the nav polys!**

bool UJoyPathFollowComp::****NavPoly_GetAllPolys****(TArray<NavNodeRef>& Polys)
{
	if(!MovementComp) return false;
	//~~~~~~~~~~~~~~~~~~
	
	//Get Nav Data
	const ANavigationData* NavData = JoyGetNavData();
	 
	const ARecastNavMesh* NavMesh = Cast<ARecastNavMesh>(NavData);
	if(!NavMesh)
	{
		return false;
	}
	
	TArray<FNavPoly> EachPolys;
	for(int32 v = 0; v < NavMesh->GetNavMeshTilesCount(); v++)
	{
		
                //CHECK IS VALID FIRST OR WILL CRASH!!! 
               //     256 entries but only few are valid!
               // using continue in case the valid polys are not stored sequentially!
		if(****!TileIsValid****(NavMesh,v)) 
                {
                    continue;
		}	
	
		NavMesh->GetPolysInTile(v,EachPolys);
	}	
	  
	
	//Add them all!
	for(int32 v = 0; v < EachPolys.Num(); v++)
	{
		Polys.Add(EachPolys[v].Ref);
	}
}


```



Enjoy!

Have fun writing custom UE4 AI C++ code and getting all the nav polys so you can truly do whatever you want with UE4’s awesome navigation system!

2 Likes

nice work i hope to see more improvement in future. i felt down laughing on the AI jump that is crazy.

,

Is the AIController code in the AI Wiki link you reference above still valid for UE4 4.7x?

In your first step I see syntax “class AJoyController : public AAIController” but when I create a new C++ AI Controller in UE4 4.7.3, I get “class MyProject_API AJoyController : public AAIController”

After that, in all examples I have found, they have “GENERATED_UCLASS_BODY()” but mine has “GENERATED_BODY()” - looks like you don’t show either of these lines of code in your example.

Regarding adding the AIModule reference to the MyProject.build.cs file, if I don’t do this prior to creating the AIController, I get an error when I compile as expected, but even after adding the AIModule reference immediately afterwards, and then trying to compile again, I still get errors at this point, but not if I create the AIModule reference first. I end up having to scrap the entire project and start over when this happens as I can’t figure out how to recover from this error.

I am using Visual Studio 2014 Ultimate update 2 if that matters.

Hi there!

I added to my wiki to show GENERATED_BODY

If you add AIModule as public dependency to build.cs your project should work great:



PublicDependencyModuleNames.AddRange(new string] { 
	"Core", 
	"CoreUObject", 
	"Engine", 
	"InputCore" ,
        //....etc
	"AIModule"      //<~~~~~~
});


Good luck!

Looking cool ! =)

Correction to My UE4 Nav Mesh ~ Get All Polys Code

Correction to My Get All Nav Polys Code

If you’ve been using my Get All Nav Polys code for your own fancy UE4 AI nav mesh calculations, please note I’ve found and fixed a bug!

This



TArray<FNavPoly> EachPolys;
	for(int32 v = 0; v < NavMesh->GetNavMeshTilesCount(); v++)
	{
		
                //CHECK IS VALID FIRST OR WILL CRASH!!! 
               //     256 entries but only few are valid!
		if(****!TileIsValid****(NavMesh,v)) 
                {
                    break; **<<~~~~~~~~~~~~~~~**
		}	
	
		NavMesh->GetPolysInTile(v,EachPolys);
	}		


becomes this



TArray<FNavPoly> EachPolys;
	for(int32 v = 0; v < NavMesh->GetNavMeshTilesCount(); v++)
	{
		
                //CHECK IS VALID FIRST OR WILL CRASH!!! 
               //     256 entries but only few are valid!
               // using continue in case the valid polys are not stored sequentially!
		if(****!TileIsValid****(NavMesh,v)) 
                {
                   ** continue;**
		}	
	
		NavMesh->GetPolysInTile(v,EachPolys);
	}


Summary:

I was assuming valid polys would get stored sequentially! I’ve proven through further testing that this is not the case.

My correction to using continue allows me to truly get all valid polys in the recast nav mesh :slight_smile:

:heart:

**Writing Custom Path Following Components

Support for PhysX-Simulating AI Characters**

Here’s a new video demoing why it can be very helpful to write your own AI Path Following components, as I show you how to do in this thread!

In the video below, I am using a few extra lines of code and a custom Path Following Component to fully support PhysX-simulating characters in UE4!

Enjoy!

Jump Pathing AI Starting Point For You

Please note that in this thread I am giving you the essential C++ framework / foundation to do anything you want with the UE4 navigation system! You get to utilize all of Epic’s fabulous navigation code and system to make your own custom game mechanics!

Like my AI Jump Pathing system, featured today on the Epic Twitch Stream!

UE4 Twitch Stream Link

Again my point is that in this thread I am sharing the essential starter code that you need to get rolling with your own fun UE4 navigation C++ mechanics!

With a custom path following component linked to a custom AI controller, and the ability to access all of the Nav Polys of the nav mesh, you can now do your own calculations to make your own custom AI navigation game mechanics!

:slight_smile:

Another sweet piece of code from !

I had a look at the pathfinding system a while back, and wanted to do a tutorial on it as soon as they had properly integrated Recast navigation. I am delighted to see you beat me to it!

I might still do a tutorial on crowd simulation using the UE4 recast implementation if I end up feeling like it.
But in the meantime, a biiig thumbs up on this!!

Best regards,
Temaran

Lovely to hear from you Temaran!

Yea it’s so nice we can easily access the Recast code now!

Others, you can check out the Recast code here:

RecastNavMesh.h



protected:
	// retrieves RecastNavMeshImpl
	FPImplRecastNavMesh* GetRecastNavMeshImpl() { return RecastNavMeshImpl; }
	const FPImplRecastNavMesh* GetRecastNavMeshImpl() const { return RecastNavMeshImpl; }


Have fun today!

:slight_smile:

PhysX Simulating Characters Pathing Over Dynamically Generated Ledges!

In this video you get to watch as I construct a section of level using my in-game level editor tools!

Then my physX-simulating ball characters are able to path over the ledges using the ledge-path AI I developed and demo in a prior video!


**UE4 Nav Mesh Rebuild At Runtime**

**This video shows off how good UE4 rebuild at runtime is**, as you watch the AI find my player unit amongst dynamically generated pieces of level that you watch me build during the video!

:)

Hey ,
I sent you a message about this + question about your rates for assistance.

Thanks!

Hi ,
Very nice work, always so useful your contributions.

Did you ever publish the full source code of this example (referring to your very first post)?

Thank you