头文件代码:

#pragma once

#include "GameFramework/Actor.h" #include "MyActor.generated.h"

UCLASS() class MYPROJECT_API AMyActor : public AActor { GENERATED_BODY()

public: // Sets default values for this actor's properties AMyActor();

protected: // Called when the game starts or when spawned virtual void BeginPlay() override;

public: // Called every frame virtual void Tick(float DeltaTime) override;

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyActor")
float XCoordinate;

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyActor")
float YCoordinate;

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyActor")
int32 GridSize;

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyActor")
UStaticMesh* Mesh;

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "MyActor")
UMaterialInterface* Material;

UFUNCTION(BlueprintCallable, Category = "MyActor")
void GenerateMesh();

private: TArray Points;

TArray<FVector> Vertices;

TArray<int32> Triangles;

TArray<FVector2D> UVs;

TArray<FVector> Normals;

void GeneratePoints();

void GenerateVertices();

void GenerateTriangles();

void GenerateUVs();

void GenerateNormals();

};

实现代码:

#include "MyActor.h" #include "Components/StaticMeshComponent.h" #include "Materials/MaterialInstanceDynamic.h" #include "Math/UnrealMathUtility.h"

// Sets default values AMyActor::AMyActor() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true;

// Create the static mesh component
UStaticMeshComponent* MeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
MeshComponent->SetupAttachment(RootComponent);

// Set default values for the properties
XCoordinate = 0;
YCoordinate = 0;
GridSize = 10;
Mesh = nullptr;
Material = nullptr;

}

// Called when the game starts or when spawned void AMyActor::BeginPlay() { Super::BeginPlay(); }

// Called every frame void AMyActor::Tick(float DeltaTime) { Super::Tick(DeltaTime); }

void AMyActor::GenerateMesh() { GeneratePoints(); GenerateVertices(); GenerateTriangles(); GenerateUVs(); GenerateNormals();

// Create the static mesh
UStaticMesh* StaticMesh = NewObject<UStaticMesh>(StaticClass(), FName(TEXT("MyStaticMesh")));
StaticMesh->InitResources();

// Create the vertex buffer
FStaticMeshVertexBuffers VertexBuffers;
VertexBuffers.InitFromSingleVertexStream(
    sizeof(FVector) * 4, // vertex size
    Points.Num(), // number of vertices
    &Vertices[0], // vertex data
    sizeof(FVector) * 2, // texture coordinate size
    &UVs[0], // texture coordinate data
    sizeof(FVector), // normal size
    &Normals[0], // normal data
    nullptr, // tangent data
    nullptr // color data
);

// Create the index buffer
FStaticMeshIndexBuffer32 IndexBuffer;
IndexBuffer.AllocateDefault(Vertices.Num());
FMemory::Memcpy(IndexBuffer.GetData(), &Triangles[0], sizeof(int32) * Triangles.Num());

// Create the static mesh section
FStaticMeshSection Section;
Section.MaterialIndex = 0;
Section.bEnableCollision = true;
Section.bCastShadow = true;
Section.bForceOpaque = true;
Section.bReverseCulling = false;
Section.bVisibleInRayTracing = true;
Section.bRenderCustomDepth = false;
Section.bEnableShadowCasting = true;
Section.bUseMaximumStreamingTexelRatio = false;
Section.bUseHighPrecisionTangents = false;
Section.bUseFullPrecisionUVs = false;
Section.bUseHighPrecisionUVs = false;
Section.bUseLandscapeForCullingInvisibleHLODVertices = false;
Section.bEnableMeshOcclusion = false;
Section.bTreatAsBackgroundForOcclusion = false;
Section.bAllowCPUAccess = false;
Section.bRequiresAdjacencyInformation = false;
Section.bSupportFaceRemap = true;
Section.bHasBeenSimplified = false;
Section.bRecomputeTangents = false;
Section.bRecomputeNormals = false;
Section.bUseMaxDeviation = false;
Section.bNeedsPositionOnlyVertexBuffer = false;
Section.bAllowCullDistanceVolume = true;
Section.bHasPerFaceMaterials = false;
Section.bHasDiscreteCollisionMeshes = false;
Section.bCastDynamicShadow = true;
Section.bCastStaticShadow = true;
Section.bAffectDynamicIndirectLighting = true;
Section.bAffectDistanceFieldLighting = true;
Section.bCastFarShadow = true;
Section.bIsTwoSidedMaterial = false;
Section.bForceNoLightmapGeneration = false;
Section.bUseCustomPrimitiveData = false;
Section.bFullyCompressedPositionOnly = false;
Section.bIsBuiltAtRuntime = false;
Section.bSupportUniformlyDistributedSampling = false;
Section.bSupportStationaryLightOverlap = false;
Section.bUseLegacyBiTangents = false;
Section.bUseHighPrecisionTangentBasis = false;
Section.bUseFullPrecisionUVsAndTangentBasis = false;
Section.bAllowShadowMapBias = false;
Section.bUsePlanarForwardReflections = false;
Section.bUseCustomizedUVs = false;
Section.bEnableFadingIn = false;
Section.bEnableFadingOut = false;
Section.bUseDynamicData = false;
Section.bUseDynamicMaterialInstance = false;
Section.VertexBuffer = &VertexBuffers;
Section.IndexBuffer = &IndexBuffer;

// Create the static mesh build settings
FMeshBuildSettings BuildSettings;
BuildSettings.BuildScale3D = FVector(1, 1, 1);
BuildSettings.DistanceFieldResolutionScale = 1;
BuildSettings.bGenerateDistanceFieldAsIfTwoSided = false;
BuildSettings.bSupportFaceRemap = true;
BuildSettings.bUseFullPrecisionUVs = false;
BuildSettings.bUseHighPrecisionTangents = false;
BuildSettings.bRecomputeNormals = false;
BuildSettings.bRecomputeTangents = false;
BuildSettings.bRemoveDegenerates = true;
BuildSettings.bUseMikkTSpace = false;
BuildSettings.bUseHighPrecisionUVs = false;
BuildSettings.bBuildAdjacencyBuffer = false;
BuildSettings.bBuildReversedIndexBuffer = false;
BuildSettings.bUseFullPrecisionUVsAndTangentBasis = false;
BuildSettings.bUseLegacyBiTangents = false;
BuildSettings.bUsePlanarForwardReflections = false;
BuildSettings.bUseCustomizedUVs = false;
BuildSettings.bUseDynamicData = false;
BuildSettings.bUseDynamicMaterialInstance = false;

// Build the static mesh
StaticMesh->BuildFromStaticMeshSection(0, Section, BuildSettings);

// Set the static mesh
UStaticMeshComponent* MeshComponent = Cast<UStaticMeshComponent>(GetComponentByClass(UStaticMeshComponent::StaticClass()));
MeshComponent->SetStaticMesh(StaticMesh);

// Set the material
if(Material != nullptr)
{
    UMaterialInstanceDynamic* DynamicMaterial = UMaterialInstanceDynamic::Create(Material, this);
    MeshComponent->SetMaterial(0, DynamicMaterial);
}

}

