使用C++编写一个可以在Unreal Engine中使用的类它具有以下功能:1、有两个浮点数输入接口分别是坐标x和坐标y可以根据输入的值定义一个二维区域2、根据定义的二维区域生成与整数坐标值对应的点3、为生成的点添加随机的高度值范围是0~2554、根据调整后的点生成mesh
#include "MyClass.h" #include "RuntimeMeshComponent.h"
// Sets default values AMyClass::AMyClass() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = false;
// Create the Runtime Mesh Component
MeshComponent = CreateDefaultSubobject<URuntimeMeshComponent>(TEXT("RuntimeMesh"));
}
// Called when the game starts or when spawned void AMyClass::BeginPlay() { Super::BeginPlay();
// Generate the mesh
GenerateMesh();
}
// Generate the mesh void AMyClass::GenerateMesh() { // Define the 2D region based on X and Y inputs FVector2D RegionSize = FVector2D(XInput, YInput);
// Calculate the number of vertices needed based on the region size
int32 NumVertices = RegionSize.X * RegionSize.Y;
// Create an array to hold the vertices
TArray<FVector> Vertices;
Vertices.SetNum(NumVertices);
// Loop through each vertex and calculate its position
for (int32 Y = 0; Y < RegionSize.Y; Y++)
{
for (int32 X = 0; X < RegionSize.X; X++)
{
// Calculate the position of the vertex
FVector VertexPosition = FVector(X, Y, 0);
// Add a random height value to the vertex
VertexPosition.Z = FMath::RandRange(0, 255);
// Add the vertex to the array
Vertices[Y * RegionSize.X + X] = VertexPosition;
}
}
// Create an array to hold the triangles
TArray<int32> Triangles;
Triangles.SetNum((RegionSize.X - 1) * (RegionSize.Y - 1) * 6);
// Loop through each quad and create two triangles
for (int32 Y = 0; Y < RegionSize.Y - 1; Y++)
{
for (int32 X = 0; X < RegionSize.X - 1; X++)
{
// Calculate the indices of the four vertices that make up the quad
int32 TopLeftIndex = Y * RegionSize.X + X;
int32 TopRightIndex = Y * RegionSize.X + X + 1;
int32 BottomLeftIndex = (Y + 1) * RegionSize.X + X;
int32 BottomRightIndex = (Y + 1) * RegionSize.X + X + 1;
// Add the two triangles that make up the quad
Triangles.Add(TopLeftIndex);
Triangles.Add(BottomLeftIndex);
Triangles.Add(TopRightIndex);
Triangles.Add(TopRightIndex);
Triangles.Add(BottomLeftIndex);
Triangles.Add(BottomRightIndex);
}
}
// Create the mesh section
MeshComponent->CreateMeshSection(0, Vertices, Triangles, TArray<FVector>(), TArray<FVector2D>(), TArray<FColor>(), TArray<FProcMeshTangent>(), true);
}
原文地址: https://www.cveoy.top/t/topic/bFP3 著作权归作者所有。请勿转载和采集!