feat: 增加摄像机跟随

This commit is contained in:
meishibiezb
2026-03-15 18:42:17 +08:00
parent 402a0fed99
commit d86b3f53a9
3 changed files with 21 additions and 5 deletions

Binary file not shown.

View File

@@ -5,6 +5,7 @@
#include "GameFramework/SpringArmComponent.h" #include "GameFramework/SpringArmComponent.h"
#include "Camera/CameraComponent.h" #include "Camera/CameraComponent.h"
#include "InputActionValue.h"
void ACameraPawn::CameraZoom(const FInputActionValue& Value) void ACameraPawn::CameraZoom(const FInputActionValue& Value)
{ {
@@ -16,6 +17,10 @@ void ACameraPawn::CameraRotate(const FInputActionValue& Value)
void ACameraPawn::CameraMove(const FInputActionValue& Value) void ACameraPawn::CameraMove(const FInputActionValue& Value)
{ {
auto f2d = Value.Get<FVector2D>();
auto f = GetActorForwardVector();
auto r = GetActorRightVector();
SetActorLocation(GetActorLocation() + f * f2d.X * 10.0f + r * f2d.Y * 10.0f);
} }
// Sets default values // Sets default values
@@ -31,6 +36,9 @@ ACameraPawn::ACameraPawn()
SpringArmComponent->bUsePawnControlRotation = true; SpringArmComponent->bUsePawnControlRotation = true;
CameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComponent")); CameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComponent"));
CameraComponent->SetupAttachment(SpringArmComponent, USpringArmComponent::SocketName); CameraComponent->SetupAttachment(SpringArmComponent, USpringArmComponent::SocketName);
// 设置弹簧臂碰撞属性
SpringArmComponent->bDoCollisionTest = false;
} }
// Called when the game starts or when spawned // Called when the game starts or when spawned
@@ -38,10 +46,17 @@ void ACameraPawn::BeginPlay()
{ {
Super::BeginPlay(); Super::BeginPlay();
// 设置摄像头可见性 if (FollowTarget)
if (CameraComponent)
{ {
CameraComponent->SetVisibility(true); // 切换到当前摄像头
auto c = Cast<APlayerController>(FollowTarget->GetController());
if (c)
{
c->SetViewTarget(this);
}
// 附加到父物体
this->AttachToActor(FollowTarget, FAttachmentTransformRules::KeepWorldTransform);
} }
} }

View File

@@ -67,6 +67,7 @@ void AMyCharacter::BeginPlay()
{ {
FTransform SpawnTransform(GetActorRotation(), GetActorLocation()); FTransform SpawnTransform(GetActorRotation(), GetActorLocation());
temp = w->SpawnActorDeferred<ACameraPawn>(CameraActorClass, SpawnTransform); temp = w->SpawnActorDeferred<ACameraPawn>(CameraActorClass, SpawnTransform);
temp->SetActorRotation(FRotator(-60.0f, 0.0f, 0.0f));
temp->FollowTarget = this; temp->FollowTarget = this;
temp->FinishSpawning(SpawnTransform); temp->FinishSpawning(SpawnTransform);
} }