[C++] 플레이어 이동

Woogle·2022년 10월 28일
0

언리얼 엔진 5

목록 보기
18/63

BP로 만들었던 플레이어 이동을 C++로 옮겨보았다.


📄 Blueprint

✏️ Event Graph


📄 C++

✏️ 헤더

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "PlayerPawn.generated.h"

UCLASS()
class MYSHOOTINGCPP_API APlayerPawn : public APawn
{
	GENERATED_BODY()

public:
	// Sets default values for this pawn's properties
	APlayerPawn();

protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

public:	
	// Called every frame
	virtual void Tick(float DeltaTime) override;

	// Called to bind functionality to input
	virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
	
    // 스태틱메쉬 컴포넌트
	UPROPERTY(EditAnywhere)
	class UStaticMeshComponent* meshComp;

	// 키 입력 바인딩할 함수
	void OnAxisHorizontal(float Value);
	void OnAxisVertical(float Value);

	float horizontal;
	float vertical;

	// 속도 (스칼라)
	UPROPERTY(EditAnywhere)
	float speed = 500;
};

✏️ 소스

#include "PlayerPawn.h"

// Sets default values
APlayerPawn::APlayerPawn()
{
 	// Set this pawn to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

	// 스태틱 메쉬 컴포넌트 생성
	meshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("meshComp"));
}

// Called when the game starts or when spawned
void APlayerPawn::BeginPlay()
{
	Super::BeginPlay();
	
}

// Called every frame
void APlayerPawn::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	// 현재 위치 (P0)
	FVector p0 = GetActorLocation();

	// 속력 (v)
	FVector direction = FVector(0, horizontal, vertical);
	direction.Normalize();	// 단위벡터
	FVector velocity = direction * speed;

	// P = P0 + v*t
	SetActorLocation(p0 + velocity * DeltaTime);
}

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

	// 키 입력 시 호출할 함수를 바인딩
	PlayerInputComponent->BindAxis(TEXT("Horizontal"), this, &APlayerPawn::OnAxisHorizontal);
	PlayerInputComponent->BindAxis(TEXT("Vertical"), this, &APlayerPawn::OnAxisVertical);
}

void APlayerPawn::OnAxisHorizontal(float Value)
{
	horizontal = Value;
}

void APlayerPawn::OnAxisVertical(float Value)
{
	vertical = Value;
}

참고자료

  • 인생 언리얼 교과서
profile
노력하는 게임 개발자

0개의 댓글