首页 > 解决方案 > UV映射如何与Godot中的surfacetool一起使用?

问题描述

我正在用 Godot 编写地形生成器。我使用 SurfaceTool 和三角形条生成网格。几何体工作正常——但 UV 映射不能,因为每个三角形重复纹理而不是覆盖纹理一次的完整网格: 没有归一化

将 UV 坐标归一化以适应 0,0 - 1,1 维度应该可行,但不行,因为它使只有一对三角形具有完整的纹理,其余的为空白: 归一化/将 uv 坐标除以地形宽度和深度后

extends MeshInstance

export var terrain_width = 16
export var terrain_depth = 16
export var terrain_height = 1
export var terrain_scale = 1

#Noise Generation
var terrain_noise = OpenSimplexNoise.new()

var terrain_heightmap = ImageTexture.new()
var terrain_texture = Texture.new()
var terrain_material = SpatialMaterial.new()
var terrain_mesh = Mesh.new()

var surfacetool = SurfaceTool.new()

func _ready():
    generate_heightmap()
    generate_mesh()

func generate_heightmap():
    #Setup the noise
    terrain_noise.seed = randi()
    terrain_noise.octaves = 4
    terrain_noise.period = 20.0
    terrain_noise.persistence = 0.8

    #Make the texture
    terrain_heightmap.create_from_image(terrain_noise.get_image(terrain_width+1, terrain_depth+1))
    terrain_texture = terrain_heightmap

func generate_mesh():
    #Set the material texture to the heightmap
    terrain_material.albedo_texture = terrain_texture

    # This is where the uv-mapping occurs, via the add_uv function
    for z in range(0,terrain_depth):
        surfacetool.begin(Mesh.PRIMITIVE_TRIANGLE_STRIP)
        for x in range(0,terrain_width):

            surfacetool.add_uv(Vector2((terrain_width-x)/terrain_width,z/terrain_depth))
            surfacetool.add_vertex(Vector3((terrain_width-x)*terrain_scale, terrain_noise.get_noise_2d(x,z)*terrain_height*terrain_scale, z*terrain_scale))
            surfacetool.add_uv(Vector2((terrain_width-x)/terrain_width,(z+1)/terrain_depth))
            surfacetool.add_vertex(Vector3((terrain_width-x)*terrain_scale, terrain_noise.get_noise_2d(x,z+1)*terrain_height*terrain_scale, (z+1)*terrain_scale))

        surfacetool.generate_normals()
        surfacetool.index()

        surfacetool.commit(terrain_mesh)

    #Set the texture and mesh on the MeshInstance
    self.material_override = terrain_material
    self.set_mesh(terrain_mesh)
    self.set_surface_material(0, terrain_texture)

我希望每个三角形只覆盖纹理中的相应坐标。似乎每个三角形都被视为一个单独的表面。

标签: terrainproceduralgodot

解决方案


那里有很多整数除法。有很多方法可以解决这个问题。这是一个快速的:只需在导出变量的默认值之后添加 .0 :

export var terrain_width  = 16.0
export var terrain_depth  = 16.0
export var terrain_height = 1.0
export var terrain_scale  = 1.0

这是一种更明确的方式:

export(float) var terrain_width  = 16
export(float) var terrain_depth  = 16
export(float) var terrain_height = 1
export(float) var terrain_scale  = 1

假设您没有任何其他错误,这应该可以解决问题。


推荐阅读