상세 컨텐츠

본문 제목

[Unreal Engine 5 : C++] 캐릭터를 따라 회전하는 물체 만들기

Study/UNREAL

by J2on 2024. 2. 6. 23:57

본문

 

언리얼에서 캐릭터나 액터의 움직임을 따라 회전하는 물체를 만들어봅시다. 

 

저는 주인공을 따라 움직이는, 캐릭터만 바라보는 눈알을 만들어 보겠습니다. 

 

 

기본적으로 Rotation은 벡터를 기반으로 만들어집니다. 

 

플레이어를 바라보는 벡터가 필요한데, 이것은 (플레이어 위치 - 눈알의 위치) 를 통해 구할 수 있습니다. 

 

위의 그림처럼 생각해보면 되겠죠?

 

 

위에서 본다면 이런 느낌으로 벡터가 생깁니다. 

이렇게 생성한 vector를 FRotator로 변환한 후에, 회전하고 싶은 component에 rotation으로 적용시켜 주시면 됩니다. 

 

코드로 표현하면 아래와 같습니다. 

void ASuspiciousPicture::RotateEye()
{
	//플레이어 위치를 받아오기
	FVector PlayerLocation = PlayerDoll->GetActorLocation();
	// 왼쪽 눈알
	FVector LeftEyeVec = PlayerLocation - LeftEyeComponent->GetComponentLocation();
	FRotator LeftEyeRotator = FRotator(0.f, LeftEyeVec.Rotation().Yaw, 0.f);
	LeftEyeComponent->SetWorldRotation(LeftEyeRotator);
	// 오른쪽 눈알
	FVector RightEyeVec = PlayerLocation - RightEyeComponent->GetComponentLocation();
	FRotator RightEyeRotator = FRotator(0.f, RightEyeVec.Rotation().Yaw, 0.f);
	RightEyeComponent->SetWorldRotation(RightEyeRotator);
}

 

 

그런데, 플레이어가 점프하는 경우에도 적용하고 싶다면 어떻게 해야할까요?

 

단순히 Roll에 EyeVec.Rotation().Roll을 적용시켜주면 아마 반대로 동작할 것입니다. 

 

플레이어가 점프하게 되면 Y값이 증가하므로 벡터도 양수의 Y값을 가지게 됩니다.

 

그런데?!

 

회전은 CounterClockWise로 회전할 때, 양수의 값을 가지므로 y값이 커지게 된다면 오히려 눈알은 아래를 보게될 것입니다. 

 

때문에 반대 부호로 Roll에 적용해주어야 합니다. 

 

 

//플레이어 위치를 받아오기
	FVector PlayerLocation = PlayerDoll->GetActorLocation();
	// 왼쪽 눈알
	FVector LeftEyeVec = PlayerLocation - LeftEyeComponent->GetComponentLocation();
	FRotator LeftEyeRotator = FRotator(0.f, LeftEyeVec.Rotation().Yaw, -LeftEyeVec.Rotation().Roll);
	LeftEyeComponent->SetWorldRotation(LeftEyeRotator);
	// 오른쪽 눈알
	FVector RightEyeVec = PlayerLocation - RightEyeComponent->GetComponentLocation();
	FRotator RightEyeRotator = FRotator(0.f, RightEyeVec.Rotation().Yaw, -RightEyeVec.Rotation().Roll);
	RightEyeComponent->SetWorldRotation(RightEyeRotator);

 

 

 

짜잔

관련글 더보기

댓글 영역