UE5 C++ 射线检测

发布于:2024-04-18 ⋅ 阅读:(44) ⋅ 点赞:(0)

一.声明四个变量

	FVector StartLocation;
	FVector ForwardVector;
	FVector EndLocation;
	FHitResult HitResult;

二.起点从摄像机,重点为摄像机前9999m。射线检测

使用LineTraceSingleByChannel 射线直线通道检测,所以

void AMyCharacter::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
	StartLocation = MyCamera->GetComponentLocation();
	ForwardVector = MyCamera->GetForwardVector();
	EndLocation = StartLocation + ForwardVector * 9999;
	bool bHit = GetWorld()->LineTraceSingleByChannel(HitResult,StartLocation,EndLocation,ECC_Visibility); 
	if (bHit)
	{
		AActor* HitActor = HitResult.GetActor();
		FVector ImpactPoint = HitResult.ImpactPoint;
		FVector HitLocation = HitResult.Location;
		GEngine->AddOnScreenDebugMessage(-1,5.0f,FColor::Red,FString::Printf(TEXT("%s"),*HitActor->GetName()));
	}
}

如果击中物体,射线检测返回HitResult结构体。ECC_Visibility则是根据通道查询检测。可以从HitResult里获取Actor. ImpactPoint是射线击中这个点的物体位置的位置。HitResult.Location是指击中的点的位置。

UE4 微笔记 之 HitResult (持续更新)_sweep hit result-CSDN博客

三.根据对象检测

//根据对象查询检测
FCollisionObjectQueryParams objectType;
//objectTypes.AddObjectTypesToQuery(E);
bool bHit2 = GetWorld()->LineTraceSingleByObjectType(HitResult,StartLocation,EndLocation,objectType);
if(bHit2)
{
	AActor* HitActor2 = HitResult.GetActor();
	FVector Impactpoint2 = HitResult.ImpactPoint;
	FVector HitLocation = HitResult.Location;
	GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Red, FString::Printf(TEXT("%s"), *HitActor2->GetName()));
}

可以规避一些不想检测的对象。但个人射线检测用的多一些。