Trace a line to where the character's camera is looking

Hi!

I’m using Unreal 5.2.1 with C++.

I’m using LineTraceSingleByChannel and I want to trace the line to where the character’s camera is looking. Now I’m using this: FVector TraceEnd = GetActorLocation() + GetActorForwardVector() * 1000.0f;, but it doesn’t work.

This is the code:

// FHitResult will hold all data returned by our line collision query
FHitResult Hit;

// We set up a line trace from our current location to a point 1000cm ahead of us
FVector TraceStart = GetActorLocation();
FVector TraceEnd = GetActorLocation() + GetActorForwardVector() * 1000.0f;

FCollisionQueryParams QueryParams;
QueryParams.AddIgnoredActor(this);

// To run the query, you need a pointer to the current level, which you can get from an Actor with GetWorld()
// UWorld()->LineTraceSingleByChannel runs a line trace and returns the first actor hit over the provided collision channel.
GetWorld()->LineTraceSingleByChannel(Hit, TraceStart, TraceEnd, TraceChannelProperty, QueryParams);

// You can use DrawDebug helpers and the log to help visualize and debug your trace queries.
DrawDebugLine(GetWorld(), TraceStart, TraceEnd, Hit.bBlockingHit ? FColor::Blue : FColor::Red, false, 5.0f, 0, 10.0f);
UE_LOG(LogTemp, Log, TEXT("Tracing line: %s to %s"), *TraceStart.ToCompactString(), *TraceEnd.ToCompactString());

// If the trace hit something, bBlockingHit will be true,
// and its fields will be filled with detailed info about what was hit
if (Hit.bBlockingHit && IsValid(Hit.GetActor()))
{
	UE_LOG(LogTemp, Log, TEXT("Trace hit actor: %s - Impact Point: %s - Location: %s"), *Hit.GetActor()->GetName(), *Hit.ImpactPoint.ToString(), *Hit.Location.ToString());
}
else {
	UE_LOG(LogTemp, Log, TEXT("No Actors were hit"));
}

How can I trace a line to where the character’s camera is looking?

Thanks!

I think I’ve found the solution.

I’ve changed this line:

FVector TraceEnd = GetActorLocation() + GetActorForwardVector() * 1000.0f;

With this line:

FVector TraceEnd = GetActorLocation() + FirstPersonCameraComponent->GetForwardVector() * 1000.0f;

By the way, I’m using the FPS template.

GetActorForwardVector() on the character won’t be where you’re looking. It’ll just be the forward direction that your character will walk or move forward. Also, you’ll need to check where your pivot is.

You found the correct solution (so you can check your own reply as the solution to close this thread). The Camera will point in the appropriate direction. You may wish to also take the camera’s position since I think most characters pivots are in the center of the character, not where the head is.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.