Fragment shader and Polygon2D

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By bruteforce
:warning: Old Version Published before Godot 3 was released.

Hi,

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!

Hm… I guess, I can not use the UV if there is no texture :confused:

bruteforce | 2017-07-18 19:59

:bust_in_silhouette: Reply From: vikinghelmet99

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).

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)
  set_polygon(v0)
  set_uv(PoolVector2Array(uv))

hex polygon with shader texture

tripod | 2021-03-16 05:13

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.

SdSaati | 2021-05-27 23:31