void AMyActor::GeneratePoints() { Points.Empty();

for (int32 i = 0; i < GridSize; i++)
{
    for (int32 j = 0; j < GridSize; j++)
    {
        float X = i * XCoordinate;
        float Y = j * YCoordinate;
        float Z = FMath::RandRange(0, 255);

        Points.Add(FVector(X, Y, Z));
    }
}

}

void AMyActor::GenerateVertices() { Vertices.Empty();

for (int32 i = 0; i < Points.Num(); i++)
{
    Vertices.Add(Points[i]);
}

}

void AMyActor::GenerateTriangles() { Triangles.Empty();

for (int32 i = 0; i < GridSize - 1; i++)
{
    for (int32 j = 0; j < GridSize - 1; j++)
    {
        int32 Index1 = i * GridSize + j;
        int32 Index2 = i * GridSize + j + 1;
        int32 Index3 = (i + 1) * GridSize + j;
        int32 Index4 = (i + 1) * GridSize + j + 1;

        Triangles.Add(Index1);
        Triangles.Add(Index2);
        Triangles.Add(Index3);

        Triangles.Add(Index2);
        Triangles.Add(Index4);
        Triangles.Add(Index3);
    }
}

}

void AMyActor::GenerateUVs() { UVs.Empty();

for (int32 i = 0; i < GridSize; i++)
{
    for (int32 j = 0; j < GridSize; j++)
    {
        float U = i / (float)(GridSize - 1);
        float V = j / (float)(GridSize - 1);

        UVs.Add(FVector2D(U, V));
    }
}

}

void AMyActor::GenerateNormals() { Normals.Empty();

for (int32 i = 0; i < Points.Num(); i++)
{
    Normals.Add(FVector(0, 0, 1));
}

}

使用C++编写一个可以在Unreal Engine中使用的actor类它具有以下功能:1、有两个浮点数输入接口分别是坐标x和坐标y可以根据输入的值定义一个二维区域2、根据定义的二维区域生成与整数坐标值对应的点3、为生成的点添加随机的高度值范围是0~2554、根据调整后的点生成mesh5、要提供完整代码包括cpp和头文件代码

原文地址: https://www.cveoy.top/t/topic/bGDg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录