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()));
}

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

相关推荐
郑寿昌4 小时前
AI生成的FBX格式导入UE5模型的兼容性优化指南
ue5
2601_9571909021 小时前
超元力悬浮玻璃剧场:当光影踏空而来,重构沉浸式文旅新体验
ue5·旅游
UTwelve1 天前
【UE】Gerstner Waves 水体模拟 4 :[颜色构成阶段3、4] - 实现NAP+CDOM
ue5·着色器
chudonghao1 天前
[UE学习笔记][基于源码] 运行时网格 PMC / DMC / RMC
笔记·学习·ue5
吴梓穆1 天前
UE5 C++ 使C++创建动画蓝图
开发语言·c++·ue5
吴梓穆1 天前
UE5 动画状态机
ue5
电子云与长程纠缠2 天前
UE5 两种方式解决Decal Actor贴花拉伸问题
学习·ue5·游戏引擎
妙为2 天前
UE5中武器未跟随角色
ue5·gas·gameplay
平行云2 天前
虚拟直播混合式2D/3D应用程序实时云渲染推流解决方案
linux·unity·云原生·ue5·图形渲染·实时云渲染·像素流送
曼巴UE52 天前
UE 客户端 需要的网络同步概念总结
网络·c++·ue5