UE5 C++ 射线检测

一.声明四个变量

cpp 复制代码
	FVector StartLocation;
	FVector ForwardVector;
	FVector EndLocation;
	FHitResult HitResult;

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

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

cpp 复制代码
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博客

三.根据对象检测

cpp 复制代码
//根据对象查询检测
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()));
}

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

相关推荐
Дерек的学习记录7 小时前
Unreal Engine 5:开关门实现和流程控制
开发语言·学习·ue5
远离UE41 天前
拉格朗日 动力学问题
ue5·图形渲染·图形学·动力学
远离UE46 天前
UE5 Substrate Thin Film 源码拆析
开发语言·javascript·ue5
七仔啊7 天前
UE5源码下载及编译
ue5
Zhichao_977 天前
【UE5.8 MCP】接入AI大模型
ue5
曼巴UE58 天前
UE 属性同步
网络·c++·ue5
易知微EasyV数据可视化10 天前
UE5中添加 PNG/TIF 到 Cesium 地球表面方案
经验分享·ue5·数字孪生
GR9010 天前
UE5 SetActorLocation背后发生了什么
ue5
成都渲染101云渲染666611 天前
云渲染怎么用?从项目准备到提交出图,3ds Max、VRay、UE5 实用教程
3d·ue5
directx3d_beginner14 天前
42,将移向指定位置改为c++
ue5