Конечно, я помогу написать код для игры на Unreal Engine 5, соответствующий вашим требованиям. Следующий код создаст игрока с камерой от первого лица, который может двигаться, а также имеет симуляцию покачивания головы при движении и ускорении:
//Заголовочные файлы
#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "GameFramework/FloatingPawnMovement.h"
#include "FirstPersonCamera.generated.h"
// Объявление функции ускорения с заданным коэффициентом ускорения.
UFUNCTION(BlueprintCallable, Category = Pawn)
void SetSprintSpeed(float SprintSpeedMultiplier);
// Объявление класса пешки (Pawn) для камеры от первого лица
UCLASS()
class MYPROJECT_API AFirstPersonCamera : public APawn
{
GENERATED_BODY()
public:
//Конструктор пешки (Pawn)
AFirstPersonCamera();
// Вызывается при запуске игры
virtual void BeginPlay() override;
// Вызывается при каждом бновлении игрового кадра
virtual void Tick(float DeltaTime) override;
// Инициализация отслеживания ускорения и скрытие мыши
virtual void SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) override;
// Установка скорости передвижения пешки
void SetMovementSpeed(float NewMovementSpeed);
// Обновление вектора ускорения в зависимости от нажатых клавиш
void UpdateInput(float DeltaTime);
// Проецирует вектор в плоскость, перпендикулярную вектору наклона
FVector ProjectVectorOntoPlane(FVector InVector, FVector InNormal);
protected:
// Компонент передвижения для пешки
UPROPERTY()
class UFloatingPawnMovement* MovementComponent;
// Ускорение передвижения пешки
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Pawn")
float SprintSpeedMultiplier;
// Чувствительность качания головы пешки
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Pawn")
float HeadBobFrequency;
// Интервал симуляции качания головы пешки
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Pawn")
float HeadBobInterval;
// Максимальное ускорение для активации симуляции качания головы
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Pawn")
float HeadBobThreshold;
// Запоминает координату последнего кадра для расчета сдвига камеры
FVector LastLocation;
// Текущее ускорение пешки
float Acceleration;
// Время последнего изменения ускорения
float LastUpdate;
};
Затем можно создать .cpp файл для этого класса:
#include "FirstPersonCamera.h"
#include "Camera/CameraComponent.h"
#include "Components/InputComponent.h"
AFirstPersonCamera::AFirstPersonCamera()
{
// Использовать контроллер пешки
AutoPossessPlayer = EAutoReceiveInput::Player0;
PrimaryActorTick.bCanEverTick = true;
// Создание компонента привязки игрока
UFloatingPawnMovement* MovementComponent = CreateDefaultSubobject<UFloatingPawnMovement>(TEXT("Movement"));
SetRootComponent(MovementComponent);
this->MovementComponent = MovementComponent;
// Создание камеры
UCameraComponent* CameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("FirstPersonCamera"));
CameraComponent->SetupAttachment(RootComponent);
CameraComponent->PostProcessSettings.AddBlendable(TSubclassOf<UMaterialInterface>(UMaterial::StaticClass()));
CameraComponent->PostProcessSettings.bOverride_FilmGrainIntensity = true;
CameraComponent->PostProcessSettings.FilmGrainIntensity = 0.f;
CameraComponent->PostProcessSettings.bOverride_VignetteIntensity = true;
CameraComponent->PostProcessSettings.VignetteIntensity = 0.f;
CameraComponent->PostProcessSettings.bOverride_FilmGrainJitter = true;
CameraComponent->PostProcessSettings.FilmGrainJitter = FVector2D(1.f, 1.f);
CameraComponent->PostProcessSettings.bOverride_LensFlareIntensity = true;
CameraComponent->PostProcessSettings.LensFlareIntensity = 0.f;
CameraComponent->PostProcessSettings.bOverride_SceneFringeIntensity = true;
CameraComponent->PostProcessSettings.SceneFringeIntensity = 0.f;
// Устанавливаем рабочее расстояние
CameraComponent->SetRelativeLocation(FVector(0.f, 0.f, 0.f));
CameraComponent->bUsePawnControlRotation = true;
// Настройки управления
InputComponent->BindAxis("Forward", this, &AFirstPersonCamera::AddMovementInput);
InputComponent->BindAxis("Strafe", this, &AFirstPersonCamera::AddMovementInput);
InputComponent->BindAxis("Turn", this, &AFirstPersonCamera::AddControllerYawInput);
InputComponent->BindAxis("LookUp", this, &AFirstPersonCamera::AddControllerPitchInput);
InputComponent->BindAction("Sprint", IE_Pressed, this, &AFirstPersonCamera::SetSprintSpeed, 2.f);
InputComponent->BindAction("Sprint", IE_Released, this, &AFirstPersonCamera::SetSprintSpeed, 1.f);
// Установка параметров
BobbingTimer = 0.f;
BobbingRatio = 0.f;
MovementSpeed = 300.f;
SprintSpeedMultiplier = 2.f;
HeadBobFrequency = 2.f;
HeadBobInterval = 2.f;
HeadBobThreshold = 1.5f;
MovementComponent->MaxSpeed = MovementSpeed;
}
void AFirstPersonCamera::BeginPlay()
{
Super::BeginPlay();
LastLocation = GetActorLocation();
}
void AFirstPersonCamera::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
// Рассчитывем новое ускорение
UpdateInput(DeltaTime);
// Рассчитываем смещение камеры с помощью качания головы в зависимости от ускорения
FVector CurrentLocation = GetActorLocation();
FVector ViewDirection = FRotationMatrix(GetControlRotation()).GetScaledAxis(EAxis::X);
float DistanceTraveled = FVector::DotProduct(CurrentLocation - LastLocation, ViewDirection);
if (DistanceTraveled > HeadBobThreshold)
{
float BobbingFrequency = HeadBobFrequency * (1.f + Acceleration * SprintSpeedMultiplier * 0.1f);
float BobbingAmount = FMath::Abs(DistanceTraveled) * 0.5f * FMath::Sin(BobbingTimer * BobbingFrequency) * FMath::Pow(MovementSpeed, 0.2f);
FVector BobbingDirection = ProjectVectorOntoPlane(ViewDirection, FVector::UpVector);
AddActorWorldOffset(BobbingDirection * BobbingAmount);
BobbingTimer += DeltaTime;
if (BobbingTimer > HeadBobInterval)
{
BobbingTimer = 0.f;
}
}
LastLocation = CurrentLocation;
}
void AFirstPersonCamera::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
}
void AFirstPersonCamera::SetMovementSpeed(float NewMovementSpeed)
{
MovementSpeed = NewMovementSpeed;
MovementComponent->MaxSpeed = MovementSpeed;
}
void AFirstPersonCamera::UpdateInput(float DeltaTime)
{
// Прибавляем скорость вверх к текущему вектору
float ForwardValue = GetInputAxisValue("Forward");
float StrafeValue = GetInputAxisValue("Strafe");
FVector ForwardDirection = FVector(ForwardValue, StrafeValue, 0.f).GetClampedToMaxSize(1.f);
float TimeSinceLastUpdate = UGameplayStatics::GetTimeSeconds(this) - LastUpdate;
float MaxLinearSpeed = MovementComponent->GetMaxSpeed();
float CurrentAcceleration = Acceleration;
float TargetAcceleration = ForwardDirection.Size() * MaxLinearSpeed * 4.f;
Acceleration = FMath::FInterpTo(CurrentAcceleration, TargetAcceleration, DeltaTime, MaxLinearSpeed);
LastUpdate = UGameplayStatics::GetTimeSeconds(this);
}
void AFirstPersonCamera::SetSprintSpeed(float SprintSpeedMultiplier)
{
this->SprintSpeedMultiplier = SprintSpeedMultiplier;
}
FVector AFirstPersonCamera::ProjectVectorOntoPlane(FVector InVector, FVector InNormal)
{
FVector Result = InVector - FVector::DotProduct(InVector, InNormal) * InNormal;
return Result;
}
Теперь вы можете использовать этот класс в своей игре, чтобы создать игрока с камерой от первого лица, который может двигаться и имеет симуляцию покачивания головы при движении и ускорении.