• 1、通过MeshDescription在运行时构建StaticMesh并设置碰撞、修改材质


    1、MyActor.h

    //MyActor.h
    
    #pragma once
    
    #include "CoreMinimal.h"
    #include "GameFramework/Actor.h"
    #include "MyActor.generated.h"
    
    UCLASS()
    class CONTROLLER_API AMyActor : public AActor
    {
    	GENERATED_BODY()
    	
    public:	
    	// Sets default values for this actor's properties
    	AMyActor();
    	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Polygon")
    	TObjectPtr PolygonComponent;
    	FPolygonGroupID GroupId;
    	UPROPERTY(EditAnywhere, Category = "Polygon")
    	TArray Coodinates;
    	TObjectPtr Polygon;
    	UPROPERTY(EditAnywhere, Category = "Polygon")
    	UMaterialInterface* Material;
    protected:
    	// Called when the game starts or when spawned
    	virtual void BeginPlay() override;
    	virtual void OnConstruction(const FTransform& Transform) override;
    public:	
    	// Called every frame
    	virtual void Tick(float DeltaTime) override;
    	TObjectPtr BuildPolygon(TArray InPositions);
    
    };
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    2、MyActor.cpp

    //MyActor.cpp
    
    
    #include "MyActor.h"
    
    #include "StaticMeshAttributes.h"
    
    #include "CompGeom/PolygonTriangulation.h"
    #include 
    #include 
    
    // 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;
    	PolygonComponent = CreateDefaultSubobject(TEXT("PolygonComponent"), false);
    	SetRootComponent(PolygonComponent);
    }
    
    // Called when the game starts or when spawned
    void AMyActor::BeginPlay()
    {
    	Super::BeginPlay();
    	if(Coodinates.Num())
    	{
    		Material = LoadObject(this, TEXT("/Engine/BasicShapes/BasicShapeMaterial.BasicShapeMaterial"));
    		PolygonComponent->SetStaticMesh(BuildPolygon(Coodinates));
    		PolygonComponent->SetMaterial(0,Material);
    		//PolygonComponent->SetForcedLodModel(1);
    
    	}
    }
    
    void AMyActor::OnConstruction(const FTransform& Transform)
    {
    	if (!IsTemplate()) {
    		if (Coodinates.Num())
    		{
    			//加载虚幻引擎自带的材质
    			Material = LoadObject(this, TEXT("/Engine/BasicShapes/BasicShapeMaterial.BasicShapeMaterial"));
    			//将生成的StaticMesh挂载到StaticMeshComponent上
    			BuildPolygon(Coodinates);
    			PolygonComponent->SetStaticMesh(Polygon);
    			//在StaticMeshComponent上设置材质,坑1:StaticMesh也有一个SetMaterial方法,但是它是仅在编辑器状态下可用的,调用了这个方法打包时会报错,打包就失败了,而StaticMeshComponent的SetMaterial方法没有这个问题,且材质能够成功应用到StaticMesh上
    			PolygonComponent->SetMaterial(0, Material);
    		}
    	}
    }
    
    // Called every frame
    void AMyActor::Tick(float DeltaTime)
    {
    	Super::Tick(DeltaTime);
    
    }
    FBox2D computeMinRectangle(TArray InPositions)
    {
    	FBox2D result;
    	uint8 num = InPositions.Num();
    	if (num < 2)
    	{
    		return result;
    	}
    	const double doubleMin = std::numeric_limits::min();
    	const double doubleMax = std::numeric_limits::max();
    
    	double minX = doubleMax, minY = doubleMax, maxX = doubleMin, maxY = doubleMin;
    	for (uint8 i = 0; i < num; ++i)
    	{
    		FVector2D currentPoint = InPositions[i];
    
    		maxX = maxX > currentPoint.X ? maxX : currentPoint.X;
    		maxY = maxY > currentPoint.Y ? maxY : currentPoint.Y;
    
    		minX = minX < currentPoint.X ? minX : currentPoint.X;
    		minY = minY < currentPoint.Y ? minY : currentPoint.Y;
    	}
    	result.Max = FVector2D(maxX, maxY);
    	result.Min = FVector2D(minX, minY);
    
    	return result;
    }
    TObjectPtr AMyActor::BuildPolygon(TArray InPositions)
    {
    	if (InPositions.Num()) {
    		TSet UniquePoints;
    
    		for (int32 i = 0; i < InPositions.Num(); ++i)
    		{
    			if (!UniquePoints.Contains(InPositions[i]))
    			{
    				UniquePoints.Add(InPositions[i]);
    			}
    		}
    		InPositions.Empty();
    		InPositions = UniquePoints.Array();
    	}
    	if (InPositions.Num() < 3) {
    		UE_LOG(LogTemp, Error, TEXT("Error:After removing duplicate points,the length of the coordinates array must be greater than or equal to 3!!"))
    			return nullptr;
    	}
    	FVector4f Color(1.0, 1.0, 1.0, 1.0);
    	Polygon = NewObject(this, FName("Polygon"));
    	//坑2:添加材质插槽,StaticMesh有个名为AddMaterial的方法,看名字像是添加材质插槽,但是实际使用上,打包后不生效,而采用“GetStaticMaterials().Add(FStaticMaterial())”这种方式可以
    	Polygon->GetStaticMaterials().Add(FStaticMaterial());
    
    	FMeshDescription meshDesc;
    	FStaticMeshAttributes attributes(meshDesc);
    	//注册默认的静态模型属性
    	attributes.Register();
    
    	//FMeshDescriptionBuilder用于设置顶点、法线、UV坐标等信息
    	FMeshDescriptionBuilder meshDescBuilder;
    	meshDescBuilder.SetMeshDescription(&meshDesc);
    	//允许使用多边形组
    	meshDescBuilder.EnablePolyGroups();
    	//设置UV坐标的级数为1
    	meshDescBuilder.SetNumUVLayers(1);
    
    	TArray vertexIDs;
    	const int count = InPositions.Num();
    	vertexIDs.SetNum(count);
    	TArray Positions2D;
    	for (int32 i = 0; i < count; ++i) {
    		FVector& position = InPositions[i];
    		vertexIDs[i] = meshDescBuilder.AppendVertex(position);
    		Positions2D.Add(FVector2D(position.X, position.Y));
    	}
    	//创建一个多边形组,每个多边形组可以单独赋予不同的材质
    	GroupId = meshDescBuilder.AppendPolygonGroup();
    
    
    	TArray polyTriangleIndices;
    	TArray PolyTriangleIndices;
    	bool bOrientAsHoleFill = true;
    	//耳切法生成多边形三角网格的顶点索引
    	PolygonTriangulation::TriangulateSimplePolygon(InPositions, polyTriangleIndices, bOrientAsHoleFill);
    	for (UE::Geometry::FIndex3i& indice : polyTriangleIndices) {
    		PolyTriangleIndices.Add(indice.A);
    		PolyTriangleIndices.Add(indice.B);
    		PolyTriangleIndices.Add(indice.C);
    
    	}
    	//用于计算纹理坐标
    	const FBox2D box = computeMinRectangle(Positions2D);
    	auto ComputeUV = [&box](FVector InPosition) {
    		FVector2D coord;
    		coord.X = (InPosition.X - box.Min.X) / 100.0;
    		coord.Y = (InPosition.Y - box.Min.Y) / 100.0;
    		return coord;
    		};
    		
    	for (int32 i = 0; i < polyTriangleIndices.Num(); ++i) {
    		//将顶点添加到meshDescBuild中并获得顶点索引
    		FVertexInstanceID index1 = meshDescBuilder.AppendInstance(vertexIDs[PolyTriangleIndices[i * 3]]);
    		//设置指定索引的顶点的uv坐标
    		meshDescBuilder.SetInstanceUV(index1, ComputeUV(meshDescBuilder.GetPosition(vertexIDs[PolyTriangleIndices[i * 3]])), 0);
    		//设置指定索引的顶点的颜色
    		meshDescBuilder.SetInstanceColor(index1, Color);
    
    		FVertexInstanceID index2 = meshDescBuilder.AppendInstance(vertexIDs[PolyTriangleIndices[i * 3 + 1]]);
    		meshDescBuilder.SetInstanceUV(index2, ComputeUV(meshDescBuilder.GetPosition(vertexIDs[PolyTriangleIndices[i * 3 + 1]])), 0);
    		meshDescBuilder.SetInstanceColor(index2, Color);
    
    		FVertexInstanceID index3 = meshDescBuilder.AppendInstance(vertexIDs[PolyTriangleIndices[i * 3 + 2]]);
    		meshDescBuilder.SetInstanceUV(index3, ComputeUV(meshDescBuilder.GetPosition(vertexIDs[PolyTriangleIndices[i * 3 + 2]])), 0);
    		meshDescBuilder.SetInstanceColor(index3, Color);
    		//设置三角形网格的顶点索引,并指定该网格属于哪个多边形组
    		meshDescBuilder.AppendTriangle(index1, index2, index3, GroupId);
    
    	}
    
    	UStaticMesh::FBuildMeshDescriptionsParams mdParams;
    	mdParams.bBuildSimpleCollision = true;//构建简单碰撞
    	mdParams.bFastBuild = true;//快速构建
    	
    	//计算三角形网格的切线和法线
    	FStaticMeshOperations::ComputeTriangleTangentsAndNormals(meshDesc);
    	
    	TArray meshDescPtrs;
    	meshDescPtrs.Emplace(&meshDesc);
    	//构建StaticMesh(构建Mesh的方法不止这一种,其中有种方法要调用InitResources,然后还要设置Lod,但是通过BuildFromMeshDescriptions方法不需要这么做,其方法内部已经封装好了)
    	Polygon->BuildFromMeshDescriptions(meshDescPtrs, mdParams);
    	
    	//坑3:如果要给StaticMeshComponent绑定鼠标的click、hover等时间的话,需要调用下面这段代码以启用复杂碰撞,因为click等事件也是基于射线检测进行判断的,但是它检测的是复杂碰撞(TraceComplex参数值为true),因此如果不调用下面这段代码,click等事件是不会生效的。注意:这里不要创建BodySetup,在前面的BuildFromMeshDescriptions方法的函数实现里面已经为StaticMesh创建了一个BodySetup,并为其赋予了一些值。
    		if (UBodySetup* bodySetup = Polygon->GetBodySetup())
    	{
    		bodySetup->DefaultInstance.SetCollisionProfileName(UCollisionProfile::BlockAll_ProfileName);
    		bodySetup->CollisionTraceFlag = CTF_UseSimpleAsComplex;
    		bodySetup->bGenerateMirroredCollision = false;
    	}
    	return Polygon;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194

    3、总结
    1)运行时修改StaticMesh的材质要调用StaticMeshComponent的SetMaterial方法而不是StaticMesh的SetMaterial方法,因为StaticMesh的SetMaterial方法仅在编辑器状态下可用,会导致你打包失败;
    2)想要在运行时修改StaticMesh的材质,首先要确保StaticMesh有材质插槽,为StaticMesh增加材质插槽的方法如上,一定不能使用StaticMesh的AddMaterial方法,运行时状态下无效;
    3)想要给StaticMesh绑定click、hover等事件,需要为其启用复杂碰撞,代码如上,但是不使用那段代码也有碰撞,只是click、hover等事件不生效。

  • 相关阅读:
    Linux日志超详细使用操作
    (学习日记)2022.7.21
    python调用接口脚本
    【数据结构】第七章 查找
    Python库——Pandas数据分析
    EditPlus 配置python 及Anaconda中的python
    【嵌入式——QT】QListWidget
    spring 事务方式和事务传播
    汇编语言与微机原理 期末复习题整理(小题)
    C++中的智能指针
  • 原文地址:https://blog.csdn.net/weixin_41364246/article/details/136563754