1.1添加头文件(.h)
#include "GameFramework/SpringArmComponent.h"//弹簧臂组件
#include "Camera/CameraComponent.h"//摄像机组件
1.2创建变量(.h)
//创建场景组件
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = MySceneComponent)
USceneComponent* MyRoot;
//创建弹簧臂组件
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = MySceneComponent)
USpringArmComponent* MySpringArm;
//创建摄像机组件
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = MySceneComponent)
UCameraComponent* MyCamera;
1.3在构造函数里初始化组件
//初始化组件
MyRoot = CreateDefaultSubobject<USceneComponent>(TEXT("MyRootComponent"));
MySpringArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("MySpringArmComponent"));
MyCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("MyCameraComponent"));
RootComponent = MyRoot;//设置为根组件
MySpringArm->SetupAttachment(MyRoot);//将弹簧臂组件设置为MyRoot的子组件
MyCamera->SetupAttachment(MySpringArm);//将摄像机组件设置为MySpringArm的子组件
MySpringArm->bDoCollisionTest = false;//摄像机碰撞设置为false
1.4在BeginPlay里设置
//设置位置、旋转和缩放
FVector MyLocation = FVector(0, 0, 0);
FRotator MyRotation = FRotator(-50, 0, 0);
FVector MyScale = FVector(1, 1, 1);
SetActorLocation(MyLocation);
SetActorRotation(MyRotation);
SetActorScale3D(MyScale);
2.1在PlayerController.h重写
//重写输入绑定
virtual void SetupInputComponent();
//鼠标滚轮上滚
void WheelUpFunction();
//鼠标滚轮下滚
void WheelDownFunction();
2.2在PlayerController.cpp按键绑定
//绑定按键
void AMyPlayerController::SetupInputComponent(){
Super::SetupInputComponent();
InputComponent->BindAction("WheelUp", IE_Pressed, this, &AMyPlayerController::WheelUpFunction);
InputComponent->BindAction("WheelDown", IE_Pressed, this, &AMyPlayerController::WheelDownFunction);
}
void AMyPlayerController::WheelUpFunction(){
if (GetPawn()) {
AMyPawn* MyCameraPawn = Cast<AMyPawn>(GetPawn());
if (MyCameraPawn) {
MyCameraPawn->Zoom(1, 10);
}
}
}
void AMyPlayerController::WheelDownFunction(){
if (GetPawn()) {
AMyPawn* MyCameraPawn = Cast<AMyPawn>(GetPawn());
if (MyCameraPawn) {
MyCameraPawn->Zoom(0, 10);
}
}
}
2.3添加操作映射
2.4Pawn.h
//鼠标滑轮移动镜头缩放
void Zoom(bool Direction, float ZoomSpeed);
2.5Pawn.cpp
void AMyPawn::Zoom(bool Direction, float ZoomSpeed){
if (Direction) {
if (MySpringArm->TargetArmLength >= 300 && MySpringArm->TargetArmLength < 5000) {
MySpringArm->TargetArmLength += (ZoomSpeed * 2);
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("SpringArmLength is %f"), MySpringArm->TargetArmLength));
}
}
else {
if (MySpringArm->TargetArmLength > 300 && MySpringArm->TargetArmLength <= 5000) {
MySpringArm->TargetArmLength -= (ZoomSpeed * 2);
GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("SpringArmLength is %f"), MySpringArm->TargetArmLength));
}
}
}