[UE/Implement] 키 입력으로 캐릭터 움직이기

2024. 12. 30. 21:15·Unrael/Implement

1. 개요

키보드(WASD)를 입력받아 C++코드에서 캐릭터 움직임을 구현한다.

 

2. 구현 프로세스

  1. 환경 설정하기
  2. 입력 액션 생성하기
  3. 입력 맵핑 컨텍스트 생성하기
  4. PlayerController 생성하기
  5. Move 함수 구현하기
  6. 블루프린트 생성하기

 

2.1 환경 설정하기

1. 플러그인 활성화

Edit > Plugins > Enhanced Input

 

2. 입력 컴포넌트 설정

Edit > Project Settings > Engine > Input > Default Classes

 

3. 모듈 추가

/* project.build.cs */
PublicDependencyModuleNames.AddRange(new string[] { "EnhancedInput", ... }

 

 

2.2 입력 액션 생성하기

1. 입력 액션 생성

Content Browser > Input > Input Action

  • Value Type을 Axis2D (Vector2D)로 설정한다.

 

2.3 입력 맵핑 컨텍스트 생성하기

1. 입력 맵핑 컨텍스트 추가

.ContentBrowser > Inpu > Input Mapping Context

  • 입력 액션(IA_Move)을 등록한다.
  • D키는 오른쪽 이동키다.
    • 키 입력시 1값이 X에 전달된다.
  • A키는 왼쪽 이동키다.
    • 입력 값을 반전한다. (Modifiers > Negate)
    • 키 입력시 -1값이 X에 전달된다.
  • W키는 앞으로 이동키다.
    • 입력 값을 재구성(XYZ > YXZ)한다. (Modifiers > Swizzle Input Axis Values)
    • 키 입력시 1값이 Y에 전달된다. 
  • S키는 뒤로 이동키다.
    • 입력 값을 반전한다. (Modifiers > Negate)
    • 입력 값을 재구성(XYZ > YXZ)한다. (Modifiers > Swizzle Input Axis Values)
    • 키 입력시 -1값이 Y에 전달된다.

 

2.4 PlayerController 생성하기

1. 클래스 생성

Tools > New C++ Classes

 

2. 입력 매핑 컨텍스 등록

/* AAuraPlayerController.h */
UCLASS()
class AURA_API AAuraPlayerController : public APlayerController
{
	GENERATED_BODY()

protected:
	virtual void BeginPlay() override;
    
private;
	UPROPERTY(EditDefaultsOnly, Category = Input)
	TObjectPtr<UInputMappingContext> Context;
}
  • BeginPlayer() 함수를 오버라이드한다.
  • 입력 맵핑 컨텍스트를 멤버 변수(Context)로 선언한다.
    • 에디터에서 값을 설정한다.
    • 에디터에서 카테고리명을 "Input"으로 설정한다.

 

/* AAuraPlayerController.cpp */
void AAuraPlayerController::BeginPlay()
{
	Super::BeginPlay();

	check(Context);
	UEnhancedInputLocalPlayerSubsystem* Subsystem =
    	ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>(GetLocalPlayer());
        
	if (Subsystem)
	{
		Subsystem->AddMappingContext(Context, 0);
	}
}
  • 플레이어 컨트롤러가 생성되었을 때(BeginPlay) 입력 맵핑 컨텍스트를 등록한다.

 

3. 입력 액션 바인딩

/* AAuraPlayerController.h */
UCLASS()
class AURA_API AAuraPlayerController : public APlayerController
{
	...
    
protected:
	virtual void SetupInputComponent() override;
    
private:
	UFUNCTION()
	void Move(const FInputActionValue& InputActionValue);
    
	UPROPERTY(EditDefaultsOnly, Category = Input)
	TObjectPtr<UInputAction> MoveAction;
}
  • 키 입력시 바인딩할 함수(Move)를 선언한다.
    • 엔진에 호출될 함수이기에 언리얼 매크로(UFUNCTION)를 등록한다.
  • 입력 액션을 멤버 변수(MoveAction)로 선언한다.
    • 에디터에서 값을 설정한다.
    • 에디터에서 카테고리명을 "Input"으로 설정한다.

 

/* ATestPlayerController.cpp */
void ATestPlayerController::SetupInputComponent()
{
	Super::SetupInputComponent();

	UEnhancedInputComponent* EnhancedInputComponent = CastChecked<UEnhancedInputComponent>(InputComponent);
	EnhancedInputComponent->BindAction(MoveAction, ETriggerEvent::Triggered, this, &AAuraPlayerController::Move);
}
  • 입력 처리 함수(SetupInputComponent)가 호출될 때 입력 액션을 바인딩한다.

 

2.5 Move 함수 구현하기

void AAuraPlayerController::Move(const FInputActionValue& InputActionValue)
{
	const FVector2D InputAxisVector = InputActionValue.Get<FVector2d>();

	const FRotator Rotation = GetControlRotation();
	const FRotator YawRotation = FRotator(0.f, ControlRotation.Yaw, 0.f);

	const FVector ForwardVector = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
	const FVector RightVector = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);

	if (APawn* ControlledPawn = GetPawn())
	{
		ControlledPawn->AddMovementInput(ForwardVector, InputAxisVector.Y);
		ControlledPawn->AddMovementInput(RightVector, InputAxisVector.X);
	}
}
  • 컨트롤러의 회전값으로 전방 벡터와 오른쪽 벡터를 구한다.
    • 회전 값의 Yaw축만으로 벡터 값을 구한다. (XY)
  • 컨트롤러에 빙의된 폰이 있다면 입력된 값만큼 움직인다.

 

