将用户输入绑定到UE4.22.3及更高版本中的UActorComponent方法

Bind user input to UActorComponent methods in UE4.22.3 and Up

本文关键字:版本 方法 UActorComponent 高版本 绑定 输入 用户 UE4      更新时间:2023-10-16

我正在尝试创建将处理一些用户输入的UActorComponent。我是这样做的:

void MyComponent::BeginPlay()
{
    Super::BeginPlay();
    this->InputComponent = GetOwner() ->FindComponentByClass<UInputComponent>();
    if (this->InputComponent != nullptr) {
        UE_LOG(LogTemp, Display, TEXT("%s InputComponent Found"), *(GetReadableName()));
        this->InputComponent->BindAction("MyAction", IE_Pressed, this, &MyComponent::ActionStart);
        this->InputComponent->BindAction("MyAction", IE_Released, this, &MyComponent:: ActionEnd);
        UE_LOG(LogTemp, Display, TEXT("%s InputComponent Binding done"), *(GetReadableName()));
    }
}

但是,组件的方法从未调用过。我发现Pawns SetupPlayerInputComponent方法之后的所有绑定都被调用了。如果我在SetupPlayerInputComponent内执行所有绑定,则所有绑定都可以正常工作。

那么,在

UActorComponent中处理用户输入的最佳方法是什么,或者根本不是好的做法?

正如您提到的,如果您调用 SetupPlayerInputComponent 中的函数,绑定会起作用,因此最简单的解决方案是在组件中创建一个名为 SetupInput 的函数,并从 pawn 的 SetupPlayerInputComponent 函数调用该函数。

是的,在我看来,绑定应该由受控棋子或玩家控制器处理,因为这就是ue4游戏框架的工作方式。如果您没有任何特定的棋子要控制,或者如果它只是一个摄像机,我会在控制器内移动我的所有输入,将其移动到棋子本身中。

SetupPlayerInputComponent 中

InputComponent->BindAction("MyAction", IE_Pressed, MyComponentRef, &MyComponent::ActionStart);

至于它是否是好的做法,它可以有它的好处,主要是减少混乱或在 APawn 的几个不相关的子类中重用输入处理程序。