// 最后2个参数可写可不写
// 需要注意的是 class AActor* otherActor ,碰撞的物体是不是敌人or食物
// 新增:使用了反射机制,需要添加关键字 UFUNCTION()
UFUNCTION()
void OnCollision(class UPrimitiveComponent* HitComp, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int OtherBodyIndex, bool bFromSweep, const FHitResult & SweepResult);
// PacManGameModeBase.h
public:
// 但是由于我们的碰撞在,吃食物在,当前的状态是EPlaying,
// 游戏中的时候才能吃食物,物体才会被销毁,把当前的状态设置成EPlaying,
// 这样方便测试了
virtual void BeginPlay() override;
// PacManGameModeBase.cpp
void APacManGameModeBase::BeginPlay()
{
SetCurrentState(EGameState::EPlaying);
}
PacManCharacter.h
private:
// 需要吃的 豆 的数量
int CollectablesToEat;
// 当前的生命值
int Lives;
PacManCharacter.cpp
#include "Public/EngineUtils.h"
void APacManCharacter::BeginPlay()
{
Super::BeginPlay();
// 迭代器:
// 使用TActorIterator 需要引入的头文件:#include "Public/EngineUtils.h"
for (TActorIterator<ACollectables>CollectableItr(GetWorld()); CollectableItr; ++CollectableItr)
{
CollectablesToEat++;
}
UE_LOG(LogTemp, Warning, TEXT("Total Collectable is %d"), CollectablesToEat);
}
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();
if (--CollectablesToEat == 0)
{
GameMode->SetCurrentState(EGameState::EWin);
}
UE_LOG(LogTemp, Warning, TEXT("Remain Collectable is %d"), CollectablesToEat);
}
}
}
// 使用TActorIterator 需要引入的头文件:#include "Public/EngineUtils.h"