在上一篇(10-控制Pawn类移动)基础上增加镜头摇臂功能
在MyPawn.h中增加如下代码:
UPROPERTY(VisibleAnywhere)
class USphereComponent* SphereComp; //定义一个球形组件UPROPERTY(VisibleAnywhere)
class USpringArmComponent* SprintArmComp; //定义一个弹簧臂
在MyPawn.cpp中增加如下代码:
#include "UObject/ConstructorHelpers.h"
#include "Components/SphereComponent.h"
#include "GameFramework/SpringArmComponent.h"
SphereComp = CreateDefaultSubobject<USphereComponent>(TEXT("Sphere"));SphereComp->SetSphereRadius(80); //设置球形组件的半径SphereComp->SetCollisionProfileName(TEXT("BlockAll")); //设置碰撞轮廓名称SphereComp->SetHiddenInGame(false); //不让球形组件隐藏SetRootComponent(SphereComp); //将球形组件设为根组件//RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent")); //创建一个根组件MeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MeshComponent")); //创建一个Mesh组件MeshComponent->SetupAttachment(GetRootComponent()); //将Mesh组件绑定在根组件下面//指定网格资源static ConstructorHelpers::FClassFinder<UStaticMesh> MeshComponentAsset(TEXT("StaticMesh'/Game/StarterContent/Shapes/Shape_Sphere.Shape_Sphere'"));if (MeshComponentAsset.Succeeded()) //资源是否找到{//MeshComponent->SetStaticMesh(MeshComponentAsset.Object);MeshComponent->SetRelativeLocation(FVector(0.f,0,-50));}SprintArmComp = CreateDefaultSubobject<USpringArmComponent>(TEXT("SprintArmComp")); //创建一个弹簧臂组件SprintArmComp->SetupAttachment(RootComponent);SprintArmComp->TargetArmLength = 400; //设置弹簧臂的长度为400SprintArmComp->SetRelativeRotation(FRotator(-45.f, 0, 0)); //设置弹簧臂的相对位置SprintArmComp->bEnableCameraLag = true; //让弹簧臂变得有韧性SprintArmComp->CameraLagSpeed = 3;Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera")); //创建一个摄像机组件Camera->SetupAttachment(SprintArmComp, USpringArmComponent::SocketName);
打开BP_MyPawn,如果位置有偏差,可以调节一下:
运行效果,可以看到移动停止后,镜头有一个惯性效果: