.h
UFUNCTION()
void StartLineTrace();
UPROPERTY()
AActor* RootActor;
};
.cpp
void ULineTraceComponent::BeginPlay()
{
Super::BeginPlay();
if (RootActor==nullptr)
{
RootActor = GetAttachmentRootActor();
}
if (RootActor!=nullptr)
{
if (RootActor->InputComponent==nullptr)
{
RootActor->EnableInput(UGameplayStatics::GetPlayerController(GWorld,0));
}
UE_LOG(LogTemp, Warning, TEXT("bind StartTraceLine successfully"));
RootActor->InputComponent->BindAction("LeftMouse", EInputEvent::IE_Pressed, this, &ULineTraceComponent::StartLineTrace);
}
UGameplayStatics::GetPlayerController(GWorld, 0)->bShowMouseCursor = true;
}
void ULineTraceComponent::StartLineTrace()
{
UKismetSystemLibrary::PrintString(GWorld, "Click Left Mouse");
FCollisionQueryParams CollisonQueryParams(TEXT("QueryParams"), true, NULL);
CollisonQueryParams.bTraceComplex = true;
CollisonQueryParams.bReturnPhysicalMaterial = false;
CollisonQueryParams.AddIgnoredActor(RootActor);
APlayerController* PlayerController = UGameplayStatics::GetPlayerController(GWorld, 0);
FVector CamPos;
FRotator CamRot;
PlayerController->GetPlayerViewPoint(CamPos, CamRot);
FVector MousePos, MouseDir;
PlayerController->DeprojectMousePositionToWorld(MousePos, MouseDir);
FVector LineStart = CamPos;
FVector LineEnd = CamPos + MouseDir * 1000;
FHitResult HitResult;
GetWorld()->LineTraceSingleByChannel(HitResult, LineStart, LineEnd, ECollisionChannel::ECC_Visibility, CollisonQueryParams);
if (HitResult.GetActor())
{
UE_LOG(LogTemp, Warning, TEXT("hit %s"), *HitResult.GetActor()->GetName());
}
UKismetSystemLibrary::DrawDebugLine(GetWorld(), LineStart, LineEnd, FLinearColor::Red, 10.f, 10.f);
}
|