언리얼 엔진/25.01.23 2차프로젝트 기술

에너미 공격과 사망시 효과음이 재생되도록 만들기

odkokdh 2025. 3. 5. 09:41

그 동안 효과음을 안 넣어서 밋밋한 느낌이 났다.

에너미가 공격할때와 사망시 효과음이 재생하도록 만들 예정이다.

 

 

RangedEnemy.h

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Sound)
class USoundBase* DeathSound;

bool PlayDeathSound = false;

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Sound)
class USoundBase* AttackSound;

 

먼저 헤더에 사운드베이스를 받을 수 있도록 선언하였다. 하나는 죽을 때의 사운드, 다른 하나는 공격을 할 때 나오는 사운드이다.

bool 변수는 죽었을 때 죽는 효과음이 한번만 나오도록 막기 위해 선언하였다.

 

RangedEnemy.cpp

void ARangedEnemy::Attack()
{
	if (atkTime <= 0)
	{
		PlaySound(this, AttackSound, GetActorLocation());
		PlayAnimMontage(AIController->Anim->REMontage, 1.0f, FName("Fire"));
		//정해진 위치에 총알 생성
		GetWorld()->SpawnActor<AEnemyBullet>(Bullet, Arrow->GetComponentTransform());
	}
}

 

그리고 cpp에서 Attack함수가 일어날때 PlaySound를 사용하여 소리가 재생되도록 만들었다.

이때 재생되는 위치는 해당 액터의 위치에서 발생되도록 만들었다.

 

RangedEnemy.cpp

void ARangedEnemy::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	if (Health <= 0)
	{
		AIController->Anim->bIsDead = true;
		if (!PlayDeathSound)
		{
			PlaySound(this, DeathSound, GetActorLocation());
			PlayDeathSound = true;
		}
		GetCapsuleComponent()->SetCollisionEnabled(ECollisionEnabled::NoCollision);
		WeakCollision->SetCollisionEnabled(ECollisionEnabled::NoCollision);
	}
}

 

사망시에 효과음은 Tick에서 발생되도록 만들었다. 따로 죽었을 때 처리하는 함수를 만들면 기존 구조에서 수정을 해야하기에 이렇게 작성하였다.

먼저 체력이 0이 될 경우 죽었을 때 효과음이 재생되지 않은 상태이면 사망 효과음을 액터의 위치에서 재생한 다음, bool을 true 값으로 바꿔 다시 재생되지 않도록 막아준다.

 

 

이렇게 작성한 다음 블루프린트에서 각각 맞는 효과음을 넣어주었다.

테스트를 해본 결과 상황에 맞게 각각 효과음이 재생되었다.

 

 

이제 근거리 에너미도 효과음을 넣을 예정이다.

다만 원거리 에너미에서는 class USoundBase* 로 받았다면 이번에는 USoundCue*로 받아볼 예정이다.

 

MeleeEnemy.h

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Sound)
USoundCue* DeathSound;

bool PlayDeathSound = false;

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Sound)
USoundCue* AttackSound;

 

원거리 에너미에서 작성한 것과는 크게 다른 부분은 없다.

단지 class USounBase* 부분이 USoundCue*로 바뀐 것 밖에 없다.

 

MeleeEnemy.cpp

void AMeleeEnemy::Tick(float DeltaTime)
{
	if (Health <= 0)
	{
		Anim->bIsDead = true;
		if (!PlayDeathSound)
		{
			//UGameplayStatics::PlaySoundAtLocation(this, DeathSound, GetActorLocation());

			PlaySound(this, DeathSound, GetActorLocation());
			PlayDeathSound = true;
		}
	}
}

void AMeleeEnemy::Attack()
{
	if (atkTime <= 0)
	{
		PlaySound(this, AttackSound, GetActorLocation());
	}
}

 

소리 재생하는 것도 원거리 에너미 재생하는 것과 같다.

이렇게 작성하고 똑같이 블루프린트에서 할당을 해준 다음 테스트를 하면 무사히 재생이 된다.

 

 

 


 

사운드 큐를 재생하는 방법은 두가지다.

 

하나는 class USoundBase*로 받는 방법

다른 하나는 USoundCue*로 받는 방법이다.

 

처음에는 class USoundCue*를 선언해서 재생하려고 하였지만 되지 않아서 많이 해메었다.