UE小白,有错误的地方请指出。
本文使用UE5,如在UE4中使用可能需调整某些API文章来源:https://www.toymoban.com/news/detail-614735.html
方法一
1.获取镜头控制器,并开启点击事件
APlayerController* playerController;
void AMeshChangeController::Item()
{
playerController = FAITestHelpers::GetWorld()->GetFirstPlayerController();
playerController->bEnableClickEvents = true;
playerController->SetShowMouseCursor(true);
playerController->EnableInput(playerController);
}
void AMeshChangeController::BeginPlay()
{
Super::BeginPlay();
Item();
}
2.鼠标点击发射射线
在Tick中调用射线发射逻辑
UE中API看起来没有分鼠标抬起和鼠标按下API,如有大佬知道可以评论一下。文章来源地址https://www.toymoban.com/news/detail-614735.html
void AMeshChangeController::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
TestRay();
}
void
AMeshChangeController:: TestRay()
{
//鼠标左键触发
if(playerController->IsInputKeyDown(EKeys::LeftMouseButton))
{
FHitResult OutHit;//用于接收命中的Actor
FVector Start; //射线起点
FVector End ; //射线终点
FVector Dir; //鼠标点击的方向
playerController->DeprojectMousePositionToWorld(Start, Dir);
End = Start + (Dir * 100000);
DrawDebugLine(GetWorld(), Start, End, FColor::Green, false, 100, 0, 5);//绘制射线
bool isFinsh = GetWorld()->LineTraceSingleByObjectType(OutHit, Start, End, ECC_WorldStatic);//进行射线检测
if (Cast<AActor>(OutHit.GetActor()))
{
AActor* gameObject = OutHit.GetActor();
FString s = gameObject->GetActorNameOrLabel();
UE_LOG(LogTemp, Warning, TEXT("被点击的物体,%s"), *s);
}
}
}
方法二
1.获取镜头控制器,并开启点击事件
APlayerController* playerController;
void AMeshChangeController::Item()
{
playerController = FAITestHelpers::GetWorld()->GetFirstPlayerController();
playerController->bEnableClickEvents = true;
playerController->SetShowMouseCursor(true);
playerController->EnableInput(playerController);
}
void AMeshChangeController::BeginPlay()
{
Super::BeginPlay();
Item();
}
2.使用射线API
playerController->HitResultTraceDistance = 1000000;
playerController->GetHitResultUnderCursor(ECollisionChannel::ECC_Visibility,true,OutHit);
if (Cast<AActor>(OutHit.GetActor()))
{
}
到了这里,关于【UE5 C++】鼠标点击发射射线获取物体信息的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!