UE4关于Pawn的运动都包装在UPawnMovementComponent类中,在此 类中设定了加速、碰撞等属性和函数功能。我们自定义复杂运动模型时也可以编写一个继承自UPawnMovementComponent或者其他运动类的子类。
在官方教程组件和碰撞中代码如下:
ColidingPawn.h中
要包含PawnMovement头文件
#include "GameFramework/PawnMovementComponent.h"
然后声明PawnMovementComponent类
class UColidingPawnMovementComponent *OurMovementComponent;
ColidingPawn.cpp中
再编写控制的方法
void AColidingPawn::MoveForward(float AxisValue)
{
if (OurMovementComponent && (OurMovementComponent->UpdatedComponent == RootComponent))
{
OurMovementComponent->AddInputVector(GetActorForwardVector() * AxisValue);
}
}
而与此同时方向的设定就“原始”一些:
void AColidingPawn::Turn(float AxisValue)
{
FRotator NewRotation = GetActorRotation();
NewRotation.Yaw += AxisValue;
SetActorRotation(NewRotation);
}
而车辆运动的代码中:
同样的在pawn的头文件中
//包含对应的movement类
#include "WheeledVehicleMovementComponent4W.h"
pawn的.cpp中
void ACPPWheeledVehicle::MoveForward(float Val)
{
GetVehicleMovementComponent()->SetThrottleInput(Val);
}
void ACPPWheeledVehicle::MoveRight(float Val)
{
GetVehicleMovementComponent()->SetSteeringInput(Val);
}
这两者一个是
class UColidingPawnMovementComponent *OurMovementComponent;
OurMovementComponent->UpdatedComponent == RootComponent;
OurMovementComponent->AddInputVector(GetActorForwardVector() * AxisValue);
一个是
GetVehicleMovementComponent()->SetThrottleInput(Val);
是因为ColidingPawn的运动新增了一些特性,是默认PawnMovementComent的子类,所以需要重设。而车辆那个就是默认的VehicleMovementComponent4W类,可以直接用。
自定义运动控制时,可以自定义一个UPawnMovementComponent的子类,然后在其中编写控制的代码;也可以像ColidingPawn的turn()函数那样直接编写,不用编写PawnMovement:
(减速更灵敏,无法后退;无操作时匀速直线运动)
//.h的代码
//速度矢量
UPROPERTY(Category = Movement, VisibleDefaultsOnly, BlueprintReadWrite, meta = (AllowPrivateAccess = "true"))
FVector CurrentSpeed;
//速度标量
UPROPERTY(Category = Movement, VisibleDefaultsOnly, BlueprintReadWrite, meta = (AllowPrivateAccess = "true"))
float ForwardSpeed;
UPROPERTY(Category = Movement, VisibleDefaultsOnly, BlueprintReadWrite, meta = (AllowPrivateAccess = "true"))
FRotator CurrentRotation;
//.cpp的代码
void AMyPawn::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
UpdateLocation(DeltaTime);
}
void AMyPawn::MoveForward(float val)
{
//减速更灵敏
if (val >= 0)
ForwardSpeed += val;
else
if (ForwardSpeed >= 0)
ForwardSpeed += 3.f*val;
if (ForwardSpeed < 0)
ForwardSpeed = 0.0f;
}
void AMyPawn::MoveRight(float val)
{
CurrentRotation.Yaw += val* 0.3f;
SetActorRotation(CurrentRotation);
}
void AMyPawn::UpdateLocation(float DeltaTime)
{
SetActorRotation(CurrentRotation);
CurrentSpeed.X = cos(CurrentRotation.Yaw/180*PI)*ForwardSpeed;
CurrentSpeed.Y = sin(CurrentRotation.Yaw/180*PI)*ForwardSpeed;
FVector VehicleLocation = GetActorLocation();
VehicleLocation += FVector(CurrentSpeed.X*DeltaTime*10.0f,CurrentSpeed.Y*DeltaTime*10.0f,0.0f);
SetActorLocation(VehicleLocation);
}
在此基础上,可以继续添加各种干扰、更复杂的控制方法,实现更仿真的运动模型