Detect wall collision Unreal Engine 5

Hey, welcome here!

Today we are going to check how could we detect wall collision from C++ code in Unreal Engine 5, be sure that you have installed UE5 and Rider.

  • Let’s first open our blueprint anD check what we have there. For this find “BP_FirstPersonCharacter”
  • Open it, and you will see something like that:
  • Click on link “Open Full Blueprint Editor” and now you could see more interesting window
  • Now we have to open “Viewport” tab
  • And now you could see how your character looks like from the outside, little bit weird but it is ok for the first face 🙂
  • I want to pay attention on this capsule
  • It is a typical approach for most of engines, put capsule for interaction with world around.
  • Now we have to get somehow this visual capsule in code and all parameters and events which it has.
  • Now it is time to go to our C++ code, try to find “WallRunCharacter” C++ class
  • Double click on it, and you should see opened Rider.
  • It should open “WallRunCharacter.cpp” file by default
  • if it is not, find this file in Explorer
  • Now, find method:
void AWallRunCharacter::BeginPlay()
  • And insert there code:
GetCapsuleComponent()->OnComponentHit.AddDynamic(this, &AWallRunCharacter::OnCapsuleHit());
  • As you can see, we don’t have OnCapsuleHit() in our code, lets add it.
  • Go to WallRunCharacter.h and create a new method in private section:
private:
UFUNCTION()
void OnCapsuleHit();
  • Unfortunately, it is not enough, that’s why we have to check what UE expect from this function, if you check OnComponentHit implementation, it has:
UPROPERTY(BlueprintAssignable, Category="Collision")
FComponentHitSignature OnComponentHit;
  • And go deeper FComponentHitSignature, there will be:
DECLARE_DYNAMIC_MULTICAST_SPARSE_DELEGATE_FiveParams( FComponentHitSignature, UPrimitiveComponent, OnComponentHit, UPrimitiveComponent*, HitComponent, AActor*, OtherActor, UPrimitiveComponent*, OtherComp, FVector, NormalImpulse, const FHitResult&, Hit );
  • We need everything after OnComponentHit , copy it. Past into method and remove , after each class name, you should have something like that:
void OnCapsuleHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit );
  • And in CPP file function itself and implement this method. For now, let’s check that it works, and debug message will be enough
GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Blue, TEXT("Capsule has been hit"));
  • And now we have to recompile our code, this is should be done from Unreal Engine Editor.
  • Run your Game, and hit the wall:

If you have questions – join our Discord and ask! And don’t forget to subscribe on Patreon!

Cheers!