keywords: UE4, C++, Trace Line, LineTraceSingle, LineTraceSingleByChannel

Line Trace

Using line trace to check if there’s a obstacle between two points.

FCollisionQueryParams TraceParams(TEXT("TraceActor"), true, this);
TraceParams.bTraceAsyncScene = true;
TraceParams.bReturnPhysicalMaterial = false;
TraceParams.bTraceComplex = false;

FHitResult Hit(ForceInit);
GetWorld()->LineTraceSingleByChannel(Hit, SelfLoc, TargetLoc, ECC_Visibility, TraceParams);

UStaticMeshComponent* MeshComp = Cast<UStaticMeshComponent>(Hit.GetComponent());
if (MeshComp)
{
    //other code ...
}
Sphere Trace

Using sphere trace to get all obstacles between two points.

AMyCharacter::TraceTest()
{
    if (FollowCameraComp)
    {
        FVector StartLoc = FollowCameraComp->GetComponentLocation();
        FVector TargetLoc = StartLoc + FollowCameraComp->GetComponentRotation().Vector() * 200.f;

        TArray<AActor*> IngoreActors;
        IngoreActors.Add(this);

        TArray<FHitResult> HitRetArray;

        bool isHit = UKismetSystemLibrary::SphereTraceMultiByProfile(GetWorld(), StartLoc, TargetLoc, 100.f, TEXT("BlockAll"), false, IngoreActors, EDrawDebugTrace::Type::None, HitRetArray, true);
        if (isHit)
        {
            for (FHitResult Hit : HitRetArray)
            {
                if (AActor* Actor = Hit.Actor.Get())
                {
                    if (Actor)
                    {
                        //other code ...
                    }
                }
            }
        }
    }
}

一些普通人也获得了巨大的成功,只是因为他们不知道何时放弃。