[C++] 총알 발사하기

Woogle·2022년 11월 18일
0

언리얼 엔진 5

목록 보기
31/60

📄 총알 발사하기

✏️ TPSPlayer.h

	void OnInputFire();

	UPROPERTY(EditAnywhere)
    TSubclassOf<class ABulletActor> bulletFactory;

	UPROPERTY(EditAnywhere)
	class USkeletalMeshComponent* gunMeshComp;

✏️ TPSPlayer.cpp

ATPSPlayer::ATPSPlayer()
{
 	// ...
	// 총 메쉬 설정
	gunMeshComp = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("gunMeshComp"));
	gunMeshComp->SetupAttachment(GetMesh());

	// 에셋 찾아오기
	ConstructorHelpers::FObjectFinder<USkeletalMesh> tempGunMesh(TEXT("SkeletalMesh'/Game/Resources/FPWeapon/Mesh/SK_FPGun.SK_FPGun'"));

	// 에셋 적용
	if (tempGunMesh.Succeeded())
	{
		gunMeshComp->SetSkeletalMesh(tempGunMesh.Object);
		gunMeshComp->SetRelativeLocation(FVector(0, 40, 140));
	}
}

void ATPSPlayer::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);
	// ...
	PlayerInputComponent->BindAction(TEXT("Fire"), IE_Pressed, this, &ATPSPlayer::OnInputFire);
}

void ATPSPlayer::OnInputFire()
{
	// 총알 발사 위치 구하기
	FTransform firePosition = gunMeshComp->GetSocketTransform(TEXT("Muzzle"));

	// 총알 스폰
	GetWorld()->SpawnActor<ABullet>(bulletFactory, firePosition);
}

📄 연사 (Auto Fire)

✏️ TPSPlayer.h

	void OnInputFirePressed();
	void OnInputFireReleased();
	void OnMakeBullet();

	// AutoFire 타이머
	FTimerHandle autoFireTimerHandle;

✏️ TPSPlayer.cpp

void ATPSPlayer::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);

	// ...
	PlayerInputComponent->BindAction(TEXT("Fire"), IE_Pressed, this, &ATPSPlayer::OnInputFirePressed);
	PlayerInputComponent->BindAction(TEXT("Fire"), IE_Released, this, &ATPSPlayer::OnInputFireReleased);
}

  void ATPSPlayer::OnInputFirePressed()
{
	// 첫발 발사
	OnMakeBullet();

	// 타이머 시작
	GetWorldTimerManager().SetTimer(autoFireTimerHandle, this, &ATPSPlayer::OnMakeBullet, 0.15f, true, 0.15f);
}

void ATPSPlayer::OnInputFireReleased()
{
	// 타이머 종료
	GetWorldTimerManager().ClearTimer(autoFireTimerHandle);
}

void ATPSPlayer::OnMakeBullet()
{
	// 총알 발사 위치 구하기
	FTransform firePosition = gunMeshComp->GetSocketTransform(TEXT("Muzzle"));

	// 총알 스폰
	GetWorld()->SpawnActor<ABullet>(bulletFactory, firePosition);
}
profile
노력하는 게임 개발자

0개의 댓글