Checkboard Pattern

Made by Flood Gate
————————

Draw a checkboard on a canvas item.

To control that the aspect ratio of the squares is not lost by reescaling the screen, add this to a script attached to the shader. If that isn’t the intent, don’t use the script.

C#

using Godot;
using System;

[Tool]
public partial class SquaresTextureShaderController : TextureRect
{
	[Export] public TextureRect imageTexture;

	// Called every frame. 'delta' is the elapsed time since the previous frame.
	public override void _Process(double delta)
	{
		Notification((int)NotificationTransformChanged, true);
	}

	public override void _Notification(int what)
	{
		if (what == (int)NotificationTransformChanged)
		{

			Vector2 size = GetViewport().GetWindow().Size;
			float aspectRatio = size.X / size.Y;

			Vector2 aspectRatioVector = new Vector2(1, aspectRatio);
			Vector2 transposedAspectRatioVector = new Vector2(1, aspectRatio);

			(GetMaterial() as ShaderMaterial).SetShaderParameter("aspect_ratio_vector", aspectRatioVector);

		}
	}
}
Shader code
shader_type canvas_item;

uniform vec2 grid_size = vec2(10.0, 10.0); // Size of the checkerboard squares
uniform vec4 color1 : source_color = vec4(0.8, 0.8, 0.8, 1.0); // Light gray
uniform vec4 color2 : source_color = vec4(0.4, 0.4, 0.4, 1.0); // Dark gray
uniform vec2 aspect_ratio_vector = vec2(1, 1.1); // Default aspect ratio vector (to be updated by script)

void fragment() {
    // Calculate the aspect ratio
    float aspect_ratio = aspect_ratio_vector.x / aspect_ratio_vector.y;

    // Adjust UV coordinates to preserve aspect ratio
    vec2 adjusted_uv = vec2(UV.x, UV.y * aspect_ratio);

    // Calculate the grid position based on the adjusted UV and grid size
    vec2 grid_pos = floor(adjusted_uv * grid_size);

    // Use mod to alternate between color1 and color2
    float checker = mod(grid_pos.x + grid_pos.y, 2.0);

    // Assign the color based on the checker value
    COLOR = mix(color1, color2, checker);
}
Tags
Board, Checkboard, Chess, grid, pattern, Squares
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.

Related shaders

Hexagon pattern

Variable Dot Pattern

circular pattern

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments