Today I worked on fixing the bug where the enemy would be destroyed if they punched the player. As well as setting up a HUD.
Enemy Header file
//Collision profile is set in the blueprint
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))
FCollisionProfileName CollisionProfile;
UFUNCTION() void OnOverlapStart(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32
OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);
After some testing I realised that only the player body had “OnOverlap”, therefore trying to get a specific overlapping component would always fail. Therefore, I created a blueprint editable property for the collision profile. I also decided to manage the enemy damage in the enemy class instead, to organise my code.
Enemy CPP file
ACompetitionEnemy::ACompetitionEnemy()
...
Body = CreateDefaultSubobject<UStaticMeshComponent>(FName("Body"));
...
void ACompetitionEnemy::BeginPlay()
...
//Sets collision presets based on blueprint editable variable
Body->SetCollisionProfileName(CollisionProfile.Name, true);
//Attaches "OnOverlapStart" function to "BeginOverlap"
Body->OnComponentBeginOverlap.AddDynamic(this, &ACompetitionEnemy::OnOverlapStart);
Here I have added the enemy body in C++ rather than blueprints as I had done previously, this will improve code consistency. I also set the collision profile and “OnOverlapStart” function as I did in the player.
void ACompetitionEnemy::OnOverlapStart(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
if (ACompetitionCharacter* Player = Cast<ACompetitionCharacter>(OtherActor))
{
if (OtherComp == (Player->PunchingArm))
{
health = health - 25;
In this code I setup how the enemy overlap works, now I can check which component is overlapping the enemy and decrease the enemy health if the player has attacked.
Player Header file
UPROPERTY(BlueprintReadOnly)
float health = 100;
In the header, I changed the health to be “BlueprintReadOnly” so the UI can read the value for the HUD. I also put everything into “public” as I was having issues with communicating values across classes.
Player C++ file
void ACompetitionCharacter::OnOverlapStart(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
if (OtherComp == (Enemy->LeftArmBox))
{
health = health - 25;
I adapted my overlap code so now it will check if the enemy attacked and decrease player health.
HUD Blueprint
