Enhanced Input 集成
更新日期:2025-01-03
蓝图对输入系统做了特殊支持,可以自动绑定输入事件。 由于技术原因,Z# 没办法做到和蓝图一样,开发者需要手动绑定输入事件。
信 息
无法自动绑定的原因是 UInputDelegateBinding::SupportsInputDelegate() 函数要求目标是一个蓝图类,而动态类是一个 Native 类,所以无法支持。 如果开发者可以修改引擎源码,理论上可以加入自动绑定机制。
以下示例代码展示了如何在脚本中绑定 Enhanced Input 的输入事件:
PlayerController pc = ...;
EnhancedInputLocalPlayerSubsystem? subsystem = pc.GetSubsystem<EnhancedInputLocalPlayerSubsystem>();
if (subsystem is null)
{
return;
}
InputMappingContext imc = ...;
subsystem.AddMappingContext(imc, 0);
EnhancedInputComponent component = ...;
InputAction inputActionMove = ...;
UnrealObject handle = component.BindAction(inputActionMove, ETriggerEvent.Triggered, static (value, _, _, _, @this) =>
{
var (right, forward) = value;
Rotator controlRot = @this.GetControlRotation();
controlRot.Pitch = controlRot.Roll = 0;
Quat quat = KismetMathLibrary.Conv_RotatorToQuaternion(controlRot);
Vector worldDir = KismetMathLibrary.Quat_RotateVector(quat, new(forward, right, 0));
@this.AddMovementInput(worldDir, (float)Math.Sqrt(right * right + forward * forward));
}, this);
BindAction()
方法返回一个 UnrealObject 类型的句柄,这和绑定委托时是一样的。
开发者需要将这个句柄缓存到一个 UProperty
或者 StrongObjectPtr
中来保持对它的引用。
绑定输入事件的逻辑推荐写在 SetupInputComponent()
函数中,但由于这个函数没有导出给脚本,需要开发者自行导出。