Search code examples
c++unreal-engine4

ue4 c++ destory on hit if specifc actor


I am making a projectile which I want to destroy enemy objects which will be basic floating objects
How do I get it so both objects are destroyed if hit by a specific actor.

 void APrimaryGun::NotifyHit(UPrimitiveComponent* MyComp, AActor* Other, UPrimitiveComponent* OtherComp, bool bSelfMoved, FVector HitLocation, FVector HitNormal, FVector NormalImpulse, const FHitResult& Hit)
{
    if (GEngine)
    {
        GEngine->AddOnScreenDebugMessage(-1, 1.5, FColor::Red, "Hit");
    }

    Destroy();

    Other->Destroy();
}

above is what I have at the moment but destroys anything it hits which is not what I want.

I believe it should be a simple if statement but am unsure how to write it.
Thanks in advance


Solution

  • Other is any AActor, so every time you hit an AActor you're going to destroy the projectile and Other. I assume what you want to happen is that if your projectile hits anything, the projectile is destroyed, and if the object it hits is the right type, then that object is also destroyed.

    Presumably the objects that you want to be destroyed by the projectile are derived from AActor. Something like:

    class DestroyableEnemy : public AActor
        { //class definition
    
        };
    

    So you know your Other is a pointer to an AActor, what you want to know if, specifically, it's a pointer to a DestroyableEnemy (or whatever you've named it). The two ways you can do that in C++ are dynamic_cast and the typeid operator. The way I know how to do it offhand is with a dynamic_cast. You're going to TRY and cast the generic AActor to a DestroyableEnemy. If it IS a DestroyableEnemy, you get a pointer to it. If it isn't, you just get a null pointer.

    DestroyableEnemy* otherEnemy = dynamic_cast<DestroyableEnemy*>(Other);
    if( otherEnemy ){ 
       //if otherEnemy isn't null, the cast succeeded because Other was a destroyableEnemy, and you go to this branch
        otherEnemy->Destroy();
    }else{
        // otherEnemy was null because it was some other type of AActor
        Other->SomethingElse(); //maybe add a bullet hole? Or nothing at all is fine
    };
    

    Adapted from: https://en.wikibooks.org/wiki/C%2B%2B_Programming/RTTI