创建类
在引擎里面新建一个C++类, 命名为 TileMapGenerator, 继承 Actor
打开 TileMapGenerator.h
, 声明变量:
1 2 3 4 5 6 7 8 9 10 11 12 13
| public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Map") int32 MapWidth;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Map") int32 MapHeight;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Map") TArray<TSubclassOf<AActor>> TileClasses;
|
打开 TileMapGenerator.cpp
, 在 BeginPlay()
里面写入以下内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| void ATileMapGenerator::BeginPlay() { Super::BeginPlay();
if (TileClasses.Num() > 0) { for (int32 x = 0; x < MapWidth; ++x) { for (int32 y = 0; y < MapHeight; ++y) { FVector Location(x * 200.f, y * 200.f, 0.f); FRotator Rotation = FRotator::ZeroRotator; FActorSpawnParameters SpawnParams;
TSubclassOf<AActor> TileClass = TileClasses[FMath::RandRange(0, TileClasses.Num() - 1)];
GetWorld()->SpawnActor<AActor>(TileClass, Location, Rotation, SpawnParams); } } } }
|
使用
Ctrl + Alt + F11 编译, 创建基于 TileMapGenerator
的子蓝图,
将 创建的 Actor 拖入场景, 设置 MapWidth、 MapHeight、 TileClasses 的参数.
然后运行游戏,即可自动随机创建地形
具体的 Actor 可在 TileClasses
中配置.
可以新建任意 Actor
赋予 TileClasses
中