/ Quickie

UE4 Quickie: Smarter Object Delete

In many kinds of games, it becomes necessary to delete objects that no longer have gameplay relevance, like dead characters and destroyed environments. However, having those objects disappear while you're looking at them breaks immersion.

Ideally, objects should disappear when nobody's looking at them. It's much easier to accept that an object was removed while you weren't looking at it than to accept that objects just blink out of existence periodically.

This is a relatively easy thing to implement. Here's a C++ implementation from our base character class that we use to get rid of corpses after a while.

void ABaseCharacter::DestroyIfOffscreen()
{
    if (!WasRecentlyRendered(.5))
    {
        Destroy();
    }
    else
    {
        // Still on screen, try again in a bit
        FTimerHandle RespawnTimerHandle;
        GetWorld()->GetTimerManager().SetTimer(RespawnTimerHandle, this, &ABaseCharacter::DestroyIfOffscreen, 0.5f, false);
    }
}

When called, this checks if the character has been rendered recently. WasRecentlyRendered is a pretty good proxy for whether an actor has been onscreen recently. There are occasional situations where an actor will be "rendered" despite not being visible on screen, but generally this approach works well.

We could do a simple camera frustum check, but that wouldn't take into account occlusion, nor would it take into account reflection captures or actors rendered into SceneCaptureComponent2D.

Here, you can see it in action:

UE4 Quickie: Smarter Object Delete
Share this

Subscribe to Recursive Blueprints