编辑
2023-11-17
学习
00
请注意,本文编写于 339 天前,最后修改于 339 天前,其中某些信息可能已经过时。

目录

内建变量
UV
TEXTURE
示例

参考地址:https://docs.godotengine.org/en/4.1/tutorials/shaders/shader_reference/shading_language.html

内建变量

UV

UV 是一个二维变量,包含了纹理坐标的X和Y分量。

UV 取值在0-1之间, 从左到右, 由上到下.

image.png

js
void fragment() { COLOR = vec4(UV, 0.5, 1.0); }

上面代码使用 UV 的xy分量作为 COLOR的 r 和 g 分量

效果:

TEXTURE

TEXTURE 表示当前片段着色器中使用的纹理

下面代码使用UV坐标从TEXTURE中采样颜色,并将结果存储在textureColor中。 然后赋值给当前片段的COLOR

void fragment() { // 使用UV坐标从纹理中采样颜色 vec4 textureColor = texture(TEXTURE, UV); // 将采样到的颜色赋值给COLOR COLOR = textureColor; }

同理, TEXTURE 是当前着色器的纹理, 也可以加载自定义的纹理

下面代码就是使用自定义的纹理变量给与到当前片段

shader_type canvas_item; uniform sampler2D custom_texture : hint_black_albedo; // 声明一个sampler2D类型的uniform变量 void fragment() { // 在片段着色器中使用custom_texture进行纹理采样 vec4 sampledColor = texture(custom_texture, UV); // 对采样到的颜色进行处理,例如修改颜色值 sampledColor.rgb *= 0.5; // 将颜色值减半 // 将处理后的颜色赋值给COLOR COLOR = sampledColor; }

这样就可以在 gd脚本中 控制纹理

extends Node2D func _ready(): # 获取你的节点(这里假设你的节点有一个ShaderMaterial) var sprite = $Sprite # 获取节点的材质 var material = sprite.material as ShaderMaterial # 确保材质存在且具有uniform变量 custom_texture if material and material.has_shader_param("custom_texture"): # 加载你的纹理 var texture = preload("res://path/to/your_texture.png") # 将纹理赋值给custom_texture uniform变量 material.set_shader_param("custom_texture", texture) else: print("Material or shader param not found.")

示例

以下着色器实现了两个纹理分别占用左半边和右半边

shader_type canvas_item; uniform sampler2D custom_texture; uniform float center_line : hint_range(0,1) = 0.5; void fragment() { vec4 sampledColor = texture(custom_texture, UV); sampledColor.a = 0.8; vec4 tempColor = vec4(UV.x, UV.y, 0.9, 0.5); // 使用 mix 函数混合左右两部分颜色 vec4 finalColor = mix(tempColor, sampledColor, step(UV.x, center_line)); COLOR = finalColor; }

提示

这里用到了 mix函数 mix(x, y, a); 其中:

x 和 y 是要插值的两个值,可以是标量、向量或颜色。

a 是插值因子,它决定了 x 和 y 之间的权重。

在0到1的范围内,a 的值为1时结果为 x,为0时结果为 y。

未设置 sampledColor 时是这样

image.png

我在这里加入了自己绘制的纹理

image.png

效果如下

image.png

本文作者:beiklive

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!