Search code examples
unreal-engine4

LineTraceSingle Collision Not Working (Unreal Engine 4)


I'm having quite a difficult time trying to use LineTraceSingle to detect a hit.

void ACustomActor::Tick(float DeltaTime){
    bool isHit = world->LineTraceSingle(HitResult, start, endV,
            traceParams, FCollisionObjectQueryParams(ECC_WorldStatic));
}

My understanding is this is sending out a line from the starting point to the ending point and trying to discover the first "block" (hit) event from an object of type WorldStatic.

I am drawing a debug line with the following code:

    DrawDebugLine(GetWorld(), start, endV, FColor::Blue, true, 1.0F, (uint8)'\000', 5.0f);

This is working, and I can see my line going through a wall.

enter image description here enter image description here

As you can see above, the object type of this wall is indeed WorldStatic and it blocks all collisions.

What am I doing wrong?


Solution

  • Answer

    world needs to be GetWorld()


    Explanation

    I was saving a reference to the UWorld* pointer in my Actor's constructor, like so:

    MyActor::MyActor()
    {
        PrimaryActorTick.bCanEverTick = true;
        world = GetWorld();
    }
    

    The problem is GetWorld() returns NULL here! I'm surprised there wasn't any errors thrown actually... To prevent this from happening this call should be somewhere else, like BeginPlay():

    void AForceField::BeginPlay()
    {
        Super::BeginPlay();
        world = GetWorld();
    }
    

    But once I actually looked up GetWorld(), I saw it was a "getter for the cached world pointer". So there's really no point in saving that to a variable.


    TL;DR

    Don't save GetWorld() to a variable.