UE5 Enhanced Input 输入增强系统学习

蓝图实现

首先开启和配置插件

创建一个第三人称蓝图模板,开启和配置 Enhanced Input 插件如下
开启和配置插件
然后在项目设置里修改默认输入系统
开启和配置插件

创建 Input Action输入操作

创建 Input Action输入操作

  • Input Action是一个定义输入事件和绑定输入操作的机制。使用Input Action可以将特定的键、按钮或手柄操作映射到一个自定义的、易于识别的名称上,从而加强了代码的可读性和可维护性。
  • 通过定义Input Action,开发者可以在整个游戏中使用相同的输入事件,并将其绑定到不同的输入设备上,如键盘、鼠标、手柄等。
  • Input Action还支持具有多个按键组合的输入操作(例如Ctrl+Shift+F),并方便地处理重复按键和动态修改操作映射。
  • 通过将Input Action与其他模块(例如动作和输入轴)结合使用,开发者可以轻松地实现交互式游戏体验,同时保持高度的可定制性和可扩展性。

创建 Input Mapping Context

创建 Input Mapping Context

  • Input Mapping Context是一个上下文环境,用于控制在何时和何地处理输入操作。通过定义Input Mapping Context,开发者可以区分不同的游戏阶段或操作模式,并根据需要切换输入映射。
    例如,游戏可能具有不同的状态,例如主菜单、游戏中、暂停等,在每个状态下支持的输入操作也可能不同。使用Input Mapping Context,开发者可以定义基于状态的输入映射,并在状态之间进行动态切换。
  • Input Mapping Context还可以用于优先级管理和操作组织。当多个操作具有相同的按键或手柄按钮映射时,Input Mapping Context可用于确定首选操作并在按键被触发时先处理它。
  • Input Mapping Context还支持层叠模式,允许为每个输入操作定义多个上下文环境。这样做可以提高代码的可重用性和灵活性,并使得更改某一输入操作不必影响其他部分的功能。

进入第三人称蓝图绑定Input Mapping Context

绑定Input Mapping Context

实现跳跃功能

编辑 IA_Jump如下
实现跳跃功能
ValueType选择Digital,跳跃不需要具体值,只需要是否就可以表达。

编辑IMC_Action如下
编辑IMC_Action
在第三人称蓝图里绑定跳跃操作。(注意要删除工程自带的IA_Jump,绑定自己创建的。后面的打印可以不需要。)
实现跳跃功能

编译保存运行,可以看到角色可以跳跃了。(打印的是ValueType)
实现跳跃功能

实现前后移动

编辑IA_MoveForward_Backword,把ValueType改成Axis2D,移动需要具体值,值越高速移动度越快。
实现前后移动
编辑IMC_Action,加入按键绑定
实现前后移动
这里S要为负值,所以要在Modifiers里选Negate。
最后编辑角色蓝图
实现前后移动
保存编译运行,角色可以前后移动了

实现左右移动

同样的操作
实现左右移动
实现左右移动
实现左右移动
保存编译运行,角色可以前后左右移动了

实现控制视角上下左右

新建2个Input Action
实现控制视角上下左右
进入编辑,这里都选择Axis2D
实现控制视角上下左右
然后在IMC_Action里绑定按键操作
实现控制视角上下左右
在角色蓝图里绑定如下:
实现控制视角上下左右
保存编译运行,视角可以上下左右看了。
在UE5.1里,第三人称模板默认启用了Enhanced Input,可以看看官方是如何使用的。

C++实现

新建一个C++空项目 EIHCPP ,导入第三人称工程包
新建一个C++空项目 EIHCPP
导入第三人称工程包
导入第三人称工程包

开启和配置插件

操作和蓝图一样
编辑 EIHCPP.Build.cs,加入 EnhancedInput 引用,代码如下:

// Copyright Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
public class EIHCPP : ModuleRules
{
	public EIHCPP(ReadOnlyTargetRules Target) : base(Target)
	{
		PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
		PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "EnhancedInput" });
		PrivateDependencyModuleNames.AddRange(new string[] {  });
	}
}

