[UE5] Cpp Multiplay Game <Cop And Robber> #5

_ dfdeer·2025년 9월 23일

Cop And Robber

목록 보기
5/7

아이템 획득/활성화 사운드

아이템을 획득했을 때 사운드를 넣어 게임을 풍성하게 하려고한다.

모든 아이템은 주웠을 때, 그리고 발동될 때 소리가 나기 때문에 ItemBase 에서 작업을 해야한다.

//CRItemBase.h

...

class COPANDROBBER_API ACRItemBase : public ACRGimmickBase
{
	...
    
protected:
	UPROPERTY(EditAnywhere, Category="Sound")
	USoundBase* PickupSound;
	UPROPERTY(EditAnywhere, Category="Sound")
	USoundBase* ActivateSound;
    
    ...
    
public:

	...
    
	UFUNCTION(NetMulticast, Unreliable)
	void PlayPickUpSound(FVector Loc);
    UFUNCTION(NetMulticast, Unreliable)
	void PlayActivateSound(FVector Loc);
};

헤더 파일이다.

protected 에서 PickupSound 와 ActivateSound 변수를 선언해두고,

public 에 PlayPickUpSound(), PlayActivate() 함수를 만들어 파라미터로는 사운드가 재생되는 위치를 넣어준다.
또한 다른 사람들에게도 아이템 획득 사운드가 들리도록 UFUNCTION 에 NetMulticast 를 넣었다.

서버에서 클라로 소리를 뿌리는 것이다.

//CRItemBase.cpp

...

void ACRItemBase::PlayPickUpSound_Implementation(FVector Loc)
{
	if (PickupSound && GetNetMode() != NM_DedicatedServer)
	{
		UGameplayStatics::PlaySoundAtLocation(this, PickupSound, Loc);
	}
}

void ACRItemBase::PlayActivateSound_Implementation(FVector Loc)
{
	if (ActivateSound && GetNetMode() != NM_DedicatedServer)
	{
		UGameplayStatics::PlaySoundAtLocation(this, ActivateSound, Loc);
	}
}

헤더에서 추가로 만든 함수를 구현해준다.

사운드가 유효하고 넷모드가 데디서버가 아니라면(즉 클라라면),
UGameplayStatics 에 있는 PlaySoundAtLocation() 함수를 통해 다른 클라에서도 사운드를 재생한다.

두 함수 모두 같은 역할을 한다.

...

void ACRItemBase::Activate(AActor* Player)
{
	if (APawn* Pawn = Cast<APawn>(Player))
	{
		if (APlayerController* PC = Cast<APlayerController>(Pawn->GetController()))
		{
			if (PickupSound)
			{
				PC->ClientPlaySound(PickupSound);
				PlayPickUpSound(Player->GetActorLocation());
			}
			if (ActivateSound)
			{
				PC->ClientPlaySound(ActivateSound);
				PlayActivateSound(Player->GetActorLocation());
			}
		}
	}
}

Activate() 함수에서는 사운드가 유효한지 확인한다.

유효하다면 본인 클라에서 사운드를 재생하고
PlayPickUpSound(), PlayActivateSound() 함수를 호출한다.

이후 각 아이템의 블루프린트로 가서 Details 패널의 Sound > PickUp Sound 에 준비해둔 사운드 파일을 넣어주면 끝이다.

0개의 댓글