2.6 블루프린트 생성하기

1. PlayerController 블루프린트 생성

Content Browser > Blueprint > 생성한 C++Player Controller

  • C++ PlayerController를 상속받은 블루프린트를 생성한다.

 

2. GameMode 블루프린트 생성

Content Browser > Blueprint > GameModeBase

  • GameModeBase를 상속받은 블루프린트를 생성한다.

 

GameMode Blueprint > Editor > Classes > Player Controller Class

  • GameMode 에디터 창에서 플레이어 컨트롤러(BP_AuraPlayerController)를 등록한다.

 

3. 월드 설정에서 GameMode 설정하기

World Settings > GameMode > GameMode Override

 

 

3. 결과 화면

0

 

'Unrael > Implement' 카테고리의 다른 글

[UE/Implement] 미니 프로젝트 회고  (0) 2025.02.13
[UE/Basic] 치트 매니저 (Cheat Manager)  (0) 2025.02.12
[UE/Implement] 트랩 구현  (0) 2025.02.11
[UE/Implement] 액터 하이라이트 표시하기  (0) 2025.01.02
[UE/Implement] 쿼터뷰 구현하기  (0) 2024.12.31
'Unrael/Implement' 카테고리의 다른 글
  • [UE/Basic] 치트 매니저 (Cheat Manager)
  • [UE/Implement] 트랩 구현
  • [UE/Implement] 액터 하이라이트 표시하기
  • [UE/Implement] 쿼터뷰 구현하기
DevColIn
DevColIn
복잡함을 단순하게
  • DevColIn
    심플한 코딩생활
    복잡함을 단순하게
  • 전체
    오늘
    어제
    • 전체보기 (223)
      • Unreal 부트캠프 (49)
        • TIL (34)
        • 사전캠프 (7)
        • 본캠프 (8)
      • Unrael (10)
        • 환경설정 (0)
        • Basic (19)
        • Component (5)
        • GAS (GameplayAbilitySystem) (3)
        • AI (2)
        • Implement (10)
        • UI (1)
        • Error (1)
        • Network (2)
        • Tip (1)
      • Level Design (5)
      • Math (1)
      • Design Pattern (16)
      • Computer Science (2)
        • Network (1)
        • Database (1)
      • Algorithm (79)
        • Basic (4)
        • Practice (74)
      • C++ (4)
        • Basic (4)
      • Tool (0)
      • Game (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 미디어로그
    • 위치로그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    디자인패턴
    Til
    레벨디자인
    unrealengine
    tsoftobjectptr
    basic
    Algorithm
    GameplayEffect
    Animation
    디자인 패턴
    본캠프
    AI
    알고리즘
    사전캠프
    액터
    퀘스트
    Design Pattern
    component
    소프트 레퍼런신
    actor
    게임동기화
    내일배움캠프
    DesignPattern
    gas
    assetmanager
    Implement
    c++
    KPT회고
    unreal
    하드 레퍼런싱
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.2
DevColIn
[UE/Implement] 키 입력으로 캐릭터 움직이기
상단으로

티스토리툴바