Unreal Engine C++ 类:二维区域随机高度网格生成器
Unreal Engine C++ 类:二维区域随机高度网格生成器
本 C++ 类用于在 Unreal Engine 中生成网格,它根据用户定义的二维区域生成随机高度的点,并创建相应的网格。
功能:
- 接受两个浮点数作为输入,分别代表坐标 x 和坐标 y,用来定义一个二维区域。
- 根据定义的二维区域,生成与整数坐标值对应的点。
- 为生成的点添加随机的高度值,范围是 0~255。
- 根据调整后的点生成网格。
代码:
MyMeshGenerator.h:
#pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "MyMeshGenerator.generated.h"
UCLASS()
class MYPROJECT_API UMyMeshGenerator : public UObject
{
GENERATED_BODY()
public:
UMyMeshGenerator();
UPROPERTY(EditAnywhere, BlueprintReadWrite)
float X;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
float Y;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
float MeshSize;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
float HeightScale;
UFUNCTION(BlueprintCallable)
void GenerateMesh();
private:
TArray<FVector> Vertices;
TArray<int32> Triangles;
TArray<FVector2D> UVs;
TArray<FColor> VertexColors;
};
MyMeshGenerator.cpp:
#include "MyMeshGenerator.h"
#include "KismetProceduralMeshLibrary.h"
UMyMeshGenerator::UMyMeshGenerator()
{
X = 100.0f;
Y = 100.0f;
MeshSize = 10.0f;
HeightScale = 255.0f;
}
void UMyMeshGenerator::GenerateMesh()
{
Vertices.Empty();
Triangles.Empty();
UVs.Empty();
VertexColors.Empty();
int32 NumVerticesX = FMath::FloorToInt(X / MeshSize) + 1;
int32 NumVerticesY = FMath::FloorToInt(Y / MeshSize) + 1;
for (int32 y = 0; y < NumVerticesY; y++)
{
for (int32 x = 0; x < NumVerticesX; x++)
{
float Height = FMath::RandRange(0.0f, HeightScale);
FVector Vertex = FVector(x * MeshSize, y * MeshSize, Height);
Vertices.Add(Vertex);
}
}
for (int32 y = 0; y < NumVerticesY - 1; y++)
{
for (int32 x = 0; x < NumVerticesX - 1; x++)
{
int32 CornerIndex = y * NumVerticesX + x;
Triangles.Add(CornerIndex);
Triangles.Add(CornerIndex + NumVerticesX);
Triangles.Add(CornerIndex + NumVerticesX + 1);
Triangles.Add(CornerIndex);
Triangles.Add(CornerIndex + NumVerticesX + 1);
Triangles.Add(CornerIndex + 1);
}
}
for (int32 i = 0; i < Vertices.Num(); i++)
{
UVs.Add(FVector2D(Vertices[i].X / X, Vertices[i].Y / Y));
VertexColors.Add(FColor(Vertices[i].Z, Vertices[i].Z, Vertices[i].Z));
}
UKismetProceduralMeshLibrary::CreateMeshSection(this, 0, Vertices, Triangles, TArray<FVector>(), UVs, VertexColors, TArray<FProcMeshTangent>(), false);
}
使用方法:
- 将
MyMeshGenerator.h和MyMeshGenerator.cpp文件添加到您的 Unreal Engine 项目中。 - 在您的蓝图中创建一个
UMyMeshGenerator类的实例。 - 使用蓝图中的
GenerateMesh函数生成网格。
注意:
- 此代码仅提供基本功能,您可以根据需要添加更多功能和自定义选项。
- 确保在使用此类之前,您的项目中已包含必要的 Unreal Engine 模块,例如
ProceduralMeshComponent。
相关资源:
原文地址: https://www.cveoy.top/t/topic/namP 著作权归作者所有。请勿转载和采集!