1.创建输入动作:
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Input", meta = (AllowPrivateAccess = "true"))
TObjectPtr<UInputAction> InputAction_Move;
2.创建回调函数:
void HandleMoveInput(const FInputActionValue& InputActionValue);
3.绑定输入动作、回调函数:
EnhancedInputComponent->BindAction(InputAction_Move, ETriggerEvent::Triggered, this, &ACPlayerCharacter::HandleMoveInput);
4.实现回调函数:
void ACPlayerCharacter::HandleMoveInput(const FInputActionValue& InputActionValue)
{
//获取鼠标轴二维向量
const FVector2D InputValue = InputActionValue.Get<FVector2D>();
//结果归一化
InputValue.GetSafeNormal();
AddMovementInput(GetMoveForwardDir()*InputValue.Y+GetLookRightDir()*InputValue.X);
}
FVector ACPlayerCharacter::GetLookRightDir() const
{
return FollowCamera->GetRightVector();
}
FVector ACPlayerCharacter::GetLookForwardDir() const
{
return FollowCamera->GetForwardVector();
}
FVector ACPlayerCharacter::GetMoveForwardDir() const
{
return FVector::CrossProduct(GetLookRightDir(), FVector::UpVector);
}
这段代码实现了虚幻引擎中基于摄像机视角的角色移动控制逻辑,主要功能包括:
输入处理
HandleMoveInput方法通过FInputActionValue获取二维输入向量- 使用
GetSafeNormal()对输入向量进行归一化处理,确保移动速度不受输入幅度影响
方向计算
GetLookRightDir返回摄像机右方向向量,用于水平移动GetLookForwardDir返回摄像机前方向向量(虽然代码中未直接使用)GetMoveForwardDir通过叉积计算地面移动方向(摄像机右向量×世界向上向量)
移动合成
- 最终通过
AddMovementInput将垂直(Y)和水平(X)输入分量分别与对应方向向量相乘后相加 - 这种实现方式使角色移动方向始终与摄像机视角保持相对一致
典型应用场景是第一/第三人称角色控制器,其中移动方向会随摄像机旋转而变化。代码中通过向量运算实现了视角相关的移动控制,是UE中处理角色移动的常见模式。
其中:
InputValue.GetSafeNormal();
TVector2<T> GetSafeNormal(T Tolerance=UE_SMALL_NUMBER) const;
这是一个典型的模板函数声明,用于获取二维向量的安全归一化结果。以下是关键点分析:
模板参数
T表示泛型类型参数,支持不同数值类型(如float/double)的向量计算。
函数功能
- 对向量进行归一化(单位化)处理,返回长度为1的同方向向量。
- 通过
Tolerance参数(默认值为引擎常量UE_SMALL_NUMBER)避免除零错误:当向量长度小于该阈值时,可能返回零向量或特定默认值。

最低0.47元/天 解锁文章
981

被折叠的 条评论
为什么被折叠?



