Найти в Дзене
Gamefiksa

Смена дня и ночи unreal engine

Реализация динамической смены дня и ночи в Unreal Engine — это важный аспект создания реалистичного и захватывающего игрового мира. Вот подробное руководство о том, как это сделать, как в Blueprint, так и в C++:

I. Основные компоненты:

Directional Light: Основной источник света, представляющий солнце или луну. Sky Light: Создает рассеянное освещение и отражения неба. Sky Sphere (или Sky Dome): Отображает небо и облака. Post Process Volume: Используется для настройки цветовой гаммы, контрастности и других эффектов постобработки.

II. Blueprint Implementation:

Create Blueprint Actor:

Create a new Blueprint Class, inheriting from Actor (e. g., “DayNightCycle”).

Add Components:

Add a Directional Light Component. Add a Sky Light Component. Add a Sky Sphere (Static Mesh Component). Можно использовать дефолтный SkySphere из стартового контента. Add a Post Process Volume.

Rotation Logic:

In the Event Graph, add an Event Tick. Create a variable called “TimeOfDay” (float). Add a float variable called “RotationSpeed” (например, 10.0). Connect the Event Tick to a “+ (Float)” node and add “RotationSpeed * Delta Seconds” to “TimeOfDay”. Set “TimeOfDay” to the result of the addition. Add a “Make Rotator” node. Set the “Pitch” value to the TimeOfDay * 360 Connect the “Make Rotator” node to a “Set World Rotation” node. Target = Directional Light Component.

Blueprint Graph Example:

(Event Tick) —> (+) —> (Set TimeOfDay)

^ |

| (RotationSpeed * Delta Seconds)

|

————-

(TimeOfDay) —> (* 360) —> (Make Rotator) —> (Set World Rotation) — (Target = Directional Light Component)

Sky Light Update:

Add a “Set Actor Tick Enabled” node and connect it with the “Event Begin Play” Set the Sky Light’s “Source Type” to “Specified Cubemap”. Add a “Set Cubemap” node and connect it with “Set Actor Tick Enabled”. Make a new Cubemap.

Post Process Volume Settings:

In the details panel, make sure that “Unbound” is checked. Setup appropriate values to auto exposure, bloom and white balance.

Sunrise/Sunset:

Чтобы имитировать рассвет и закат, настройте кривые изменения цвета и интенсивности света в зависимости от времени суток. В Blueprint используйте ноды “Lerp” для плавного перехода между разными значениями параметров освещения.

Настройка Sky Sphere (необязательно): * Чтобы улучшить визуальный эффект, можно настроить материал Sky Sphere для изменения цвета неба и облаков в зависимости от времени суток. * Используйте “Material Parameter Collection” для передачи значений времени суток в материал Sky Sphere.

III. C++ Implementation:

Create Actor Class:

Create a new C++ Class, inheriting from Actor (e. g., “ADayNightCycle”).

Declare Components:

In the header file (.h), declare the necessary components:

#pragma once

#include "CoreMinimal. h"

#include "GameFramework/Actor. h"

#include "Components/DirectionalLightComponent. h"

#include "Components/SkyLightComponent. h"

#include "Components/StaticMeshComponent. h"

#include "Components/PostProcessComponent. h"

#include "DayNightCycle. generated. h"

UCLASS()

Class MYPROJECT_API ADayNightCycle : public AActor

{

GENERATED_BODY()

Public:

ADayNightCycle();

Protected:

UPROPERTY(VisibleAnywhere, Category = "Components")

UDirectionalLightComponent* DirectionalLightComponent;

UPROPERTY(VisibleAnywhere, Category = "Components")

USkyLightComponent* SkyLightComponent;

UPROPERTY(VisibleAnywhere, Category = "Components")

UStaticMeshComponent* SkySphereComponent;

UPROPERTY(VisibleAnywhere, Category = "Components")

UPostProcessComponent* PostProcessComponent;

UPROPERTY(EditAnywhere, Category = "Settings")

float RotationSpeed;

float TimeOfDay;

Public:

virtual void Tick(float DeltaTime) override;

};

Implement Constructor:

In the source file (.cpp), implement the constructor:

#include "DayNightCycle. h"

#include "Components/DirectionalLightComponent. h"

#include "Components/SkyLightComponent. h"

#include "Components/StaticMeshComponent. h"

#include "Components/PostProcessComponent. h"

ADayNightCycle::ADayNightCycle()

{

PrimaryActorTick. bCanEverTick = true;

DirectionalLightComponent = CreateDefaultSubobject (TEXT("DirectionalLight"));

RootComponent = DirectionalLightComponent;

SkyLightComponent = CreateDefaultSubobject (TEXT("SkyLight"));

SkyLightComponent->SetupAttachment(RootComponent);

SkySphereComponent = CreateDefaultSubobject (TEXT("SkySphere"));

SkySphereComponent->SetupAttachment(RootComponent);

PostProcessComponent = CreateDefaultSubobject (TEXT("PostProcess"));

PostProcessComponent->SetupAttachment(RootComponent);

RotationSpeed = 10.0f;

TimeOfDay = 0.0f;

}

Implement Tick Function:

Implement the Tick function in the source file (.cpp):

#include "DayNightCycle. h"

Void ADayNightCycle::Tick(float DeltaTime)

{

Super::Tick(DeltaTime);

TimeOfDay += RotationSpeed * DeltaTime;

FRotator NewRotation = FRotator(TimeOfDay * 360, 0.0f, 0.0f);

DirectionalLightComponent->SetWorldRotation(NewRotation);

SkyLightComponent->ProcessSkyLightChange();

}

Add Actor to the Level:

Drag the DayNightCycle Actor from the Content Browser to your level.

IV. Дополнительные возможности:

Color Grading: Use a Post Process Volume to change colors in dependence of the TimeOfDay variable. Cloud Effects: Add volumetric clouds to improve the visual effect. Weather: Combine the Day/Night Cycle with weather effects (rain, snow, fog).

V. Оптимизация:

Avoid heavy calculations every frame. Use timers to update variables less frequently.

VI. Распространенные ошибки и их решения:

Directional Light не вращается: Проверьте, включен ли Tick для актера, и правильно ли настроены параметры вращения. Небо слишком яркое или темное: Настройте параметры Sky Light и Post Process Volume. Низкая производительность: Оптимизируйте код и ресурсы, уменьшите количество вычислений каждый кадр. Некорректное отображение облаков: Убедитесь, что материал облаков настроен правильно и поддерживает динамическое изменение цвета. Резкие переходы между днем и ночью: Используйте Lerp для плавного перехода между разными значениями параметров освещения.

Следуя этим инструкциям, вы сможете создать реалистичную и захватывающую смену дня и ночи в своем проекте Unreal Engine.

  📷
📷