新建游戏模式和角色代码

新建游戏模式和角色代码

新建游戏模式和角色代码
指定游戏模式为EIHCPPGameMode
新建游戏模式和角色代码
创建角色
创建角色
创建角色

新建输入操作蓝图

3个输入操作蓝图名称分别为IA_Jump, IA_Look和IA_Move
新建输入操作蓝图
分别编辑如下
新建输入操作蓝图新建输入操作蓝图
新建输入操作蓝图

新建输入映射情境蓝图

名称为IMC_Default
新建输入映射情境蓝图
编辑如下

编辑输入映射情境蓝图
编辑输入映射情境蓝图

编辑角色文件

IHCPPCharacter.h

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "InputActionValue.h"
#include "IHCPPCharacter.generated.h"

UCLASS()
class EIHCPP_API AIHCPPCharacter : public ACharacter
{
	GENERATED_BODY()


public:
	AIHCPPCharacter();

	// 弹性臂组件
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
	class USpringArmComponent* CameraBoom;

	// 摄像机组件
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
	class UCameraComponent* FollowCamera;

	// 输入映射情境
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Input, meta = (AllowPrivateAccess = "true"))
	class UInputMappingContext* DefaultMappingContext;

	// 角色跳输入操作
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Input, meta = (AllowPrivateAccess = "true"))
	class UInputAction* JumpAction;

	// 角色移动输入操作
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Input, meta = (AllowPrivateAccess = "true"))
	class UInputAction* MoveAction;

	// 视角输入操作
	UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Input, meta = (AllowPrivateAccess = "true"))
	class UInputAction* LookAction;

protected:
	
	virtual void BeginPlay() override;

	virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;

	// 移动操作回调方法
	void Move(const FInputActionValue& Value);

	// 视角操作回调方法
	void Look(const FInputActionValue& Value);
};

IHCPPCharacter.cpp

// Fill out your copyright notice in the Description page of Project Settings.

#include "IHCPPCharacter.h"
#include "GameFramework/SpringArmComponent.h"
#include "Camera/CameraComponent.h"
#include "EnhancedInputComponent.h"
#include "EnhancedInputSubsystems.h"
#include "EnhancedInputSubsystemInterface.h"
// #include "InputActionValue.h"
// #include "InputMappingContext.h"

// Sets default values
AIHCPPCharacter::AIHCPPCharacter()
{
	// 初始化弹性臂组件
	CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
	CameraBoom->SetupAttachment(RootComponent); // 弹性臂组件附加到跟节点
	CameraBoom->TargetArmLength = 400.0f; // 弹性臂组件长度
	CameraBoom->bUsePawnControlRotation = true; // 控制器能控制弹性臂组件旋转

	// 初始化摄像机组件
	FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera"));
	FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // 摄像机组件附加到弹性臂组件上
	FollowCamera->bUsePawnControlRotation = false; // 摄像机不相对于弹性臂旋转

	// 加载输入配置文件
	/* static ConstructorHelpers::FObjectFinder<UInputAction> LookInputAction(TEXT("/Game/Input/IA_Look.IA_Look"));
	static ConstructorHelpers::FObjectFinder<UInputAction> MoveInputAction(TEXT("/Game/Input/IA_Move.IA_Move"));
	static ConstructorHelpers::FObjectFinder<UInputMappingContext> IMC(TEXT("/Game/Input/IMC_Default.IMC_Default"));
	if (LookInputAction.Succeeded() && MoveInputAction.Succeeded() && IMC.Succeeded()) {
		LookAction = LookInputAction.Object;
		MoveAction = MoveInputAction.Object;
		DefaultMappingContext = IMC.Object;
	}*/

	// 本地找到模型文件
	static ConstructorHelpers::FObjectFinder<USkeletalMesh> playerPawn(TEXT("/Script/Engine.SkeletalMesh'/Game/Characters/Mannequins/Meshes/SKM_Quinn_Simple.SKM_Quinn_Simple'"));
	if (playerPawn.Succeeded()) {

		// 把模型添加给组件的静态网格体
		GetMesh()->SetSkeletalMesh(playerPawn.Object);

		// 设置网格体位置
		GetMesh()->SetRelativeLocation(FVector(0, 0, -90.0f));

		// 设置网格体默认方向
		GetMesh()->SetRelativeRotation(FRotator(0, -90.0f, 0.f));
	}
}

