C++ 绑定:EnhancedInputComponent

绑定模式:三种委托演示

void AMyPlayerController::SetupInputComponent()
{
    Super::SetupInputComponent();

    UEnhancedInputComponent* EIC = Cast<UEnhancedInputComponent>(InputComponent);
    if (EIC)
    {
        EIC->BindAction(IA_Jump, ETriggerEvent::Started,  this, &AMyPlayerController::OnJumpStarted);
        EIC->BindAction(IA_Jump, ETriggerEvent::Triggered, this, &AMyPlayerController::OnJump);
        EIC->BindAction(IA_Move, ETriggerEvent::Triggered, this, &AMyPlayerController::OnMove);
        EIC->BindAction(IA_Look, ETriggerEvent::Triggered, this, &AMyPlayerController::OnLook);

        // Lambda / UObject 委托也支持
        EIC->BindAction(IA_Fire, ETriggerEvent::Triggered, this, &AMyPlayerController::OnFire);
    }
}

void AMyPlayerController::OnMove(const FInputActionValue& Value)
{
    FVector2D MoveVec = Value.Get<FVector2D>();
    if (APawn* P = GetPawn())
        P->AddMovementInput(FRotationMatrix(P->GetControlRotation()).GetScaledAxis(EAxis::Y) * MoveVec.Y
                          + FRotationMatrix(P->GetControlRotation()).GetScaledAxis(EAxis::X) * MoveVec.X, 1.f, false);
}

触发事件枚举对应蓝图阶段

ETriggerEvent 对应
Started Started 阶段
Triggered 满足 Trigger 条件
Ongoing 持续(即使未 Trigger)
Completed 正常完成
Canceled 取消

缓存 IA 引用:IA 通常是 UPROPERTY(EditDefaultsOnly) 引用(手动指定资产),或 ConstructorHelpers 加载。

放哪个类里?

类 适合接什么
PlayerController 与全局操作有关(暂停、视角、交互)
Pawn/Character 与自身状态有关(移动、跳跃)
Actor 组件(如 USpringArmComponent) 自己关心的输入(视角缩放)

常见工程实践:输入路由集中在 PlayerController,再转发给 Pawn 的公开函数(第 1 本"通信选型"原则)。

本章小结

  • C++ 绑定用 UEnhancedInputComponent::BindAction + ETriggerEvent 枚举。
  • 移动向量要乘相机朝向(FRotationMatrix)实现"方向跟手"。
  • 输入路由放 Controller 或 Pawn,按"与谁状态相关"判断。