2

如何正确更改 Godot3 中的网格颜色?

extends MeshInstance

# class member variables go here, for example:
# var a = 2
# var b = "textvar"
var i=0
export(Color) var new_color = Color(1, 1, 1, 1)
func _ready():
    var n = self
    var mat=n.get_mesh().surface_get_material(0)
    var mat2 = SpatialMaterial.new()
    mat2.albedo_color = Color(0.8, 0.0, 0.0)
    self.get_mesh().surface_set_material(0,mat2)
    set_process(true)
    # Called every time the node is added to the scene.
    # Initialization here
func _process(delta):
    randomize()
    var mat2 = SpatialMaterial.new()
    mat2.albedo_color = Color8(255, 0, 0)
    var i = rand_range(0.0,100.0)
    if i>50.0:
        self.get_mesh().surface_set_material(0,mat2)
        i=0
    else:
        mat2.albedo_color = Color8(0, 0, 255)
        self.get_mesh().surface_set_material(0,mat2)

我尝试了这个简单的代码来改变 godot3 引擎中的网格颜色。这个想法可能有助于改变汽车的阶梯灯颜色,例如在某些游戏中。

4

2 回答 2

3

您可以使用material_overrideMeshInstance 的albedo_color属性和材质 (SpatialMaterial) 的属性,将颜色设置为您需要的任何颜色:

下面的示例将 MeshInstance 的颜色更改为橙​​色:

func _ready():
    var newMaterial = SpatialMaterial.new() #Make a new Spatial Material
    newMaterial.albedo_color = Color(0.92, 0.69, 0.13, 1.0) #Set color of new material
    $"MeshInstance".material_override = newMaterial #Assign new material to material overrride

首先,创建一个新的 SpatialMaterial 并为其命名。然后,设置该材质的颜色并将该材质设置为 MashInstance 的覆盖材质。只需将“MeshIsntance”替换为您的 MeshInstance 的名称。例如,如果此行包含在附加到 MeshInstance 本身的脚本中:

func _ready():
    var newMaterial = SpatialMaterial.new()
    newMaterial.albedo_color = Color(0.92, 0.69, 0.13, 1.0)
    self.material_override = newMaterial

如果要撤消覆盖:

self.material_override = null
于 2019-11-05T19:39:23.427 回答
1

您可以通过以下方式更改材质颜色:

extends MeshInstance

export(Color) var new_color = Color(1, 1, 1, 1)

func _ready():
    randomize()
    get_surface_material(0).albedo_color = new_color
    set_process(true)

您还可以在“GeometryInstance”下的检查器中添加材质覆盖(SpatialMaterial),并将其albedo属性设置为脚本中所需的颜色。

material_override.albedo_color = new_color
于 2018-08-27T09:34:07.267 回答