Class GameDev* SheepAdult

[Unreal Engine 4] Timeline을 이용하여 부드럽게 앉기 구현 (Smooth Crouching) 본문

Unreal Project

[Unreal Engine 4] Timeline을 이용하여 부드럽게 앉기 구현 (Smooth Crouching)

SheepAdult 2022. 2. 7. 17:33

 기본적인 Crouch() 함수를 사용해 캐릭터의 앉는 기능을 구현하면 부자연스럽게 뚝뚝 끊어져 보이는 것처럼 앉게 된다. 3인칭이나 사이드뷰같은 경우 SpringArm의 CameraLag을 통해 부드러운 앉기를 구현할 수 있지만 보통 1인칭은 캡슐 컴포넌트에 카메라를 박아 넣는 방식을 사용하므로 직접 구현해주는 게 낫다고 판단해 구현해 보았다.

 

 먼저 Timeline에 쓰일 변수와 함수를 Pawn으로 사용할 메인 캐릭터 헤더파일에 아래와 같이 추가해 준다.

private:
// SmoothCrouching
	FOnTimelineFloat SmoothCrouchInterpFunction; // (1)
	FOnTimelineEvent SmoothCrouchTimelineFinish; // (2)
	UFUNCTION()
		void SmoothCrouchInterpReturn(float Value); // (3)
	UFUNCTION()
		void SmoothCrouchOnFinish(); // (4)
	UPROPERTY()
		UTimelineComponent* SmoothCrouchingCurveTimeline; // (5)
	UPROPERTY(EditAnywhere, Category = "Timeline")
		UCurveFloat* SmoothCrouchingCurveFloat; // (6)

 (1)과 (3), 그리고 (2)와 (4)는 BindUFunction으로 delegate를 사용하여 바인딩 해줘 타임라인이 시작되면, 그리고 실행된 후 각각 기능이 실행된다. SmoothCrouchingCurveTimeline은 TimelineComponent로 cpp에서 CreateDefaultSubobject를 사용하여 생성해줘야 한다. SmoothCrouchingCurveFloat은 커브 블루프린트를 만든 후 넣어 줄 변수이다. (5)는 몸통?이라고 보면된다. 즉, Play나 Stop등을 해주는 녀석이다. (6)은 Curve를 언리얼에서 하나 생성 후 원하는 Value와 Time을 그래프로 그린 후 넣어주면 된다. 커브를 굳이 넣지 않고 FInterpTo로 직접 값을 변경해 주며 실행해도 무방하다.

 

 아래는 cpp 파일이다.

void AMainCharacter::AMainCharacter
{
	SmoothCrouchingCurveTimeline = CreateDefaultSubobject<UTimelineComponent>(TEXT("TimelineFront"));
	SmoothCrouchInterpFunction.BindUFunction(this, FName("SmoothCrouchInterpReturn"));
	SmoothCrouchTimelineFinish.BindUFunction(this, FName("SmoothCrouchOnFinish"));
}

void AMainCharacter::SmoothCrouchInterpReturn(float Value)
{
	TriggerCapsuleComponent->SetCapsuleHalfHeight(FMath::Lerp(88.f, CrouchHeight, Value));
	FirstPersonCameraComponent->SetRelativeLocation(FVector(0.0f, 10.0f, (FMath::Lerp(160.0f, 120.0f, Value))));
}

void AMainCharacter::SmoothCrouchOnFinish()
{
	// 원하면 작성
}

void AMainCharacter::BeginPlay()
{
	Super::BeginPlay();

	SmoothCrouchTimelineSetting();
}

void AMainCharacter::SmoothCrouchTimelineSetting()
{
	if (SmoothCrouchingCurveFloat)
	{
		SmoothCrouchingCurveTimeline->AddInterpFloat(SmoothCrouchingCurveFloat, SmoothCrouchInterpFunction);
		SmoothCrouchingCurveTimeline->SetTimelineFinishedFunc(SmoothCrouchTimelineFinish);
		SmoothCrouchingCurveTimeline->SetLooping(false);
	}
}

void AMainCharacter::StartCrouch()
{
	SmoothCrouchingCurveTimeline->Play();
}

 다른 기능들이 많이 구현되어 있는 상태에서 뒤늦게 작성하는 거라 이것저것 빼고 컴파일은 안해보고 올리는 거라 될진 모르겠지만,,, Timeline을 사용하는 것에 대한 글이므로 이 정도만 코드는 작성하는 걸로 하겠다. 위는 앉는 것만 실행되므로 SmoothCrouchingCurveTimeline->Reverse()를 사용해 일어서는 것을 작성해야 하는데 앉는 키를 누르고 있을 때만 앉을 것인지 한 번 누르면 다시 누를 때까지 계속 앉아 있을 것인지에 따라 일어날 때 reverse 해주면 된다.

 

해당 프로젝트 13iew 다운로드 링크 : https://store.steampowered.com/app/2362150/13iew/