Neste tutorial, você criará um personagem e o configurará para receber entrada. Em seguida, atribuirá o personagem a um GameMode para que ele seja o pawn padrão durante o jogo. Após a criação do personagem, você definirá como ele reage a entradas do jogador.
A Unreal permite mapeamentos de entrada mais complexos para diversos tipos de projeto. Confira "Entrada avançada" para obter documentação adicional.
Configuração do projeto
Create a new Games > Blank > C++ project named "SettingUpInput".
In the Editor, navigate to Edit > Project Settings > Input > Bindings.
Configuração de mapeamento de eixo e de ações
A definição de entrada é feita por vinculações definidas pelo usuário de mapeamentos de eixo e de ações. Os dois mapeamentos são mecanismos para associar com facilidade teclas e eixos que informam comportamentos ao inserir uma camada de indireção entre o comportamento de entrada e as teclas que o invocam.
Os mapeamentos de ações são para toques e liberações de tecla. Já os mapeamentos de eixos permitem que as entradas tenham um intervalo contínuo. Quando definir os mapeamentos, você pode os vincular a comportamentos em Blueprints ou C++.
Clique em Adicionar(+) ao lado de "Mapeamento de ações" para criar uma ação chamada Saltar.
Pela seta do menu suspenso(1) ou o botão "Selecionar valor da tecla"(2), pesquise e selecione o valor de tecla "Barra de espaço".
Vá para "Mapeamento de eixo" e clique em Adicionar(+) para criar os seguintes nomes de mapeamento de eixo, valores de tecla e valores de escala:
Nome do mapeamento de eixo Valor da tecla Valor da escala MoveForward
W
1,0
S
-1,0
MoveRight
A
-1,0
D
1,0
Turn
Mouse X
1,0
LookUp
Mouse Y
-1,0
Como criar o personagem de exemplo
A Character is a special type of Pawn that has the ability to walk around. Characters extend from the Pawn class, and inherit similar properties such as physical representation of a player or AI entity within the world.
From the Content Drawer, navigate to the C++ classes folder, right-click and select New C++ Class, then choose Character as your parent class.
Name your character class "ExampleCharacter", then click Create Class.
Como criar componentes SpringArm e de câmera
When the Camera and SpringArm Components are used together, they provide functionality for a third-person perspective that can dynamically adjust to your game world. The camera component contains a camera that represents the player's point of view or how the player sees the world. The SpringArm component is used as a "camera boom" to keep the camera for a player from colliding into the world.
In your code editor, navigate to ExampleCharacter.h. In the Class defaults, declare the following classes.
C++protected: UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Components") class USpringArmComponent* CameraBoom; UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Components") class UCameraComponent* FollowCamera; |UProperty Specifiers are used to provide visibility of the component in the Blueprint Editor.
Navigate to your
ExampleCharacter.cppfile. Add the following libraries to the include line.C++#include "GameFramework/SpringArmComponent.h" #include "Camera/CameraComponent.h"Next, implement the following in the
AExampleCharacterconstructor.C++AExampleCharacter::AExampleCharacter() { //Initialize the Camera Boom CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); //Setup Camera Boom attachment to the Root component of the class CameraBoom->SetupAttachment(RootComponent); //Set the boolean to use the PawnControlRotation to true. CameraBoom->bUsePawnControlRotation = true;The component calls the FObjectInitializer::CreateDefaultSubobjecttemplate, then uses the SetupAttachment method to attach to a parent Scene Component. When setting the Camera Boom to use the Pawn's control rotation, it uses its parent pawn's rotation instead of its own.
Compile your code.
Creating the Action/Axis Functions to your Input Component
In your
ExampleCharacter.hclass defaults, declare the following Input functions.C++protected: void MoveForward(float AxisValue); void MoveRight(float AxisValue);Navigate to your
ExampleCharacter.cppand implement yourMoveForwardandMoveRightmethods.C++void AExampleCharacter::MoveForward(float AxisValue) { if ((Controller != NULL) && (AxisValue != 0.0f)) { // find out which direction is forward const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get forward vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);Navigate to the SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) method, then implement the following code.
C++void AExampleCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump); PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping); PlayerInputComponent->BindAxis("MoveForward", this, &AExampleCharacter::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &AExampleCharacter::MoveRight); PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput);The Player Input Component links the AxisMappings and ActionMappings in your project to game actions. Both the Pawn and Character class contain methods that are inherited and can be used or extended for your custom characters. In our example, we've used the Pawn's AddControllerYawInput and AddControllerPitchInput functions, and the Character's Jump and StopJumping functions.
Compile your code.
Finished Code
ExampleCharacter.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "ExampleCharacter.generated.h"
UCLASS()
class SETTINGUPINPUT_API AExampleCharacter : public ACharacter
{
GENERATED_BODY()
ExampleCharacter.cpp
// Sets default values
AExampleCharacter::AExampleCharacter()
{
//Initialize the Camera Boom
CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
//Setup its attachment to the Root component of the class
CameraBoom->SetupAttachment(RootComponent);
//Set the boolean to use the PawnControlRotation to true.
Creating the Character Blueprint
Navigate to your C++ Classes Folder and right click your ExampleCharacter, from the drop down menu select Create Blueprint class based on ExampleCharacter. Name your Blueprint BP_ExampleCharacter.
In the Components panel, select the Mesh Skeletal Mesh Component.
Navigate to Details > Mesh > Skeletal Mesh and expand the drop-down menu. In the Browser section, click the Settings Icon. Then from the context menu, select Content > Show Engine Content.
Search for and select the TutorialTPP Skeletal Mesh.
Navigate to the Transform category, then set the Location and Rotation vector values to (0.0, 0.0, -90)
Como criar Blueprint de GameMode
The GameMode defines the game's set of rules. These rules include what default pawn the player will spawn when the game is launched. You need to set up these rules to spawn the Player Character you created.
In the Content Drawer, navigate to your C++ Classes folder, right-click the SettingUpInputGameModeBase, then in the drop-down menu select Create Blueprint Based on SettingUpInputGameModeBase. Name your game mode Blueprint "BP_InputGameMode".
In the Class defaults, navigate to Classes > Default Pawn Class, and select the BP_ExampleCharacter.
Compile and Save.
Navigate to Edit > Project Settings > Maps and Modes. Set the Default GameMode to BP_InputGameMode.
Navigate to the Editor and select Play (Play in Editor)
You can now control your character's movement using the W, A, S, D keys. Moving the mouse moves the camera, and pressing the spacebar causes the character to jump.