Download

Wiki Code Tutorials

**New Wiki!

AI Navigation in C++, Customize Path Follwing Every Tick!**

Shows you how to extend UE4’s wonderful AI Path Folllowing foundation by adding your own C++ that will run every tick that the path following is occurring!

This lets you add to UE4 Path Following without having to rewrite the whole thing from scratch, you can inject your own code per-tick into the standard UE4 path following code!

I used what I share in the wiki below to make c++ dynamic jump pathing, as shown in the AI videos in my signature.

UE4 Wiki Link

Enjoy!

Rama

Example Of Template Functions

I make extensive use of C++ Template functions in my Min/Max of Array, full code here!

Min/Max of Array Forum Link

Wiki on C++ Templates

**How To

Add Handcrafted Custom Math Curves From UE4 Editor to C++**

Here’s a tutorial on how to construct perfect hand crafted curves in the Editor and then bring them into C++!

You can thus create spring curves, dampen curves, bounce curves, any kind of curves you want, and then use them to drive your C++ code!

Rama

Wow :smiley: Now that is creative :smiley:

Hee hee!

Glad you liked!

Custom Handcrafted Math Curves in C++ for Everyone!

Rama

Link to PhysX 3.3 Source Code For All UE4 Devs

I’ve updated my PhysX Wiki to include the direct link to the PhysX entire source code!

As a UE4 developer, you now have access to the entire PhysX C++ source code!

Rama Wiki, Integrating PhysX Code into Your Project

Rama

Garbage Collection and Dynamic Memory Allocation

In this wiki I show you how you can prevent your runtime-spawned UObjects from getting garbage collected prematurely!

This includes things like spawned emitters / Particle System Components, decals, and your own custom UObject systems!

I also go over how to allocate memory yourself and also free it, so you can do your own memory management.

Enjoy!

Garbage Collection and Dynamic Memory Management

Rama

Creating Custom Level Blueprints in C++

Here’s a wiki on how you can make your own C++ Level Blueprints so that you can easily store and access variable data for levels in C++!

You can also make your own functions specifically for your game, that your level designers can then use, that are backed by the power of C++!

Creating Custom Level Blueprints in C++

Rama

e Custom Console Commands in C++ to be implemented in Blueprints!

Empower your whole team to make their own console commands in Blueprints!

I originally designed this at the request of Hourences for use in Solus!

Enjoy!

Rama

[FONT=Comic Sans MS]USTRUCTS, UE4 C++ Structs

UE4 C++ Structs

[FONT=Comic Sans MS]I love UStructs!

:slight_smile:

Rama

New Wiki Section, Getting Nav Polys!

I’ve added a section showing you how to get the Nav Polys, the actual individual units of the nav mesh system, so you can do completely custom calculations like I do in this video below!

Wiki: Custom UE4 C++ AI Coding

Enjoy!

Rama

Added a second tutorial, how to get the screen-size of any actor :slight_smile: Useful for scaling widgets like the image below:

Get Screen-Size Bounds of An Actor

Hope it helps people!

@The Jamsh

Thanks for your awesome wiki contribution, wohooo! Really useful!


**Use C++ Operator New Instead of Malloc**

Using Malloc does not initialize the Vtable! So virtual functions will crash!

I recommend that you use C++ operator **new** to get around this, which both

a. calls the constructor of the data type
b. properly initializes the VTable (virtual function table)


I updated my wiki with this information

**UE4 Dynamic Memory Management**
https://wiki.unrealengine.com/Garbage_Collection_%26_Dynamic_Memory_Allocation#Every_New_Must_Have_a_Delete

♥

Rama

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: Rama'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 Rama

*/

#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!



```


**// Rama 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);


```





