0 votes


I am trying to make a fragment shader, and apply it to a Polygon2D node.

The shader is a very simple horizontal gradient (from black to red):

COLOR = color(UV.x, 0.0, 0.0, 1.0);

It works with Sprite nodes, but doesn't work with Polygon2D:
enter image description here

Can anyone show me how to do this properly?

(Godot Engine 2.1.3 win64)

Thank you!

in Engine by (672 points)

Hm... I guess, I can not use the UV if there is no texture :/

1 Answer

+3 votes
Best answer

For people who have this issue in the future, know that UVs don't get passed into the shader if there is no texture. I've gotten around it by having a solid white 1 x 1 placeholder texture.

In short, under Polygon2D, set your texture to an Image Texture. Next, set its size to x==1 and y==1. For the sake of efficiency, unless you need them, you can turn all flags off.

From that, a UV will be provided to your custom shader; without a texture, even an unused one, apparently UV is meaningless to it. If anyone has further data I would love to hear about it.

Side note: Remember that you still need to set the UVs for your individual polygon coordinates; or they'll all, still, default to (0,0).

by (50 points)
selected by

side note: if you want to use a 1:1 mapping from the polygons bounding box to the frag coords, you can do something like this:

  var v0 = .... polygons vertices....
  var x0 = INF
  var y0 = INF
  var x1 = -INF
  var y1 = -INF
  for v in v0:
    x0 = min(x0, v.x)
    x1 = max(x1, v.x)
    y0 = min(y0, v.y)
    y1 = max(y1, v.y)
  var s = max(x1 - x0, y1 - y0)
  var d = Vector2(s / 2, s / 2);
  var uv = PoolVector2Array([])
  for v in v0:
    uv.append((v + d) / s)

hex polygon with shader texture

You are true, thank you for this advice, I also used the gradient texture instead of an image, maybe it's better for efficiency but I realized that gradient is just have width (UV.x) so there is no UV.y with gradient, then your solution still is the best for me.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.