最简单的 UE 4 C++ 教程 —— Actor 线轨迹(line trace( 二 )


同时 , 我们还要为线轨迹函数创建碰撞参数变量 。
【最简单的 UE 4 C++ 教程 —— Actor 线轨迹(line trace】void AActorLineTrace::Tick(float DeltaTime){Super::Tick(DeltaTime);FHitResult OutHit;FVector Start = GetActorLocation();Start.Z += 50.f;Start.X += 200.f;FVector ForwardVector = GetActorForwardVector();FVector End = ((ForwardVector * 500.f) + Start);FCollisionQueryParams CollisionParams;}
在开发时 , 我们希望看到我们的线轨迹 。通过上面的变量 , 我们将使用函数来画一条绿色的线 。如果线轨迹接触到我们这个 actor 中的任何组件 , 将向屏幕打印一条消息 。
void AActorLineTrace::Tick(float DeltaTime){Super::Tick(DeltaTime);FHitResult OutHit;FVector Start = GetActorLocation();Start.Z += 50.f;Start.X += 200.f;FVector ForwardVector = GetActorForwardVector();FVector End = ((ForwardVector * 500.f) + Start);FCollisionQueryParams CollisionParams;DrawDebugLine(GetWorld(), Start, End, FColor::Green, false, 1, 0, 5);if(ActorLineTraceSingle(OutHit, Start, End, ECC_WorldStatic, CollisionParams)){GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Green, FString::Printf(TEXT("The Component Being Hit is: %s"), *OutHit.GetComponent()->GetName()));}}
以下是完整的 cpp 代码
#include "ActorLineTrace.h"#include "UObject/ConstructorHelpers.h"#include "DrawDebugHelpers.h"// Sets default valuesAActorLineTrace::AActorLineTrace(){// Set this actor to call Tick() every frame.You can turn this off to improve performance if you don't need it.PrimaryActorTick.bCanEverTick = true;// add cube to rootUStaticMeshComponent* Cube = CreateDefaultSubobject(TEXT("VisualRepresentation"));Cube->SetupAttachment(RootComponent);static ConstructorHelpers::FObjectFinder CubeAsset(TEXT("/Game/StarterContent/Shapes/Shape_Cube.Shape_Cube"));if (CubeAsset.Succeeded()){Cube->SetStaticMesh(CubeAsset.Object);Cube->SetRelativeLocation(FVector(0.0f, 0.0f, 0.0f)); ///< 根据自己的实际情况调整Cube->SetWorldScale3D(FVector(1.f));}// add another component in the editor to the actor to overlap with the line trace to get the event to fire}// Called when the game starts or when spawnedvoid AActorLineTrace::BeginPlay(){Super::BeginPlay();}// Called every framevoid AActorLineTrace::Tick(float DeltaTime){Super::Tick(DeltaTime);FHitResult OutHit;FVector Start = GetActorLocation();Start.Z += 50.f;Start.X += 200.f; ///< 根据自己的实际情况调整FVector ForwardVector = GetActorForwardVector();FVector End = ((ForwardVector * 500.f) + Start);FCollisionQueryParams CollisionParams;DrawDebugLine(GetWorld(), Start, End, FColor::Green, false, 1, 0, 5);if(ActorLineTraceSingle(OutHit, Start, End, ECC_WorldStatic, CollisionParams)){GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Green, FString::Printf(TEXT("The Component Being Hit is: %s"), *OutHit.GetComponent()->GetName()));}}
实际的运行效果如下