需要用到DeprojectScreenPositionToWorld()方法,这个方法与GetViewportSize一样,只能在PlayerController里使用。
新建一个PlayerController
1 void AMyPlayerController::setAll() {
2
3 int32 viewx;
4 int32 viewy;
5 GetViewportSize(viewx,viewy);
6
7 FVector WorldLocation;
8 FVector WorldDirection;
9
10 if (DeprojectScreenPositionToWorld(viewx * 0.5, viewy * 0.5, WorldLocation, WorldDirection)) {
11 //UE_LOG(LogTemp, Warning, TEXT("WorldDirection is %s"), *WorldDirection.ToString());
12 GetWorld()->GetFirstPlayerController()->bShowMouseCursor = false;
13 }
14
15 FHitResult hit;
16 FVector startLocation;
17 FVector endLocation;
18 startLocation = PlayerCameraManager->GetCameraLocation();
19 endLocation = startLocation + PlayerCameraManager->GetCameraRotation().Vector() * 1000;
20
21 DrawDebugLine(GetWorld(),startLocation,endLocation,FColor::Red,false,-1.0f,'\000',5.0f);
22
23 auto pawn = GetWorld()->GetFirstPlayerController()->GetPawn();
24
25
26 if (GetWorld()->LineTraceSingleByChannel(
27 hit,
28 startLocation,
29 endLocation,
30 ECollisionChannel::ECC_Vehicle,
31 FCollisionQueryParams(),
32 FCollisionResponseParams(ECR_Block)
33 )) {
34 UE_LOG(LogTemp, Warning, TEXT("Name is %s"), *hit.GetActor()->GetName());
35 }
36
37 }
38
39
40
41 void AMyPlayerController::Tick(float DeltaSeconds) {
42 setAll();
43 }
WorldLocation就是Camera的Location。
文中使用的按照通道进行射线检测:
ECollisionChannel::ECC_Vehicle, 检测的物体必须是Vehicle类型
FCollisionQueryParams(), 是否开启复杂碰撞,是否忽略自己等等。
FCollisionResponseParams(ECR_Block) 检测的物体必须是Block的碰撞预设。
DeprojectScreenPositionToWorld(viewx * 0.5, viewy * 0.5, WorldLocation, WorldDirection) //前两个坐标是画布的中心点,第四个参数是鼠标在三维世界的坐标。当画面指向X轴的时候,x的值为1.以此类推。
此节没有图例。