原教程是基于 UE 4.18,我是基于 UE 4.25】数组
英文原地址markdown
接上一节教程,本教程将说明如何使用 SweepMultiByChannel 返回给定半径内的结果。ide
建立一个新的 C++ Actor 子类并将其命名为 MySweepActor 。咱们不会对默认头文件作任何修改。函数
下面是最终的头文件。oop
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "MySweepActor.generated.h"
UCLASS()
class UNREALCPP_API AMySweepActor : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AMySweepActor();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
};
复制代码
在咱们编写代码的逻辑以前,咱们必须首先 #include DrawDebugHelpers.h 文件来帮助咱们可视化 actor 。ui
#include "MySweepActor.h"
// include debug helpers
#include "DrawDebugHelpers.h"
复制代码
在这个例子中,咱们将在 BeginPlay() 函数中执行全部的逻辑。this
首先,咱们将建立一个FHitResults 的 TArray,并将其命名为 OutHits。spa
咱们但愿扫描球体在相同的位置开始和结束,并经过使用 GetActorLocation 使它与 actor 的位置相等。碰撞球体能够是不一样的形状,在这个例子中,咱们将使用 FCollisionShape:: makephere 使它成为一个球体,咱们将它的半径设置为 500个虚幻单位。接下来,运行 DrawDebugSphere 来可视化扫描球体。debug
而后,咱们想要设置一个名为 isHit 的 bool 变量来检查咱们的扫描是否击中了任何东西。code
咱们运行 GetWorld()->SweepMultiByChannel 来执行扫描通道跟踪并返回命中状况到 OutHits 数组中。
你能够在这里了解更多关于 SweepMultiByChannel 功能。若是 isHit 为真,咱们将循环遍历 TArray 并打印出 hit actor 的名字和其余相关信息。
你能够在这里了解更多关于 TArray 的信息。
下面是最后的.cpp文件。
#include "MySweepActor.h"
#include "DrawDebugHelpers.h"
// Sets default values
AMySweepActor::AMySweepActor()
{
// 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;
}
// Called when the game starts or when spawned
void AMySweepActor::BeginPlay() {
Super::BeginPlay();
// create tarray for hit results
TArray<FHitResult> OutHits;
// start and end locations
FVector SweepStart = GetActorLocation();
FVector SweepEnd = GetActorLocation();
// create a collision sphere
FCollisionShape MyColSphere = FCollisionShape::MakeSphere(500.0f);
// draw collision sphere
DrawDebugSphere(GetWorld(), GetActorLocation(), MyColSphere.GetSphereRadius(), 50, FColor::Purple, true);
// check if something got hit in the sweep
bool isHit = GetWorld()->SweepMultiByChannel(OutHits, SweepStart, SweepEnd, FQuat::Identity, ECC_WorldStatic, MyColSphere);
if (isHit)
{
// loop through TArray
for (auto& Hit : OutHits)
{
if (GEngine)
{
// screen log information on what was hit
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Green, FString::Printf(TEXT("Hit Result: %s"), *Hit.Actor->GetName()));
// uncommnet to see more info on sweeped actor
// GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("All Hit Information: %s"), *Hit.ToString()));
}
}
}
}
// Called every frame
void AMySweepActor::Tick(float DeltaTime) {
Super::Tick(DeltaTime);
}
复制代码
最终运行的效果以下所示