To do this in C++ / Unreal, you need to do the following either in (or called by) EventTick or on a timer:
// Set up parameters for getting the player viewport
FVector PlayerViewPointLocation;
FRotator PlayerViewPointRotation;
// Get player viewport and set these parameters
GetWorld()->GetFirstPlayerController()->GetPlayerViewPoint(
OUT PlayerViewPointLocation,
OUT PlayerViewPointRotation
);
// Parameter for how far out the the line trace reaches
float Reach = 100.f;
FVector LineTraceEnd = PlayerViewPointLocation + PlayerViewPointRotation.Vector() * Reach;
// Set parameters to use line tracing
FHitResult Hit;
FCollisionQueryParams TraceParams(FName(TEXT("")), false, GetOwner()); // false to ignore complex collisions and GetOwner() to ignore self
// Raycast out to this distance
GetWorld()->LineTraceSingleByObjectType(
OUT Hit,
PlayerViewPointLocation,
LineTraceEnd,
FCollisionObjectQueryParams(ECollisionChannel::ECC_PhysicsBody),
TraceParams
);
// See what if anything has been hit and return what
AActor* ActorHit = Hit.GetActor();
if (ActorHit) {
UE_LOG(LogTemp, Error, TEXT("Line trace has hit: %s"), *(ActorHit->GetName()))
}
This will return the first actor that has been hit. If you want to find a specific actor, you can say:
if (ActorHit == Cast<AYourCustomActorClass>YourCustomClassCast<AYourCustomActorClass>(YourCustomClass))
Which will only return true if the first item hit is the specific class you're looking for.