# "Onhit" function not working correctly

**URL:** <https://forums.unrealengine.com/t/onhit-function-not-working-correctly/450680>\
**Category:** World Creation\
**Tags:** unreal-engine, FeatureRequest, first-person-templat, Physics, UE4, Blueprint, CPP, question\
**Created:** [June 14, 2019, 1:02pm UTC](https://forums.unrealengine.com/t/onhit-function-not-working-correctly/450680 "2019-06-14T13:02:48Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![anonymous\_user\_58137bd7](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@anonymous\_user\_58137bd7](https://forums.unrealengine.com/u/anonymous_user_58137bd7)\
**Post date:** [June 14, 2019, 1:02pm UTC](https://forums.unrealengine.com/t/onhit-function-not-working-correctly/450680/1 "2019-06-14T13:02:48Z")

</div>

I am new to unreal and doing the tutorial from this video here:

[![](https://d3kjluh73b9h9o.cloudfront.net/original/4X/3/6/e/36eb0a5846e50cee2b0d14490e32062f14bcf88e.jpeg "Intro to Unreal Engine C++ Tutorial") ](https://www.youtube.com/watch?v=D4UM73O7Zxs)

The “Onhit” function the projectile class is not doing what its supposed to do.

Here is the projectile.h file:

```
        #pragma once

   #include "CoreMinimal.h"
   #include "GameFramework/Actor.h"
     #include "FPSProjectile.generated.h"

     class UProjectileMovementComponent;
      class USphereComponent;

     UCLASS()
      class AFPSProjectile : public AActor
      {
GENERATED_BODY()

      protected:

      /** Sphere collision component */
        UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category= "Projectile")
            	USphereComponent* CollisionComp;

   /** Projectile movement component */
    UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Movement")
    UProjectileMovementComponent* ProjectileMovement;

      public:

  AFPSProjectile();

   /** called when projectile hits something */
     UFUNCTION(BlueprintCallable)
	virtual void OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* 
      OtherComp, FVector NormalImpulse, const FHitResult& Hit);

     / **Returns CollisionComp subobject** /
      USphereComponent* GetCollisionComp() const { return CollisionComp; }

   / **Returns ProjectileMovement subobject** /
   UProjectileMovementComponent* GetProjectileMovement() const { return ProjectileMovement; }
       };

```

Here is the projectile.cpp file:

```
      #include "FPSProjectile.h"
       #include "GameFramework/ProjectileMovementComponent.h"  
        #include "Components/SphereComponent.h"

      AFPSProjectile::AFPSProjectile() 
      {
    // Use a sphere as a simple collision representation
     CollisionComp = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComp"));
     	CollisionComp->InitSphereRadius(5.0f);
       CollisionComp->SetCollisionProfileName("Projectile");

          CollisionComp->OnComponentHit.AddDynamic(this, &AFPSProjectile::OnHit);	
                // set up a notification for when this component hits something 

```

`

```
           // Players can't walk on it
   CollisionComp->SetWalkableSlopeOverride(FWalkableSlopeOverride(WalkableSlope_Unwalkable, 0.f));
    CollisionComp->CanCharacterStepUpOn = ECB_No;

  // Set as root component
  RootComponent = CollisionComp;

 // Use a ProjectileMovementComponent to govern this projectile's 
 ProjectileMovement = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("ProjectileComp"));
  ProjectileMovement->UpdatedComponent = CollisionComp;
  ProjectileMovement->InitialSpeed = 3000.f;
   ProjectileMovement->MaxSpeed = 3000.f;
    ProjectileMovement->bRotationFollowsVelocity = true;
    ProjectileMovement->bShouldBounce = true;

   // Die after 3 seconds by default
    InitialLifeSpan = 3.0f;
      }

      void AFPSProjectile::OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* 
       OtherComp, FVector NormalImpulse, const FHitResult& Hit)
         {
    // Only add impulse and destroy projectile if we hit a physics
    if ((OtherActor !=	NULL) && (OtherActor != this) && (OtherComp != NULL) && OtherComp- 
         >IsSimulatingPhysics())
       {
         	OtherComp->AddImpulseAtLocation(GetVelocity() * 100.0f, GetActorLocation());
	
	      Destroy();
     }
      }

```

---

<div class="post-metadata">

**Author:** ![staticvoidlol](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@staticvoidlol](https://forums.unrealengine.com/u/staticvoidlol)\
**Post date:** [June 24, 2019, 2:58pm UTC](https://forums.unrealengine.com/t/onhit-function-not-working-correctly/450680/2 "2019-06-24T14:58:05Z")

</div>

Don’t bind the delegate in the constructor as it’s not reliable. Move the following line from the constructor to e.g. BeginPlay:

```
CollisionComp->OnComponentHit.AddDynamic(this, &AFPSProjectile::OnHit);  

```

You can override BeginPlay by adding the following to your header:

```
public:
        virtual void BeginPlay() override;

```

and implement it in your cpp file as follows:

```
void AFPSProjectile::BeginPlay()
{
            // Always remember to call Super
    	    Super::BeginPlay();
    
            // Bind delegate
            CollisionComp->OnComponentHit.AddDynamic(this, &AFPSProjectile::OnHit);
}
```

---

<div class="post-metadata">

**Author:** ![T0NGSTAR](https://d1ap1mz92jnks1.cloudfront.net/user_avatar/forums.unrealengine.com/t0ngstar/32/480390_2.png) [@T0NGSTAR](https://forums.unrealengine.com/u/T0NGSTAR)\
**Post date:** [May 1, 2022, 9:50pm UTC](https://forums.unrealengine.com/t/onhit-function-not-working-correctly/450680/3 "2022-05-01T21:50:54Z")

</div>

Thx Man! This is really helpful!
