The crosshair location and direction differ from hit location, Why did that?
I used yellow DrawDebugLine to simulate the crosshair location and other one which is a red line for the hit location and the result is really strange.
I reviewed my c++ code step by step to discover the problem but every thing is as Mr @Ben did.
bool ATankPlayerController::GetSightRayHitLocation(FVector& HitLocation) const
{
HitLocation = FVector(1.0);
int32 OUT ViewportSizeX, OUT ViewportSizeY;
GetViewportSize(ViewportSizeX, ViewportSizeY);
auto ScreenLocation = FVector2D(ViewportSizeX * CrosshairXLocation, ViewportSizeY * CrosshairYLocation);
FVector OUT LookDirection;
if (GetLookDirection(ScreenLocation, LookDirection))
{
GetLookVectorHitLocation(LookDirection, HitLocation);
}
return true;
}
bool ATankPlayerController::GetLookDirection(FVector2D ScreenLocation, FVector& LookDirection) const
{
FVector OUT WorldLocation ; // To be discarded
return DeprojectScreenPositionToWorld(
ScreenLocation.X,
ScreenLocation.Y,
WorldLocation,
LookDirection);
}
bool ATankPlayerController::GetLookVectorHitLocation(FVector LookDirection, FVector& HitLocation) const
{
auto StartLocation = PlayerCameraManager->GetCameraLocation();
auto EndLocation = StartLocation + (LookDirection * LineTraceRange);
DrawDebugLine(GetWorld(), StartLocation, EndLocation , FColor::Yellow, false, 0, 0, 10);
FHitResult OUT HitResult;
if (GetWorld()->LineTraceSingleByChannel(
HitResult,
StartLocation,
EndLocation,
ECollisionChannel::ECC_Visibility
))
{
HitLocation = HitResult.Location;
DrawDebugLine(GetWorld(), StartLocation, StartLocation + (HitLocation.GetSafeNormal() * LineTraceRange), FColor::Red, false, 0, 0, 10);
return true;
}
HitLocation = FVector(0);
return false; // Line trace didn't succeed
}