En este tutorial, crearás un personaje y lo configurarás para que reciba entrada, luego asignarás al personaje a un modo de juego (GameMode) para que sea el peón por defecto al jugar. Después de crear a tu personaje, definirás cómo reacciona a la entrada del jugador.
Unreal proporciona mapeados de entrada más complejos para diversos tipos de proyecto. Consulta Enhanced Input para leer más al respecto.
Configuración del proyecto
Create a new Games > Blank > C++ project named "SettingUpInput".
In the Editor, navigate to Edit > Project Settings > Input > Bindings.
Configuración de asignación de ejes y acciones
La entrada se determina a través de las vinculaciones definidas por el usuario para asignación de ejes y acciones. Ambas asignaciones son un mecanismo práctico para asignar teclas y ejes a comportamientos de entrada mediante la inserción de una capa de direccionamiento indirecto entre el comportamiento de entrada y las teclas que lo invocan.
Las asignaciones de acción son para presionar y soltar teclas, mientras que las asignaciones de eje permiten entradas que tienen un rango continuo. Cuando hayas definido tus asignaciones, puedes vincularlas a comportamientos en Blueprint o en C++.
Haz clic en Añadir (+), al lado de Asignaciones de acciones, para crear una nueva acción llamada Jump.
Desde la flecha desplegable(1) o desde el botón Seleccionar valor de tecla(2), busca y selecciona el valor de la tecla Barra espaciadora.
Ve hasta Asignaciones de ejes y haz clic en Añadir (+) para crear los siguientes nombres de asignación de ejes, valores de teclas y valores de escala:
Nombre de asignación de eje Tecla Valor de Scale MoveForward
W
1,0
S
-1.0
MoveRight
A
-1.0
D
1,0
Turn
Mouse X
1,0
LookUp
Mouse Y
-1.0
Creación del personaje de ejemplo
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.
Creación de los componentes de cámara y SpringArm
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)
Creación del 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.