UE4小游戏二—创建能移动的主角
- 创建主角继承于character类
先上代码(一部分,只是关于移动的代码)
MyPacManCharacter.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "MyPacManCharacter.generated.h"
UCLASS()
class MYPACMANCOPY_API AMyPacManCharacter : public ACharacter
{
GENERATED_BODY()
public:
// Sets default values for this character's properties
AMyPacManCharacter();
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;
//创建StaticMesh
/*UPROPERTY()
UStaticMeshComponent* MyPacMan;*/
int Lives; //生命值
void MoveXAxis(float AxisValue); //在X上移动
void MoveYAxis(float AxisValue);//在Y轴上移动
private:
FVector StartPoint; //初始点
FVector CurrentVelocity;//移动速度
};
MyPacManCharacter.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "..\Public\MyPacManCharacter.h"
// Sets default values
AMyPacManCharacter::AMyPacManCharacter()
{
// 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;
}
void AMyPacManCharacter::MoveXAxis(float AxisValue)
{
CurrentVelocity.X = AxisValue;
AddMovementInput(CurrentVelocity);
}
void AMyPacManCharacter::MoveYAxis(float AxisValue)
{
CurrentVelocity.Y = AxisValue;
AddMovementInput(CurrentVelocity);
}
// Called when the game starts or when spawned
void AMyPacManCharacter::BeginPlay()
{
Super::BeginPlay();
Lives = 3;
StartPoint = GetActorLocation();//在游戏开始获取主角位置
}
// Called every frame 每一帧都会调用,想保持无论FPS怎么变都不影响移动的话,就得用到DeltaTime
void AMyPacManCharacter::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
// Called to bind functionality to input
void AMyPacManCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
PlayerInputComponent->BindAxis("MoveX", this, &AMyPacManCharacter::MoveXAxis);//绑定输入的X轴
PlayerInputComponent->BindAxis("MoveY", this, &AMyPacManCharacter::MoveYAxis);//绑定输入的Y轴
}
当需要连续按键的时候,像移动这样的需要用到轴映射,当需要检测按键是否按下时,像跳跃这种需要Action映射。还需要注意的是移动的方向最好看你地图的X轴和Y轴的方向进行绑定。
代码写好了,需要在UE里面进行操作了,首先创建继承于character的蓝图类
对蓝图character类进行操作,首先添加StaticMesh组件,然后设置材质,大小,形状
要想character动起来就需要用到GameModeBase了,首先创建继承于GameModeBase的蓝图类
点开BP_GameModeBases设置,将默认Pawn类改为我们创建好的BP_MyPacManCharacter类。
然后在项目设置的默认游戏模式改为BP_GameModeBases模式,那么就可以操控你的主角了。
因为没有设置碰撞属性,所以主角可能会被挡住,下一节会进行碰撞的设置。