Basic Fog of War Shader

This shader implements a fog of war, as long as it is passed a series of points and the proper camera variables it will accurately judge whether or not something should be occluded.

Shader code
shader_type canvas_item;

uniform sampler2D SCREEN_TEXTURE:hint_screen_texture,filter_linear_mipmap;

// --- UNIFORMS PASSED FROM GDSCRIPT ---
// The array of points where circles will be drawn.
uniform vec2 points[500];//this unfortunately has to be a constant size
// The actual number of points currently in the array.
uniform int points_count = 0;
// Camera/Viewport info for coordinate conversion.
uniform vec2 camera_global_position;
uniform vec2 camera_zoom;
uniform vec2 viewport_size;

// --- SHADER PARAMETERS (Editable in Inspector) ---
// The radius of the circles in pixels.
uniform float distance_threshold : hint_range(1.0, 400.0) = 50.0;
// The color to draw.
uniform vec4 hidden_color : source_color = vec4(0.0, 0.0, 0.0, 1.0);


void fragment() {
	// 1. Calculate the world coordinate of the current pixel.
	// SCREEN_UV is the pixel's position on the screen (from 0.0 to 1.0).
	// We use the camera and viewport info to convert this to a global coordinate.
	vec2 world_pos = (SCREEN_UV - vec2(0.5)) * viewport_size / camera_zoom + camera_global_position;

	// 2. Assume the pixel is not within the threshold distance of any point.
	bool is_near_point = false;

	// 3. Loop through the provided points and check the distance.
	for (int i = 0; i < points_count; i++) {
		if (distance(world_pos, points[i]) < distance_threshold) {
			is_near_point = true;
			break; // Optimization: A point was found, so no need to check others.
		}
	}

	// 4. Get the original color of the pixel from the screen texture.
	vec4 original_color = texture(SCREEN_TEXTURE, SCREEN_UV);

	// 5. Set the final color for the pixel.
	if (is_near_point) {
		// If near a point, show point
		COLOR = original_color;
	} else {
		// Otherwise, hide point.
		COLOR = hidden_color;
	}
}
Tags
fog of war, occlusion
The shader code and all code snippets in this post are under MIT license and can be used freely. Images and videos, and assets depicted in those, do not fall under this license. For more info, see our License terms.

Related shaders

Hexagon TileMap Fog of War

Fog of war with alpha cut off as white color

Depth based fade (Fog of war)

guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments