在一般的射击游戏中,会有通过十字准星在世界中的坐标为起点开始进行射线检测,从而去确定最终的射击位置。
如何获取屏幕中心2D坐标并转化为世界坐标呢?
//获取屏幕在世界中的坐标和方向
if (GEngine && GEngine->GameViewport)
{
FVector2D ViewPortSize;
GEngine->GameViewport->GetViewportSize(ViewPortSize);
const FVector2D HalfViewPortSize = FVector2D(ViewPortSize.X/2,ViewPortSize.Y/2);
const APlayerController* PC = UGameplayStatics::GetPlayerController(GetWorld(),0);
FVector WorldLocation;
FVector WorldDirection;
PC->DeprojectScreenPositionToWorld(HalfViewPortSize.X,HalfViewPortSize.Y,WorldLocation,WorldDirection);
FVector End = SocketLocation + WorldDirection*20000;
FHitResult Hit;
FCollisionQueryParams QueryParams;
QueryParams.AddIgnoredActor(this);
GetWorld()->LineTraceSingleByChannel(Hit,WorldLocation,End,ECollisionChannel::ECC_Visibility,QueryParams);
if (Hit.GetActor())
{
End = Hit.Location;
}
//生成子弹
FRotator Rotation = UKismetMathLibrary::FindLookAtRotation(SocketLocation,End);
GetWorld()->SpawnActor<AMagicProjectile>(MagicProjectileClass,SocketLocation,Rotation,Params);
//DrawDebugLine(GetWorld(),SocketLocation,End,FColor::Green,false,5.0f,0,2);
}
GetViewportSize通过这个接口获取试图大小,注意屏幕坐标(0,0)是从左上角开始的,如果有需要处理准星偏移,注意偏移量的加减。
DeprojectScreenPositionToWorld通过这个接口处理2D转3D坐标。