UE4 How to On Actor Hit C++

I’m trying to make a jump mechanic in my game and I need to use On Actor Hit or any sort of On Collision begin or whatever to get the name of what my player is colliding with. This works perfectly when I use blueprint and I don’t need to add anything or change anything. But for C++ it’s weird. I see tutorials all talking about adding this sphere for collision checking but I see that as unnessacry as my pawn has perfectly working collision and it works just fine in blueprints. So I am wondering, how can I check in C++ without adding all these spheres and stuff. Also I am using a pawn and I am not switching to a character.

What are you using that works in blueprints ?

I went to my mesh and just did on component hit in blueprints and just made it simply display the other objects name to see if it works and it did.

Then do the same in c++ :wink:

    GetMesh()->OnComponentHit.AddDynamic(this, &AMyCharacter::OnHit)

OnHit needs to be like this I think

    UFUNCTION()    
    void OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit)
3 Likes

There is no function called Get Mesh. In Get Owner, there is functions in it like On Actor Hit and On Actor Begin Overlap but there is no Add Dynamic in those functions and I am just so confused.

Edit: I did some testing and I found out that getowner was pointing at the mesh, it was pointing at the pawn as a whole. So I needed the actual mesh to access the event. But I don’t know how to get the mesh. It is the root component so I tried getting it that way but I need it to return an AActor, and the root component returns a USceneComponent.

For anyone who comes across this topic looking for an answer…

My class inherits from AActor and I added a mesh component to the class myself in the header…

UPROPERTY(VisibleAnywhere)
UStaticMeshComponent* MeshComp;

Then in the constructor…

MeshComp = CreateDefaultSubobject(“MeshComp”);
MeshComp->OnComponentHit.AddDynamic(this, &AMyClass::OnActorHit);
RootComponent = MeshComp;

Then implement…

void AMyClass::OnActorHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector normalImpulse, const FHitResult& Hit)

Credit to Tom Looman’s class, where I learned this.

1 Like

Dont initialize a delegate in the constructor. do it in either PostInitializeComponents() or BeginPlay();

void ALFLava::PostInitializeComponents()
{
Super::PostInitializeComponents();
MeshComp->OnComponentHit.AddDynamic(this, &ALFLava::ALFLava::OnCompHit);
}

That should fix it.

2 Likes