void APlayingCharacter::MoveForward(float val) { AddMovementInput(GetActorForwardVector(), val); } void APlayingCharacter::MoveBack(float val) { AddMovementInput(-GetActorForwardVector(), val); } void APlayingCharacter::MoveRight(float val) { AddMovementInput(GetActorRightVector(), val); } void APlayingCharacter::MoveLeft(float val) { AddMovementInput(-GetActorRightVector(), val); }AddMovementInput() 这个函数会根据第一个参数的值去移动角色,第二个参数是个浮点数,如果这个数是 1 的话,那么它会按照第一个参数的方向去添加,如果第二个参数是 -1 的话,那么会往第一个参数的反方向去添加。
APlayingCharacter.h // Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Character.h" #include "PlayingCharacter.generated.h" UCLASS() class GAMEPROJECT_API APlayingCharacter : public ACharacter { GENERATED_BODY() public: // Sets default values for this character's properties APlayingCharacter(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; // Called to bind functionality to input virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; void MoveForward(float val);//人物往前移动 void MoveBack(float val); //人物向后 void MoveRight(float val); //人物向右 void MoveLeft(float val); //人物向左 }; APlayingCharacter.Cpp // Fill out your copyright notice in the Description page of Project Settings. #include "PlayingCharacter.h" // Sets default values APlayingCharacter::APlayingCharacter() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; } // Called when the game starts or when spawned void APlayingCharacter::BeginPlay() { Super::BeginPlay(); } // Called every frame void APlayingCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); } // Called to bind functionality to input void APlayingCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); InputComponent->BindAxis("MoveForward", this, &APlayingCharacter::MoveForward); InputComponent->BindAxis("MoveBack", this, &APlayingCharacter::MoveBack); InputComponent->BindAxis("MoveRight", this, &APlayingCharacter::MoveRight); InputComponent->BindAxis("MoveLeft", this, &APlayingCharacter::MoveLeft); InputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput); InputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput); } void APlayingCharacter::MoveForward(float val) { AddMovementInput(GetActorForwardVector(), val); } void APlayingCharacter::MoveBack(float val) { AddMovementInput(-GetActorForwardVector(), val); } void APlayingCharacter::MoveRight(float val) { AddMovementInput(GetActorRightVector(), val); } void APlayingCharacter::MoveLeft(float val) { AddMovementInput(-GetActorRightVector(), val); }
本文链接:http://task.lmcjl.com/news/13838.html