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

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

相关推荐
zhangzhangkeji10 小时前
UE5 蓝图-游老师-18-蓝图的封装,19-继承,20-多态:父类中的变量,函数、事件,分发器,实现的接口,可以被子类直接使用,也可以被子类重写重定义
ue5
每天回答3个问题14 小时前
UE教程|unlua知识地图
ue5·腾讯·lua5.4
皇族崛起1 天前
【3D标注】- Unreal Engine 5.7 与 Python 交互基础
python·3d·ue5
一眼万里*e2 天前
UE中的UObject创建,销毁
ue5
吴梓穆5 天前
UE5 Perforce使用完全手册
ue5
zhangzhangkeji5 天前
UE5 蓝图-游老师-13-事件、函数、宏、事件分发器:在自定义蓝图(包括 UI 控件蓝图)中就可以创建事件分发器
ue5
Zhichao_975 天前
【UE5.3】小白人动画重定向
ue5
Zhichao_975 天前
【UE5.3】为人形角色建立Contrl Rig
ue5
竹欣5 天前
UE杂项(Mass 崩溃排查)
ue5
__Ryan5 天前
BlueprintImplementableEvent和BlueprintNativeEvent
c++·ue5·unreal engine