```


**//Rama'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!

Rama

**New Wiki Section

Shorthand Forward Declaration**

I added a new section and also polished up my Forward Declaration Wiki!

Forward Declaration ~ Shorthand Forward Declaration

:slight_smile:

Rama

Just added another tutorial of my own, Spawning different Pawns for different Players in Multiplayer!

Hope this helps people :slight_smile:

Thanks for sharing TheJamsh!

:slight_smile:

Rama

Tutorial: How to use UPhysicsConstraintComponent inside OnConstruction(FTransform) override function

I wanted to try contributing to the wiki with a tutorial. I noticed that Rama had already made an article here in regards to Physics Constraint Components and creating them dynamically. All I wanted to do is to just extend that article, so it also touches on ObjectInitializer, why we shouldn’t initialize physics constraint components in OnConstruction(Transform) function (which I really don’t know), and other ways to dynamically create physics constraint components.

If I edit Rama’s article, it will easily get reverted because I do not have a polished code at the moment. Therefore, I will be posting my extension here, and hopefully someone could give me tips. Feedback is welcomed.

[HR][/HR]

I wanted to be able to spawn actors and constrain the actors in a given space like a chain or a line from my base class to the end. I know that to spawn actors, I need to call on SpawnActor() any function that is not going to be called in the constructor. However, I am having trouble with the UPhysicsConstraintComponent where it would fail to be created when I call on CreateDefaultSubobject() in the OnConstruction(Transform) override function of my base class. The only thing I know that will allow me to set UPhysicsConstraintComponent successfully is by initializing it in the constructor.

I did another alternate method where I would store three TArrays in the base class, with each of them representing the subclass, physics constraint component, and the constraint names. The following code is placed in the base class’ header file. I use APawn because, frankly, everything is in APawn.



UCLASS()
class TUTORIAL_API ABaseClass : public APawn
{
	GENERATED_BODY()
public:
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=CustomProperties) TArray<ASubClass*> SubClassArray;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=CustomProperties) TArray<UPhysicsConstraintComponent*> PhysicsConstraintArray;
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=CustomProperties) TArray<FName> ConstraintNameArray;
	...
	...
}


Then to initialize the arrays, first you need to create the following components for the PhysicsConstraintArray and the ConstraintNameArray.



ABaseClass::ABaseClass(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
	for (int32 i = 0; i < 4; i++){
		//Names
		FString Name = "Frame_" + FString::FromInt(i);
		this->ConstraintNameArray.Push(FName(*Name));

		//Physics Constraints
		UPhysicsConstraintComponent* PhysicsConstraint = ObjectInitializer.CreateDefaultSubobject<UPhysicsConstraintComponent>(this, this->ConstraintNameArray*);
		PhysicsConstraint->SetWorldLocation(this->GetActorLocation());
		this->PhysicsConstraintArray.Push(PhysicsConstraint);
	}
	
	...
	...
}


Then in the OnConstruction(Transform) override function, you would then start initializing the subclass array. Note that the ConstraintNameArray.Num() is then used as an array size counter, so you don’t have to define constants here and there.



void ABaseClass::OnConstruction(const FTransform& Transform){
	Super::OnConstruction(Transform);

	//First loop needs initial values passed in, so successive calls can then be swapped for last initialized actors.
	FVector Height(0.0f, 0.0f, 100.0f); //How high from the initial world origin. Since the default floor mesh in a blank level is 80 UE4 units high, I set it to 100.
	FActorSpawnParameters Params;
	Params.Owner = this; //Setting the owner as the base class. When spawning actors, actors will have the owner as their parents.
	USceneComponent* Scene = this->GetRootComponent();
	UPrimitiveComponent* Primitive = this->BoxCollider;

	//Initializing Subclass array.
	for (int32 i = 0; i < ConstraintNameArray.Num(); i++){
		ASubClass* Class = this->GetWorld()->SpawnActor<ASubClass>(ASubClass::StaticClass(), Height, this->GetActorRotation(), Params);
		Class->BoxCollider->AttachTo(Params.Owner->GetRootComponent());
		
		//Set whatever constraining limits you need here
		UPhysicsConstraintComponent* Physics = this->PhysicsConstraintArray*;
		Physics->AttachTo(Scene, NAME_None, EAttachLocation::KeepWorldPosition);
		Physics->SetConstrainedComponents(Primitive, NAME_None, Class->BoxCollider, NAME_None);
		Physics->SetAngularSwing1Limit(EAngularConstraintMotion::ACM_Locked, 0.0f);
		Physics->SetAngularSwing2Limit(EAngularConstraintMotion::ACM_Locked, 0.0f);
		Physics->SetAngularTwistLimit(EAngularConstraintMotion::ACM_Locked, 0.0f);
		
		//Prepare for next iteration.
		Params = {};
		Params.Owner = Class;
		Scene = Class->GetRootComponent();
		Primitive = Class->BoxCollider;
	}
	
	...
	...
}


That is all.

Hi All,

I just created a tutorial on making an editor module A new, community-hosted Unreal Engine Wiki - Announcements and Releases - Unreal Engine Forums. I hope someone finds it useful!

This is my first tutorial so let me know if there is anything I should be doing differently in terms of style.

I’ve got another one coming up on component visualizers and then maybe one on custom editor modes if I’ve still got the energy.

Hi All Again,

As promised I’ve made another tutorial on using component visualizers: A new, community-hosted Unreal Engine Wiki - Announcements and Releases - Unreal Engine Forums. Please feel free to give me some feedback on it!