MiddleCodeCommonNot answered yet
How do you find the object under the mouse cursor or at screen center?
On a APlayerController, find the actor under the mouse cursor in the world. Convert the cursor's screen position into a world-space ray, trace along it, and report the actor that was hit.
Constraints:
- Do not treat screen pixel coordinates as world points — deproject first.
- Trace on
ECC_Visibility; returnnullptrwhen nothing is hit. - Read the hit actor only after confirming the trace actually hit.
AActor* AMyPlayerController::ActorUnderCursor()
{
// your code here
}
Write the implementation.
Convert the screen point to a world ray with APlayerController::DeprojectScreenPositionToWorld, then line trace along it. For the cursor, GetHitResultUnderCursor does both steps in one call and fills an FHitResult.
- ✗Treating screen pixel coordinates as world-space points without deprojecting first
- ✗Forgetting that
bShowMouseCursormust be enabled forGetHitResultUnderCursorto work - ✗Confusing deproject (screen → world ray) with project (world → screen)
- →How would you trace from the exact center of the screen instead of the cursor?
- →Why does a deprojected ray need both an origin and a direction, not just a point?
Contents
Object under the cursor
The shortest path is GetHitResultUnderCursor, which deprojects and traces for you:
void AMyPlayerController::TraceUnderCursor()
{
FHitResult Hit;
const bool bHit = GetHitResultUnderCursor(ECC_Visibility, false, Hit);
if (bHit && Hit.GetActor())
{
UE_LOG(LogTemp, Log, TEXT("Under cursor: %s"),
*GetNameSafe(Hit.GetActor()));
}
}
Object at screen center
Here you deproject manually: a screen point → a ray origin and direction.
void AMyPlayerController::TraceFromScreenCenter()
{
int32 ViewportX, ViewportY;
GetViewportSize(ViewportX, ViewportY);
const FVector2D ScreenCenter(ViewportX * 0.5f, ViewportY * 0.5f);
FVector WorldOrigin, WorldDirection;
if (!DeprojectScreenPositionToWorld(
ScreenCenter.X, ScreenCenter.Y, WorldOrigin, WorldDirection))
return;
const FVector End = WorldOrigin + WorldDirection * 10000.0f;
FHitResult Hit;
FCollisionQueryParams Params;
Params.AddIgnoredActor(GetPawn());
if (GetWorld()->LineTraceSingleByChannel(
Hit, WorldOrigin, End, ECC_Visibility, Params))
{
UE_LOG(LogTemp, Log, TEXT("At screen center: %s"),
*GetNameSafe(Hit.GetActor()));
}
}
DeprojectScreenPositionToWorld returns the ray's world-space origin and its direction — screen pixels alone are not world coordinates.
Contents