a simple reflection shader

A simple and straightforward mirror shader that can be placed anywhere on the map to mirror the adjacent screen content above it. It can be used for the reflection of water in a TileMap. Scale automatically align to the top edge.
Shader code
shader_type canvas_item;

uniform sampler2D  SCREEN_TEXTURE:hint_screen_texture,  filter_nearest;
uniform float offset = 0;
uniform float scale: hint_range(0.05, 1.0, 0.05) = 1.0;

varying float screen_baseY;

void vertex() {
    // uv to screen_uv for getting top screen_uv.y when uv.y==0
    // firstly uv to local then local to screen_uv, local coordinate is center based so we should convert (0,1) to (-1, 1) mulity with pixles distance
	mat4 t = mat4(vec4(2.0, 0, 0, 0), vec4(0, 2.0, 0, 0), vec4(0, 0, 1.0, 0), vec4(-1.0, -1.0, 0, 1.0));
	screen_baseY = (inverse(t)*SCREEN_MATRIX*CANVAS_MATRIX *  (MODEL_MATRIX)*vec4(-1.0/TEXTURE_PIXEL_SIZE.x/2.0,  -1.0/TEXTURE_PIXEL_SIZE.y/2.0, 0, 1.0)).y;
}

void fragment() {
	
	vec2 uv =  SCREEN_UV;
	uv.y -= screen_baseY;
	uv.y *= scale;
	uv.y += screen_baseY;
	
	COLOR = texture(SCREEN_TEXTURE, vec2(uv.x, (screen_baseY*2.0- (uv.y-offset))));
}
The shader code and all code snippets in this post are under CC0 license and can be used freely without the author's permission. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms.

More from niwho

slice texture

2D Pixel Art Water

Related shaders

[2D]Water reflection and distortion simulation shader ver1.2

Sprite Water Reflection Pixel Art Pokémon Style

Water 2D + reflection 4.x

Subscribe
Notify of
guest

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Rathalos23
Rathalos23
1 month ago

Hello,

Can you give a quick exemple of how to use it ?

For beginners studying Shaders it’s not that easy.
What do you mean by “anywhere on the map” ? Should i apply the Shader to the Tilemap itself or specific Tiles ? Or create a new Node then attach it ?
I tried all of that and nothing works, so any advice would be nice =) !

Last edited 1 month ago by Rathalos23
1amp
1amp
17 days ago
Reply to  Rathalos23

我最近也在研究着色器。您可以直接在 TileMap 节点的 Inspector 中创建着色器。绘制地形图时,您可以提前组织图层。您可以将特定的着色器代码应用于特定的 TileMap 节点,或者直接创建一个 Sprite2D 节点,并在 Sprite2D 节点的检查器中将着色器代码添加到其材质中。