Wiki Code Tutorials

Blueprint Native Event

Dear Community,

Here is my new wiki tutorial on Blueprint Native Events!

BP Native Events allow you to have a core C++ implementation that can be overridden / extended in BP by your team mates!

Blueprint Native Events
https://wiki.unrealengine./Blueprints,_Empower_Your_Entire_Team_With_BlueprintNativeEvents#Adding_Call_To_Parent_Function

:slight_smile:

Before I invest time into , will the tutorials on the first post work with 4.8?

[=Slateboard;337687]
Before I invest time into , will the tutorials on the first post work with 4.8?
[/]

If you find a tutorial is not compiling in 4.8 just let me know!

If you find any uses of



(const class FPostConstructInitializeProperties& PCIP)
	: Super(PCIP)


replace it with



(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)


Epic has been providing absolutely wonderful compiler error / deprecation warnings since about 4.6, so most likely if something is out of date, the compiler will tell you exactly what to do.

:slight_smile:

Animated Vertex Positions With Movement Velocity Correction

Dear Community,

I’ve released a new wiki on how you can obtain animated vertex positions of character meshes!

https://wiki.unrealengine./Animated_Vertex_Positions_How_To_Obtain_Them


**C++ Code For You**

Here's the code I just finished writing to obtain accurate animated character vertex positions!



```


bool UVictoryBPFunctionLibrary::AnimatedVertex__GetAnimatedVertexLocations(
	USkeletalMeshComponent* Mesh, 
	TArray<FVector>& Locations,
	bool PerformPawnVelocityCorrection
){
	if(!Mesh || !Mesh->SkeletalMesh)  
	{
		return false;
	}

	//~~~~~~~~~~~~~
	Locations.Empty(); 
	//~~~~~~~~~~~~~
	 
	Mesh->ComputeSkinnedPositions(Locations);
	
	FTransform ToWorld = Mesh->GetComponentTransform();
	FVector WorldLocation = ToWorld.GetLocation();
	
	//Pawn Velocity Correction
	UPawnMovementComponent* MovementComp = nullptr;
	if(PerformPawnVelocityCorrection)
	{
		APawn* Pawn = Cast<APawn>(Mesh->GetOwner());
		MovementComp = (Pawn) ? Pawn->GetMovementComponent() : NULL;
	}
	bool DoVelocityCorrection = PerformPawnVelocityCorrection && MovementComp;
	//Pawn Velocity Correction
	 
	for(FVector& Each : Locations)
	{
		Each = WorldLocation + ToWorld.TransformVector(Each);
		if(DoVelocityCorrection)
		{
			Each += MovementComp->Velocity * FApp::GetDeltaTime();
		} 
	} 
	
	return true;
}


```



Enjoy!

:)

New Wiki Tutorial: How to create a blueprint node for sorting an array of Actors by field value.

https://wiki.unrealengine./Blueprint_Node:_Sort_Array_of_Actors_By_Field

Awesome!..

[=Nimgoble;342180]
New Wiki Tutorial: How to create a blueprint node for sorting an array of Actors by field value.

https://wiki.unrealengine./Blueprint_Node:_Sort_Array_of_Actors_By_Field
[/]

Thanks for sharing Nimgoble!

:slight_smile:

:slight_smile:

:slight_smile:

Finding out Which Streamed Level an Actor is In

Dear Community,

I’ve gone back and updated one of my earliest wikis.

Streamed Levels, Test If Actor Is In Level Bounds
https://wiki.unrealengine./Streamed_Levels,_Test_If_Actor_Is_In_Level_Bounds#Getting_the_Streaming_Level_Name

is a wiki on how to find out which streamed level an actor is contained in, during runtime!

My old code obtained the StreamingLevels array by pointer, and my new method retrieves the array by reference.

Notice how much simpler the code becomes when getting by reference!

I also use a ranged for loop to simplify the code even more :slight_smile:


**New Version**



```


//Getting the array by reference!
const TArray<ULevelStreaming*>& StreamedLevels = GetWorld()->StreamingLevels;

for(const ULevelStreaming* EachLevelStreaming : StreamedLevels)
{
	if( !EachLevelStreaming) 
	{
		continue;
	}
	
	ULevel* EachLevel =  EachLevelStreaming->GetLoadedLevel();
	
	//Is Level Valid and Visible?
	if( !EachLevel || !EachLevel->bIsVisible) 
	{
		continue;
	}
		 
	//Print Name of current Level Streaming to know which level the unit is in!
	ClientMessage( EachLevelStreaming->GetWorldAssetPackageName() );
	  
	//Is the Player Location Within Level's Bounds
	if(ALevelBounds::CalculateLevelBounds(EachLevel).IsInside(GetPawn()->GetActorLocation()))
	{
		ClientMessage("Yes Player Is Within Level");
	}
}


```


