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

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

相关推荐
zhangzhangkeji1 天前
UE5 C++(70-2):定义成员函数 getCleanDirectory(..) 和枚举类 EFileDirectoryType,来获得目录
ue5
avi91112 天前
UE4-UE5虚幻引擎-前置学习三,优化,基础CPP
ue5·ue4·游戏开发·虚幻·游戏优化·游戏代码
zhangzhangkeji2 天前
UE5线程进阶(3-2):任务图的相关源码整理。 FGraphEvent 与 TGraphTask 的区别和联系
ue5
zhangzhangkeji4 天前
UE5线程进阶(3-1):
ue5
zhangzhangkeji4 天前
UE5线程进阶(2-3):enum ENamedThreads命名空间 :: Type : int32 { RHIThread = 0 } 是渲染硬件接口线程
ue5
zhangzhangkeji5 天前
UE5线程进阶(2-1):枚举类EAsyncExecution,作业类TAsyncRunnable、TAsyncQueuedWork,及全局线程函数 Async(..),及线程调用的 4 种方法总结
ue5
zhangzhangkeji6 天前
UE5线程进阶(1):
ue5
yblackd9 天前
UnrealEngine Win风格 窗口选择打开文件
c++·ue5·虚幻
AI视觉网奇10 天前
ue 推送直播流 推流 linux 实战
笔记·学习·ue5
郁闷的网纹蟒10 天前
虚幻5---第16部分---敌人(中)
开发语言·c++·ue5·游戏引擎·虚幻