JuniorCodeVery commonNot answered yet
How do you perform a line trace in C++ in Unreal Engine?
Implement a single-line trace from a weapon's muzzle straight forward and return the first blocking hit, or nullptr if the ray hits nothing.
Constraints:
Endmust be an absolute world-space point, not a direction vector.- Exclude the firing actor (and its owner) from the trace so it cannot hit itself.
- Trace on
ECC_Visibility; read theFHitResultonly after the boolean result istrue.
AActor* AWeapon::FireTrace()
{
// your code here
}
Write the implementation.
Call GetWorld()->LineTraceSingleByChannel(Hit, Start, End, Channel, Params). It writes the first blocking hit into an FHitResult and returns true if something was hit. Start and End are world-space points.
- ✗Passing a direction vector instead of an absolute world-space
Endpoint - ✗Forgetting to add the tracing actor to
FCollisionQueryParamsand hitting itself - ✗Reading
FHitResultfields without first checking the boolean return value
- →How do you trace against multiple objects instead of stopping at the first blocker?
- →What is the difference between tracing by channel and tracing by object type?
A simple line trace
void AWeapon::FireTrace()
{
const FVector Start = GetActorLocation();
const FVector End = Start + GetActorForwardVector() * 5000.0f;
FHitResult Hit;
// Exclude the weapon's owner from the trace so it doesn't hit itself
FCollisionQueryParams Params;
Params.AddIgnoredActor(this);
Params.AddIgnoredActor(GetOwner());
const bool bHit = GetWorld()->LineTraceSingleByChannel(
Hit, Start, End, ECC_Visibility, Params);
if (bHit)
{
// Hit.GetActor() — the actor that was hit
// Hit.ImpactPoint — the world-space point of impact
// Hit.ImpactNormal — the surface normal at the impact point
UE_LOG(LogTemp, Log, TEXT("Hit: %s"), *GetNameSafe(Hit.GetActor()));
DrawDebugLine(GetWorld(), Start, Hit.ImpactPoint, FColor::Red, false, 1.0f);
}
else
{
DrawDebugLine(GetWorld(), Start, End, FColor::Green, false, 1.0f);
}
}
Key points:
Endis an absolute world-space point, not a direction.- The function returns
trueonly on a blocking hit; always check the result before readingHit. FHitResultis filled synchronously — the data is available right after the call.