void AIHCPPCharacter::BeginPlay()
{
	Super::BeginPlay();

	// 加入按键操作绑定功能
	if (APlayerController* PlayerController = Cast<APlayerController>(Controller))
	{
		if (UEnhancedInputLocalPlayerSubsystem* Subsystem = ULocalPlayer::GetSubsystem<UEnhancedInputLocalPlayerSubsystem>(PlayerController->GetLocalPlayer()))
		{
			Subsystem->AddMappingContext(DefaultMappingContext, 0);
		}
	}
}

void AIHCPPCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
	// 绑定输入操作
	if (UEnhancedInputComponent* EnhancedInputComponent = CastChecked<UEnhancedInputComponent>(PlayerInputComponent)) {
		
		// 绑定角色跳输入操作
		EnhancedInputComponent->BindAction(JumpAction, ETriggerEvent::Triggered, this, &ACharacter::Jump);
		EnhancedInputComponent->BindAction(JumpAction, ETriggerEvent::Completed, this, &ACharacter::StopJumping);

		// 绑定移动操作
		EnhancedInputComponent->BindAction(MoveAction, ETriggerEvent::Triggered, this, &AIHCPPCharacter::Move);

		// 绑定视角操作
		EnhancedInputComponent->BindAction(LookAction, ETriggerEvent::Triggered, this, &AIHCPPCharacter::Look);
	}
}

// 移动操作回调方法
void AIHCPPCharacter::Move(const FInputActionValue& Value)
{
	FVector2D MovementVector = Value.Get<FVector2D>();

	if (Controller != nullptr)
	{
		const FRotator Rotation = Controller->GetControlRotation();
		const FRotator YawRotation(0, Rotation.Yaw, 0);

		const FVector ForwardDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X);
		
		const FVector RightDirection = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y);
		
		AddMovementInput(ForwardDirection, MovementVector.Y);
		AddMovementInput(RightDirection, MovementVector.X);
	}
}

// 视角操作回调方法
void AIHCPPCharacter::Look(const FInputActionValue& Value)
{
	FVector2D LookAxisVector = Value.Get<FVector2D>();

	if (Controller != nullptr)
	{
		AddControllerYawInput(LookAxisVector.X);
		AddControllerPitchInput(LookAxisVector.Y);
	}
}

创建角色蓝图

建角色蓝图
创建角色蓝图
编辑 BP_IHCPPCharacter蓝图,指定输入操作如下
在这里插入图片描述

编辑游戏模式

编辑 EIHCPPGameMode代码如下:
EIHCPPGameMode.h

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "EIHCPPGameMode.generated.h"

/**
 * 
 */
UCLASS()
class EIHCPP_API AEIHCPPGameMode : public AGameModeBase
{
	GENERATED_BODY()
public:
	AEIHCPPGameMode();
};

EIHCPPGameMode.cpp

// Fill out your copyright notice in the Description page of Project Settings.

#include "EIHCPPGameMode.h"
#include "IHCPPCharacter.h"
#include "UObject/ConstructorHelpers.h"

AEIHCPPGameMode::AEIHCPPGameMode()
{
	static ConstructorHelpers::FClassFinder<APawn> PlayerPawnBPClass(TEXT("/Script/Engine.Blueprint'/Game/Blueprint/BP_IHCPPCharacter.BP_IHCPPCharacter_C'"));
	// 指定默认控制角色
	if (PlayerPawnBPClass.Class != NULL)
	{
		DefaultPawnClass = PlayerPawnBPClass.Class;
	}
}

保存编译,指定游戏模式
指定游戏模式
最后运行, 可以控制角色和视角基本操作。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值