UEC++ 按键输入绑定

目录

触发时机的枚举类型

旧版输入系统

Enhanced Input System


APlayerController类定义了一个虚函数SetupInputComponent用于设置按键输入绑定;

UInputComponentAActor的成员变量;

触发时机的枚举类型

EInputEvent 枚举类型,旧版用于定义输入事件的触发时机;

ETriggerEvent 枚举类型,增强输入系统中定义输入事件触发时机;取代旧版输入系统中的 EInputEvent,功能更强大、粒度更细;

旧版输入系统

// 旧版按键输入绑定,绑定到项目设置好的 Action Mappings 和 Axis Mappings void AMyPlayerController::SetupInputComponent() { Super::SetupInputComponent(); // 绑定动作(如跳跃,按下触发一次) InputComponent->BindAction("Jump", IE_Pressed, this, &AMyPlayerController::StartJump); InputComponent->BindAction("Jump", IE_Released, this, &AMyPlayerController::StopJump); // 绑定轴(如移动,持续触发,提供连续值) InputComponent->BindAxis("MoveForward", this, &AMyPlayerController::MoveForward); InputComponent->BindAxis("MoveRight", this, &AMyPlayerController::MoveRight); }

Enhanced Input System

UE5后推荐使用增强输入系统(Enhanced Input System),更强大更灵活;通过 Input Action,Input Mapping Context 等资产来解耦输入映射和逻辑;

  • 项目设置内设置默认输入类;

  • BeginPlay中,在Input Mapping Context添加UEnhancedInputLocalPlayerSubsystem

// 类中声明输入动作资产指针 UPROPERTY(EditAnywhere, Category = "Input") class UInputAction* JumpAction; void AMyPlayerController::SetupInputComponent() { Super::SetupInputComponent(); // InputComponent 是根据项目设置自动创建的子类实例,需转化 if (UEnhancedInputComponent* EnhancedInputComponent = Cast<UEnhancedInputComponent>(InputComponent)) { // 绑定增强输入动作 EnhancedInputComponent->BindAction(JumpAction, ETriggerEvent::Started, this, &AMyPlayerController::StartJump); EnhancedInputComponent->BindAction(MoveAction, ETriggerEvent::Triggered, this, &AMyPlayerController::Move); } }