Unreal

[Unreal] 캐릭터 이동 및 마우스로 화면 전환 (1) - C++ (Character Class)

TIM_0529 2023. 1. 4. 16:34
반응형

캐릭터 클래스를 사용해 캐릭터 이동을 좀 더 간편하게 구현해 보겠습니다.

우선 프로젝트 셋팅에 input 에서 다음과 같이 설정합니다.

MoveForward : 앞 뒤 이동 시 사용될 키들을 맵핑합니다.

MoveRight : 좌 우 이동 시 사용될 키들을 맵핑합니다.

LookUp : 위 아래를 바라볼 시 사용될 축 값을 맵핑합니다.

Turn: 좌 우를 바라볼 시 사용될 축 값을 맵핑합니다.

 

다음은 C++ 파일을 하나 만들고 헤더 파일에 다음을 추가합니다.

 

	void MoveForward(float Value);
	void MoveRight(float Value);
	void Turn(float Value);
	void LookUp(float Value);

다음은 CPP 파일로 이동하여 다음의 함수를 구현합니다.

void APlayerCharacter::MoveForward(float Value)
{
	if ((Controller != nullptr) && (Value != 0.0f))
	{
		// Find out which way is forward
		FRotator Rotation = Controller->GetControlRotation();
		FRotator YawRotation(0.f, Rotation.Yaw, 0.f);

		FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
		AddMovementInput(Direction, Value);
	}
}
void APlayerCharacter::MoveRight(float Value)
{
	if ((Controller != nullptr) && (Value != 0.0f))
	{
		// Find out which way is forward
		FRotator Rotation = Controller->GetControlRotation();
		FRotator YawRotation(0.f, Rotation.Yaw, 0.f);

		FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);
		AddMovementInput(Direction, Value);
	}
}
void APlayerCharacter::Turn(float Value){}
void APlayerCharacter::LookUp(float Value){}

앞 뒤와 좌 우만 구현합니다.

if문 조건에보면 Controller 라는 객체가 있습니다. 이것을 객체라고 부른 이유는 Controller에 정의를 찾아 들어가보면

/** Controller currently possessing this Actor */
	UPROPERTY(replicatedUsing=OnRep_Controller)
	AController* Controller;

이렇게 정의되어 있습니다. 그리고 AController는

class ENGINE_API AController : public AActor, public INavAgentInterface
{
...
}

다음과 같이 정의되어 있습니다.

지금 우리가 사용하는 클래스는 Character이므로 AActor 에게서 상속받은 AController 클래스를 사용할 수 있습니다.

 

다음으로는 만든 함수를 사용해서 유저 인풋에 따라 바인딩을 시키는 작업을 해 주겠습니다.

// Called to bind functionality to input
void APlayerCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	Super::SetupPlayerInputComponent(PlayerInputComponent);

	PlayerInputComponent->BindAxis("MoveForward", this, &APlayerCharacter::MoveForward);
	PlayerInputComponent->BindAxis("MoveRight", this, &APlayerCharacter::MoveRight);

	// Mouse Input
	PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput);
	PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput);

}

여기서 주요할 점은 MouseInput값을 받아오는 부분입니다.

APlayeriCharacter 클래스에서 가져오는 것이 아니라 APawn에서 정의된 AddControllerYawInput 함수를 사용해서 받아옵니다.

컴파일 후 실행을 하면 앞뒤 좌우로 잘 움직이는 것을 확인할 수 있습니다. 카메라 위치를 따로 지정해 두지 않아서 character 오브젝트와 카메라가 마치 한 몸처럼 움직입니다. 그리고 좌 우 이동시 캐릭터에 몸도 같이 돌아가는 것을 확인할 수 있습니다. 

 

다음 포스팅에서 이를 수정할 코드를 마저 적어보겠습니다.

반응형