PacManCharacter.h
public:
// 最后2个参数可写可不写
// 需要注意的是 class AActor* otherActor ,碰撞的物体是不是敌人or食物
void OnCollision(class UPrimitiveComponent* HitComp, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult);
PacManCharacter.cpp
#include "Public/Collectables.h"
#include "Components/CapsuleComponent.h"
void APacManCharacter::BeginPlay()
{
Super::BeginPlay();
// 使用 GetCapsuleComponent() ,需要引入的头文件:#include "Components/CapsuleComponent.h"
// 第一个参数是当前类,第二个参数是 要绑定的函数
GetCapsuleComponent()->OnComponentBeginOverlap.AddDynamic(this, &APacManCharacter::OnCollision);
}
void APacManCharacter::OnCollision(UPrimitiveComponent * HitComp, AActor * OtherActor, UPrimitiveComponent * OtherComp, int OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult)
{
// 当游戏正在运行才去检测碰撞
if (GameMode->GetCurrentState() == EGameState::EPlaying)
{
// 当碰撞的对象是 ACollectables 类时销毁掉
// 使用自己定义的类AColletables,也需要引入对应的头文件: #include "Public/Collectables.h"
if (OtherActor->IsA(ACollectables::StaticClass()))
{
OtherActor->Destroy();
}
}
}
主角是 CapsuleComponent的碰撞体