[UE5] 언리얼5 C++ - 이동 방향에 따른 구르기

AnJH·2024년 6월 17일
0

플레이어의 이동 방향에 따른 구르기

따로 방향값에 따른 구르기 모션을 가지고 있다면 해당 모션을 사용해서 방향값에 따라 Blend Space나 Animation Montage를 활용할 수 있겠으나, 앞으로 구르는 모션밖에 존재하지 않다면 해당 방법을 고려해볼만 하다.

  • PlayerCharacter.h
FRotator OriginalRotation;
FVector ForwardDirection;
FVector RightDirection;

플레이어의 이동과 관련된 함수와 구르기와 관련된 함수에서 동일하게 사용될 변수를 따로 헤더파일에 빼놓았다.

  • PlayerMove
void APlayerCharacter::PlayerMove(const FInputActionValue& Value)
{
	MovementVector = Value.Get<FVector>();
	if (Controller != nullptr && !bPlayerDie)
	{
		const FRotator Rotation = cameraComp->GetComponentRotation();
		const FRotator YawRotation(0.f, Rotation.Yaw, 0.f);
		ForwardDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
		RightDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);

		AddMovementInput(ForwardDirection, MovementVector.Y);
		AddMovementInput(RightDirection, MovementVector.X);
	}
}

먼저 플레이어의 이동과 관련된 함수이다.

이는 Enhanced Input을 사용한 방법이기에 방향값을 구하는 코드가 조금씩은 다를 수 있어도 거의 고정된 코드이다.

여기서 조금 달라진 점은 Rotation값을 구할 때, 보통 Player를 기점으로 구하지만 위 코드에서는 카메라의 회전값을 토대로 구한다는 점이다.

  • PlayerRoll
if (!MovementVector.IsNearlyZero()) {
		MovementVector.Normalize();
}
else {
	MovementVector = ForwardDirection;
}

먼저 플레이어의 이동 함수에서 입력값이 저장되는 MovementVector가 일정 값을 존재한다면 정규화를 하여 플레이어의 방향을 구한다.

만약 해당 Vector가 거의 0 즉, 플레이어가 정지한 상태라면 MovementVector에 ForwardDirection을 넣음으로써 전방 방향으로 구르도록 한다.

  • Player Rotator State
bUseControllerRotationYaw = false;
GetCharacterMovement()->bOrientRotationToMovement = true;

UseControllerRotationYaw를 False로, OrientRotationToMovement를 True로 바꿈으로써 플레이어가 이동하는 방향으로 회전하도록 설정해준다.

  • SetActorRotation
OriginalRotation = GetActorRotation();

FVector TransformedDirection = (ForwardDirection * MovementVector.Y) + (RightDirection * MovementVector.X);
TransformedDirection.Normalize();
FRotator NewRotation = TransformedDirection.Rotation();

SetActorRotation(NewRotation);

회전값을 바꾸기 전에 회전값을 미리 변수값으로 저장해둔다.

플레이어가 이동하는 방향 좌표에 Input값에 따라 구한 입력된 방향 좌표를 곱해주고 이를 정규화함으로써 플레이어가 구를 방향을 구하여 해당 좌표로 플레이어의 방향을 바꿔준다.

  • Timer
GetWorldTimerManager().SetTimer(RollTimerHandle, this, &APlayerCharacter::PlayerRollComplete, rollDelay, false);

구르는 모션의 Rate값을 Timer의 시간으로 넣고, 해당 모션이 끝났을 때의 함수를 호출한다.

  • RollComplete
void APlayerCharacter::PlayerRollComplete()
{
	bPlayerRolling = false;
	SetActorRotation(OriginalRotation);
	bUseControllerRotationYaw = true;
	GetCharacterMovement()->bOrientRotationToMovement = false;
}

구르는 모션이 끝났을 땐, 위에서 바꿔놓은 UseControllerRotationYaw와 OrientRotationToMovement값을 원래 상태로 다시 바꿔준다.

0개의 댓글