Run on: Godot: v4.6.stable.official [89cea1439]
https://github.com/idkshite/fragment-shader-uv
I wanted to try out Shaders in Godot and struggled with getting UV values in my fragment shader on a Polygon2D. Here is how managed to get UV values in my Shader.
TLDR;
I could only see my shader displayed on the Polygon2D in my Editor after:
- adding the shader as a material to the
Polygon2D - adding a 1x1 px dummy texture to the
Polygon2D - manually adding UV data to to the
Polygon2D(maps polygon coordinates to 0->1 UV range
Step by Step
My setup is a simple 200x200 px square, created with a Polygon2D Node.
I wanted to visualize the UV.x value on that square by setting this Shader
shader_type canvas_item;
void fragment() {
COLOR = vec4(UV.x, 0.0, 0.0, 1.0);
}
And as soon as I set that Shader as a Material on the Polygon2D node, the material-preview displays what I would expect the shader to look like. But in the editor preview the shader doesn't get applied.
Then I applied a 1x1 px png (created in figma) as the Texture of the Polygon2D. This seems make UV values available to the shader. Now we see a bright red square, which indicates that UV.x is 1.0. But that still not what I'd expect. I assumed the UV.x differs throughout the entire Polygon2D and isn't uniform.
Now the Data -> UV on my Polygon2D is still empty. So I have to fill it.
My assumption was, that I could do that with the the Polygon tab at the bottom of the Editor and then Edit -> "Copy Polygon to UV"
But that literally copies over the Polygon coordinates into the UV data. And UV data needs to be represented in a normalized format (0->1). So after copying the Polygon Coordinates I normalized the UV data by hand.
Adding UV coordinates and normalizing them by mapping each vertex from world coordinates to the 0→1 UV range.

That's it. Now the shader get's displayed. Hope this helps someone out there 🙌


Top comments (0)