Shadow 2D

Add a 2D shadow behind your texture.  

Shader code
/**
* Shadow 2D.
* License: CC0
* https://creativecommons.org/publicdomain/zero/1.0/
*/
shader_type canvas_item;
render_mode blend_mix;

uniform vec2 deform = vec2(2.0, 2.0);
uniform vec2 offset = vec2(0.0, 0.0);
uniform vec4 modulate : hint_color;

//uniform vec2 texture_size; //uncomment for GLES2

void fragment() {
	vec2 ps = TEXTURE_PIXEL_SIZE;
	vec2 uv = UV;
	float sizex = float(textureSize(TEXTURE,int(ps.x)).x); //comment for GLES2
	float sizey = float(textureSize(TEXTURE,int(ps.y)).y); //comment for GLES2
	//float sizex = texture_size.x; //uncomment for GLES2
	//float sizey = texture_size.y; //uncomment for GLES2
	uv.y+=offset.y*ps.y;
	uv.x+=offset.x*ps.x;
	float decalx=((uv.y-ps.x*sizex)*deform.x);
	float decaly=((uv.y-ps.y*sizey)*deform.y);
	uv.x += decalx;
	uv.y += decaly;
	vec4 shadow = vec4(modulate.rgb, texture(TEXTURE, uv).a * modulate.a);
	vec4 col = texture(TEXTURE, UV);
	COLOR = mix(shadow, col, col.a);
}
Tags
2d, shadow
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

2D shadow with bottom offset, image ratio independent shadow direction, and minimal vertex increase

2D Cast shadow

2D Pixel Shadow/Outline

Subscribe
Notify of
guest

13 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Josh
Josh
3 years ago

Would there be a way to do this with gles2?

Dan
Dan
3 years ago

How to use this and AnimatedSprite?

Also, good job.

Tks

nahrf
nahrf
1 year ago
Reply to  Dan

prolly gotta make copy the frames of the sprite and ya know.. depends what you need to do

nahrf
nahrf
1 year ago
Reply to  nahrf

just using the material propertyy

RafaFiedo
3 years ago

Nice shader!

Mamaev
Mamaev
3 years ago

If you make the shadow long, it is cropped. How can I fix it?

Fox
Fox
3 years ago
Reply to  Mamaev

your texture must have a bit of transparent area around the main texture so the shader has space. It can’t draw outside the textures bounding box.

The2AndOnly
The2AndOnly
1 year ago
Reply to  Fox

I can’t do that! It would make a terrible workflow for creating textures and complicate positioning sprites!

KING_FUCK
KING_FUCK
7 months ago
Reply to  The2AndOnly

whiner

Fisen
Fisen
1 year ago

Doesn’t work with Godot 4.

nahrf
nahrf
1 year ago
Reply to  Fisen

nothing does

kyle
kyle
1 year ago
Reply to  Fisen

Replace hint_color with source_color, that should fix the problem.