Proper TileMap Tile UV shader

Standard solution for calculating tile uv based on pixel_size has issue when using animated tiles. To fix this we can rely on vertex coordinates to get proper UV

 

// Works only if tiles are not animated
vec2 get_cell_uv(vec2 uv, vec2 pixel_size) {
	vec2 ut = uv;
	ut.x = mod(1.0 - uv.x, pixel_size.x / tile_size) / pixel_size.x * tile_size;
	ut.y = mod(1.0 - uv.y, pixel_size.y / tile_size) / pixel_size.y * tile_size;
	return ut;
}
Shader code
shader_type canvas_item;

const vec2 local_uv[] = { vec2(0,0), vec2(0,1), vec2(1,1), vec2(1,0)};
varying vec2 LOCAL_UV;
void vertex() {
	LOCAL_UV = local_uv[VERTEX_ID];
}

void fragment() {
	COLOR = vec4(LOCAL_UV, 0.0, 1.0);
}
Tags
animated, tile, tilemap, uv
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

Highlight the Mouse Tile in an Hexagon Tile Map

2D tilemap tile blending (texture splatting)

screen tile shader

guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments