# HowTo_PlayerInput **Repository Path**: wblong/how-to_-player-input ## Basic Information - **Project Name**: HowTo_PlayerInput - **Description**: 对Pawn类进行扩展,以便响应玩家的输入操作。 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-07-30 - **Last Updated**: 2021-10-21 ## Categories & Tags **Categories**: Uncategorized **Tags**: Cpp, UE4 ## README # 玩家输入和Pawn 对Pawn类进行扩展,以便响应玩家的输入操作。 ## Code ### 可视化相机 ```cpp // 创建可附加内容的虚拟根组件。 RootComponent = CreateDefaultSubobject(TEXT("RootComponent")); // 创建相机和可见对象 UCameraComponent* OurCamera = CreateDefaultSubobject(TEXT("OurCamera")); OurVisibleComponent = CreateDefaultSubobject(TEXT("OurVisibleComponent")); // 将相机和可见对象附加到根组件。偏移并旋转相机。 OurCamera->SetupAttachment(RootComponent); OurCamera->SetRelativeLocation(FVector(-250.0f, 0.0f, 250.0f)); OurCamera->SetRelativeRotation(FRotator(-45.0f, 0.0f, 0.0f)); OurVisibleComponent->SetupAttachment(RootComponent); ``` ![可视化相机](./Images/HowTo_PlayerInput.png) ### 绑定输入函数 ```cpp //输入函数 void Move_XAxis(float AxisValue); void Move_YAxis(float AxisValue); void StartGrowing(); void StopGrowing(); //输入变量 FVector CurrentVelocity; bool bGrowing; //AMyPawn::SetupPlayerInputComponent // 在按下或松开"Grow"键时做出响应。 InputComponent->BindAction("Grow", IE_Pressed, this, &AMyPawn::StartGrowing); InputComponent->BindAction("Grow", IE_Released, this, &AMyPawn::StopGrowing); // 对两个移动轴"MoveX"和"MoveY"的值逐帧反应。 InputComponent->BindAxis("MoveX", this, &AMyPawn::Move_XAxis); InputComponent->BindAxis("MoveY", this, &AMyPawn::Move_YAxis); ``` ### 处理操作 ```cpp // 根据"Grow"操作处理增长和缩减 { float CurrentScale = OurVisibleComponent->GetComponentScale().X; if (bGrowing) { // 一秒内增长到两倍大小 CurrentScale += DeltaTime; } else { // 以增长速度缩减一半 CurrentScale -= (DeltaTime * 0.5f); } // 确保不会降至初始大小以下,或者增至两倍大小以上。 CurrentScale = FMath::Clamp(CurrentScale, 1.0f, 2.0f); OurVisibleComponent->SetWorldScale3D(FVector(CurrentScale)); } // 根据"MoveX"和"MoveY"轴处理移动 { if (!CurrentVelocity.IsZero()) { FVector NewLocation = GetActorLocation() + (CurrentVelocity * DeltaTime); SetActorLocation(NewLocation); } } ``` ## Note ```cpp /** Component that handles input for this actor, if input is enabled. */ // 如果启用了输入,则处理此角色的输入的组件。 UPROPERTY(DuplicateTransient) class UInputComponent* InputComponent; ``` ## Reference 1. [玩家输入和Pawn - https://docs.unrealengine.com/4.26/zh-CN/ProgrammingAndScripting/ProgrammingWithCPP/CPPTutorials/PlayerInput/](https://docs.unrealengine.com/4.26/zh-CN/ProgrammingAndScripting/ProgrammingWithCPP/CPPTutorials/PlayerInput/)