Original Code



//Get the Currently Streamed Levels
TArray<ULevelStreaming*>* StreamedLevels = &GetWorld()->StreamingLevels;
 
ULevel* EachLevel = NULL;
for(int32 v=0; v < StreamedLevels->Num(); v++)
{
	if( ! (*StreamedLevels)[v]) continue;
	//~~~~~~~~~~~~~~~~
 
	EachLevel =  (*StreamedLevels)[v]->GetLoadedLevel();
	if(!EachLevel) continue;
	//~~~~~~~~~~~~
 
	//Is Level Visible?
	if(!EachLevel->bIsVisible) continue;
	//~~~~~~~~~~~~~~~~~~~
 
	//Print Package Name For Level!
	ClientMessage( (*StreamedLevels)[v]->PackageName.ToString());
 
	//Is the Player Location Within Level's Bounds
	if(ALevelBounds::CalculateLevelBounds(EachLevel).IsInside(GetPawn()->GetActorLocation()))
	{
		ClientMessage("Yes Player Is Within Level");
	}
}



**Obtaining Streaming Level Name**

Please note I've adjusted the code to 4.8 so you can tell which streaming level the actor is in!



```


//Print Name of current Level Streaming to know which level the unit is in!
ClientMessage( EachLevelStreaming->**GetWorldAssetPackageName**() );


```



Enjoy!

:)

AI Dodge Wiki

Dear Community,

I’ve put up a wiki on how to quickly and easily implement an AI dodge mechanic!

https://wiki.unrealengine./AI_Dodge,_Rotate_Vector_Along_Axis_By_Angle#AI_Dodge

I discuss:

  1. Obtaining the perpedicular to the direction of the AI unit to its target

  2. Picking which way to dodge

  3. Choosing how far to dodge along the perpedicular

  4. How to ensure the UE4 Navigation System will find the dodge point on the nav mesh

  5. How to do all easily using FVector::RotateAngleAxis


**My C++ Code For You**



```


void AIDodge(bool DodgeRight=true, float Distance=256); //.h
 
void AYourAIClass::AIDodge(bool DodgeRight, float Distance) 
{
	//Location of unit who wants to dodge sideways, presumed to be facing target already
	FVector UnitLocation = GetActorLocation();
	FVector DirectionToActor = (OtherActor->GetActorLocation() - UnitLocation ).GetSafeNormal();
 
	//Optional, Ensure UE4 Nav mesh point will be found.
	DirectionToActor.Z = 0;
 
	//Rotate the direction by 90 to get perpendicular of direction to actor
	FVector Perpendicular = DirectionToActor.RotateAngleAxis(90,FVector(0,0,1));
 
	//Dodging to relative Left or Right?
	Perpendicular *= (DodgeRight) ? 1 : -1;
 
	//Tell Unit to move 256 units along perpendicular
	FVector GoalLocation = UnitLocation + Perpendicular * Distance;
 
	//Tell unit to move to location
	AAIController* AIControl = Cast<AAIController>(GetController());
	if(AIControl)
	{
	  AIControl->MoveToLocation(GoalLocation,0); //Optional Acceptance Radius
	}
}


```



Enjoy!

[=;1511]
https://www.mediafire./convkey/7d2b/fr75kbso2kkazru6g.jpg

Dear Community,

I have been hard at work making UE4 C++ Code tutorials!

I have added many pages of entirely code-focused tutorials, including both .h and .cpp,

to the UE4 Wiki Code Page!

https://wiki.unrealengine./Category:Code


**UE4 C++**

The entire focus of these tutorials is UE4 C++, not just regular C++.

Using my code samples will help you get a feel of how UE4 C++ works and help you get integrated with the UE4 API.


**Code Example

Custom Save System To Compressed Binary File**

Here’s a sample of the kind of code I am posting on the Wiki Code page:

is a code sample for how to Save any game data you want from UE4 C++ to a compressed binary filename of your choosing.


