Infinite grid (V1.0)

This infinite grid shader is combination of a simple transparency shader that follows the mouse and a small grid sprite of 12×12 squares that also follows the mouse when it gets far.

 

Important: to get the shader to work you need a grid sprite of your choice and both the shader and the moving script attached to the grid sprite.

 

First attach the following code snippet to the grid sprite: it will follow the mouse while strictly sticking to your grid. Change the grid size if needed.

func _process(delta: float) -> void:
	var mouse_position = get_global_transform_with_canvas().affine_inverse() * get_viewport().get_mouse_position()
	var grid_position = Vector2(int(mouse_position.x-int(mouse_position.x)%64), int(mouse_position.y-int(mouse_position.y)%64)) # Calculate the correct grid position the sprite should have
	if((visual_grid.global_position - Vector2(grid_position)).length() > 100.0): # if the mouse gets far, the sprite follows the new mouse position
		visual_grid.global_position = Vector2(grid_position) + Vector2(32.0, 32.0) # In my case I needed to add an offset of 32 pixels in both axes, due to my sprite

Then, attach the shader code to the grid sprite, and finally control the distance_to parameter, so it follows the mouse (it converts the mouse position to sprite UVs. Note: both code snippets may go in the same script. 

extends Sprite2D
var texture_size = Vector2()

func _ready():
	if texture:
		texture_size = texture.get_size()

func _input(event):
	var world_pos = get_global_mouse_position()
	var local_pos = to_local(world_pos)
	if get_rect().has_point(local_pos):
		var uv = get_uv_from_pos(local_pos)
		setTransparencyPoint(uv)

func get_uv_from_pos(local_pos: Vector2) -> Vector2:
	var top_left_pos = local_pos + (texture_size) / 2
	var uv = top_left_pos / (texture_size)
	return uv

func setTransparencyPoint(uv):
	if material and material is ShaderMaterial:
		material.set_shader_parameter("distance_to", uv)
Shader code
shader_type canvas_item;

uniform vec2 distance_to = vec2(0.5, 0.5);
uniform float transparency_strength = 1.0;
uniform float transparency_fall = 1.0;

void fragment() {
	float dist = length(UV - distance_to);
	dist = clamp(dist, 0.0, 1.0) * transparency_fall;
	COLOR.a *= (1.0 - dist) * (1.0/transparency_strength);
}
Live Preview
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 enekoassets

Related shaders

Comments 0

No comments yet.