代码实现

方式一:

通过重写继承来的NotifyActorBeginOverlap,这更易于实现

1
2
3
4
5
6
7
8
//Actor.h:
Public:
/**
*Event when this actor overlaps another actor, for example a player walking into a trigger.
*For events when objects have a blocking collision, for example a player hitting a wall, see 'Hit' events.
*@note Components on both this and the other Actor must have bGenerateOverlapEvents set to true to generate overlap events.
*/
virtual void NotifyActorBeginOverlap(AActor* OtherActor);

举例:

1
2
3
4
5
6
7
8
9
10
11
12
13
//AFPSActor.h:
public:
virtual void NotifyActorBeginOverlap(AActor* OtherActor) override;

//AFPSActor.cpp:
void AFPSObjectiveActor::NotifyActorBeginOverlap(AActor* OtherActor)
{
Super::NotifyActorBeginOverlap(OtherActor);
AFPSCharacter* Mycharacter = Cast<AFPSCharacter>(OtherActor);
if (Mycharacter) {
Destroy();
}
}

方式二:

通过组件触发event:Comp->OnComponentBeginOverlap.AddDynamic(this, &AClass::Handlefunc);

其中处理函数自己创建,函数类型见下方举例部分。

光标放在OnComponentBeginOverlap上,按F12:

1
2
UPROPERTY(BlueprintAssignable, Category="Collision")
FComponentBeginOverlapSignature OnComponentBeginOverlap;

光标放在FComponentBeginOverlapSignature上,按F12(Visual Studio,Go to Definition):

这里声明了事件本身,相关的处理函数要对应后六个参数,将它们复制,变量名称和变量类型之间的逗号。

1
2
/** Delegate for notification of start of overlap with a specific component */
DECLARE_DYNAMIC_MULTICAST_SPARSE_DELEGATE_SixParams( FComponentBeginOverlapSignature, UPrimitiveComponent, OnComponentBeginOverlap, UPrimitiveComponent*, OverlappedComponent, AActor*, OtherActor, UPrimitiveComponent*, OtherComp, int32, OtherBodyIndex, bool, bFromSweep, const FHitResult &, SweepResult);

举例:

//绑定这类型的函数时,需将其标记为UFUNCTION,以便让虚幻后端明白该函数的含义及如何将其与事件相绑定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//AFPSActor.h:
UPROPERTY(VisibleAnywhere, Category = "Components")
UBoxComponent* OverlapComp;

UFUNCTION()
void HandleOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);

//AFPSActor.cpp:
OverlapComp = CreateDefaultSubobject<UBoxComponent>(TEXT("OverlapComp"));
OverlapComp->OnComponentBeginOverlap.AddDynamic(this, &AFPSExtractionZone::HandleOverlap);


void AFPSExtractionZone::HandleOverlap(UPrimitiveComponent* OverlappedComponent,
AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) {
//sth.
}