bool ControllerClass::SaveGameDataToFileCompressed(const FString& FullFilePath, 
	int32& SaveDataInt32,
	FVector& SaveDataVector,
	TArray<FRotator>& SaveDataRotatorArray
){
	FBufferArchive ToBinary;
	SaveLoadData(ToBinary,NumGemsCollected,PlayerLocation,ArrayOfRotationsOfTheStars); 
 
	**//Pre Compressed Size**
	ClientMessage("~ PreCompressed Size ~");
	ClientMessage(FString::FromInt(ToBinary.Num()));
 
	//
 
	**// Compress File 
	//tmp compressed data array**
	TArray<uint8> CompressedData;
	FArchiveSaveCompressedProxy Compressor = 
		FArchiveSaveCompressedProxy(CompressedData, ECompressionFlags::COMPRESS_ZLIB);
 
	**//Send entire binary array/archive to compressor**
	Compressor << ToBinary;
 
	**//send archive serialized data to binary array**
	Compressor.Flush();
 
	//
 
	**//Compressed Size**
	ClientMessage("~ Compressed Size ~");
	ClientMessage(FString::FromInt(CompressedData.Num()));
 
 
	if (!GFileManager) return false;
 
	**//vibes to file, return successful or not**
	if (FFileHelper::SaveArrayToFile(CompressedData, * FullFilePath)) 
	{
		**// Free Binary Arrays **
		Compressor.FlushCache();
		CompressedData.Empty();
 
		ToBinary.FlushCache();
		ToBinary.Empty();
 
		**// Close Buffer **
		ToBinary.Close();
 
		ClientMessage("File Save Success!");
 
		return true;
		//
	}
	else
	{
		**// Free Binary Arrays **
                Compressor.FlushCache();
		CompressedData.Empty();
 
		ToBinary.FlushCache();
		ToBinary.Empty();
 
		**// Close Buffer **
		ToBinary.Close();
 
		ClientMessage("File Could Not Be Saved!");
 
		return false;
		//
	}
}


**Summary**

Enjoy!


[/]


how would you go about decompressing the file and then loading the saved info?

[=Markyroson;348427]
how would you go about decompressing the file and then loading the saved info?
[/]

I show you how to decompress and load the data in section of my Binary Save System wiki:

Loading Compressed Binary Data
https://wiki.unrealengine./Save_System,Read%26_Write_Any_Data_to_Compressed_Binary_Files#Loading_Compresse


**C++ Code For You**

Here's the code most relevant to your question:



```


//Load the Compressed data array
	TArray<uint8> CompressedData;
	if (!FFileHelper::LoadFileToArray(CompressedData, *FullFilePath))
	{
		Optimize("FFILEHELPER:>> Invalid File");
		return false;
		//~~
	}
 
	// Decompress File 
	FArchiveLoadCompressedProxy Decompressor = 
		FArchiveLoadCompressedProxy(CompressedData, ECompressionFlags::COMPRESS_ZLIB);
 
	//Decompression Error?
	if(Decompressor.GetError())
	{
		Optimize("FArchiveLoadCompressedProxy>> ERROR : File Was Not Compressed ");
		return false;
		//
	}
 
	//Decompress
	FBufferArchive DecompressedBinaryArray;
	Decompressor << DecompressedBinaryArray;
 
	//~
	//		  Read the Data Retrieved by GFileManager
	//~
 
	FMemoryReader FromBinary = FMemoryReader(DecompressedBinaryArray, true); //true, free data after done
	FromBinary.Seek(0);

	SaveLoadData(FromBinary,NumGemsCollected,PlayerLocation,ArrayOfRotationsOfTheStars);


```



SaveLoadData uses the Memory Reader Archive to put the supplied data back in the variables, which are passed in by reference.

You could also pass in a UStruct or an actor that was spawned and then fill in the appropriate variable data that way!

Enjoy!

:)

AI Navigation, Custom Pathing Using Nav Modifiers, Nav Area Classes, and Query Filters

Dear Community,

I’ve just released a new wiki on how to use Nav Modifiers and Query Filters!

Wiki Link
https://wiki.unrealengine./AI_Custom_Pathing,_How_To_Use_Nav_Modifiers_Query_Filters#Nav_Area_Class


**Video**

https://youtube./watch?v=xwdVQQtQa8s

Use Case: Electric Currents and 2 Types of Characters

In my example, I have two types of units.

The blue unit is immune to electricity, and does not need to path around electric currents.

The red unit bids us all a fond farewell if it passes thruogh an electric current.

So in case I can’t just block of areas that have electric currents completely from the nav mesh, or else the blue unit cannot pass through freely as it should be able to, taking a shortcut as a result.

is a case where Nav Modifiers and Query Filters really shine!

I only want to filter out certain sections of the nav mesh for the red unit, while still allowing the blue unit to pass through those areas freely.


**C++ Code**

Here's the code I used to make a BP Node that allows you to use custom Navigation Query Filters in Blueprints!

Notice the in-Editor documentation!

//.h


