Help required with using shader to colour a triangle

Godot Version

4.4.1

Question

Help using shader to colour a triangle

Hi - I’m trying to colour a triangle using a shader. The thinking being to interpolate the colour as a distance between the 3 vertices using barycentric coordinates.

I generate the triangles as Polygon2D’s in code, then attach a material with a shader to each polygon. The thinking is that down the line I’ll provide the appropriate 3 colours to each shader - but for now I’ve hardcoded 3 colours in the shader.

This is the shader code I’m trying to use.

void fragment() {
	float d0 = sqrt(pow(UV.x, 2)+pow(UV.y, 2));
	float d1 = sqrt(pow(1.0-UV.x, 2)+pow(UV.y, 2));
	float d2 = sqrt(pow(UV.x, 2)+pow(1.0-UV.y, 2));
	
	if (d0 > d1 && d0 > d2) {
		COLOR = center_colour;
	} else if (d1 > d0 && d1 > d2) {
		COLOR = point_0_colour;
	} else {
		COLOR = point_1_colour;
	}
}

However, this ends up rendering each triangle as a singular colour:

Each hexagon is basically 6 triangles being rendered.

I’ve solved this myself - it came down to a Godot bug Polygon2D UVs are never available to canvasitem shader materials · Issue #81627 · godotengine/godot · GitHub

If you stumble here and have the same issue - there’s a very easy workaround listed in the issue above