在项目中的build.cs文件中引入包
- //头文件代码
- UPROPERTY(EditAnywhere)//此标记可以在蓝图中导入映射资产
- class UInputMappingContext*MappingContext;
- UPROPERTY(EditAnywhere)
- class UInputAction * JumpAction;//跳跃事件的action
- UPROPERTY(EditAnywhere)
- UInputAction * MoveAction;//移动事件的action
- virtual void BeginPlay() override;
- virtual void ALGPlayerCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
- //轴映射移动绑定的函数,必须带有一下参数格式必须一致
- void Move(const FInputActionValue& Value);
-
- //cpp文件代码
- //按键操作一般在beginplay中执行
- void ALGPlayerCharacter::BeginPlay()
- {
- Super::BeginPlay();
- //判断一下资产是否添加,否则UE会崩溃
- if(MappingContext)
- {
- //因为按键是在角色身上执行的,所以需要找到角色控制器
- if (APlayerController* PC = Cast
(GetController())) - {
- //通过角色控制找到增强输入子系统
- UEnhancedInputLocalPlayerSubsystem*Subsystem=ULocalPlayer::GetSubsystem
(PC->GetLocalPlayer()); - //将映射表添加至系统中
- Subsystem->AddMappingContext(MappingContext,0);
- }
-
- }
- }
-
- void ALGPlayerCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
- {
- Super::SetupPlayerInputComponent(PlayerInputComponent);
- //使用了增强输入后,旧的输入控件就无法使用,必须使用新的
- if(UEnhancedInputComponent*EnhancedInputComponent = Cast
(PlayerInputComponent)) - {
- //跳跃事件的绑定
- EnhancedInputComponent->BindAction(JumpAction,ETriggerEvent::Started,this,&ALGPlayerCharacter::DoJump);
- //移动事件的绑定
- EnhancedInputComponent->BindAction(MoveAction,ETriggerEvent::Triggered,this,&ALGPlayerCharacter::Move);
- }
- }
-
- //绑定的移动事件
- void ALGPlayerCharacter::Move(const FInputActionValue& Value)
- {
- 获取绑定事件给出的轴值
- FVector2D InputValue = Value.Get
(); - UE_LOG(LogTemp, Log, TEXT("ok%s"),*InputValue.ToString())
- //前后移动
- AddMovementInput(GetActorForwardVector(), InputValue.Y);
- //左右移动
- AddMovementInput(GetActorRightVector(), InputValue.X);
- }