```


/** Move to Location with optional Query Filter! 
*
* 1. Create Custon Nav Area Classes. 
*
* 2. Use Nav Modifier Volumes to apply custom area class data within the level, then
*
* 3. Create Query Filters which alter/exclude those custom nav areas. 
*
* 4. Can then choose to use the filters per character or even per Move To using node. 
*
*  <3
*
* @param FilterClass - Allows different types of units to path in different ways all the time, or path differently per Move To using node!
* @param bProjectDestinationToNavigation - Whether to attempt to find a nearby point on the nav mesh below/above/close to the supplied point. Uses the Agent's Nav Extent for the projection
* @param bStopOnOverlap - Add pawn's radius to AcceptanceRadius
* @param bCanStrafe - Set focus related flag: bAllowStrafe
* @return Whether the Pawn's AI Controller is valid and goal can be pathed to
*/ 
UFUNCTION(BlueprintCallable, Category = "VictoryBPLibrary|AI Move To")
static EPathFollowingRequestResult::Type Victory_AI_MoveToWithFilter(
	APawn* Pawn, 
	const FVector& Dest, 
	TSubclassOf<UNavigationQueryFilter> FilterClass = NULL,
	float AcceptanceRadius = 0,  
	bool bProjectDestinationToNavigation = false,
	bool bStopOnOverlap = false,
	bool bCanStrafe = false
);


```



//.cpp


```


EPathFollowingRequestResult::Type UVictoryBPFunctionLibrary::Victory_AI_MoveToWithFilter(
	APawn* Pawn, 
	const FVector& Dest, 
	TSubclassOf<UNavigationQueryFilter> FilterClass ,
	float AcceptanceRadius , 
	bool bProjectDestinationToNavigation ,
	bool bStopOnOverlap ,
	bool bCanStrafe 
){
	if(!Pawn) 
	{
		return EPathFollowingRequestResult::Failed;
	}
	
	AAIController* AIControl = Cast<AAIController>(Pawn->GetController());
	if(!AIControl) 
	{
		return EPathFollowingRequestResult::Failed;
	} 
	
	return AIControl->MoveToLocation(
		Dest, 
		AcceptanceRadius,
		bStopOnOverlap, 	//bStopOnOverlap
		true,						//bUsePathfinding 
		bProjectDestinationToNavigation, 
		bCanStrafe,			//bCanStrafe
		FilterClass			//<~~~
	);
}


```



Enjoy!

Ah, i forgot about thread (always skipping the pinned threads). Gonna post my
simple Session Code Tutorial and examples, as well as explanations here too if i’m allowed!

How to use Sessions in C++!

PS: If it’s not allowed by you just tell me and i will remove it again. :open_mouth:

[=;351574]
Ah, i forgot about thread (always skipping the pinned threads). Gonna post my
simple Session Code Tutorial and examples, as well as explanations here too if i’m allowed!

How to use Sessions in C++!

PS: If it’s not allowed by you just tell me and i will remove it again. :open_mouth:
[/]

Thank you for sharing !

That’s quite the nicely formatted and extensive tutorial on the important topic of Network Game Sessions!

Great work!

:heart:

Thanks for sharing your tutorials, wiki already added to bookmarks :slight_smile:

[=;351574]
Ah, i forgot about thread (always skipping the pinned threads). Gonna post my
simple Session Code Tutorial and examples, as well as explanations here too if i’m allowed!

How to use Sessions in C++!

PS: If it’s not allowed by you just tell me and i will remove it again. :open_mouth:
[/]

Great work ! That’ll be a super valuable resource! Tweeted it out too!

Wiki on BlueprintImplementableEvent updated to 4.8 Standards

Dear Community,

I’ve now upgraded my BlueprintImplementableEvent wiki to 4.8 standards!

Empower Your Entire Team With BlueprintImplementableEvent

Most notably, it is a recent new standard that BP Implementable events should not be virtual.

:slight_smile:

PhysX Wiki Updated to 4.9

Dear Community,

I’ve now updated my PhysX wiki to 4.9

Specifically, all PToU conversions were moved from PhysicsPublic.h to PhysXPublic.h

Enjoy!

Get Vertices Wiki Updated

Dear Community,

I’ve now updated the Accessing Mesh Triangles and Vertex Positions wiki to 4.9!

:slight_smile:

4.9.0 ~ FHitResult Now Returns Distance From Start to Impact Point

Dear Community,

Epic accepted my pull request to expose Distance information as part of FHitResult!

The PhysX engine was always returning information, so my requested Engine code change did not affect performance at all.

The advantage is that now whenever you do a trace, you already have the non-squared actual distance from the start of the trace to the impact point available to you!

Trace Functions Wiki Updated to 4.9.0

Enjoy!

:slight_smile: