image.get_pixel() always returns zero on GradientTexture

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By sygi

I have a TextureRect with a GradientTexture. I’m trying to get a pixel at a given position. I follow the accepted answer of this question:

var texture_rect = get_node("../TextureRect")
print(texture_rect)
var texture = texture_rect.get_texture()
print(texture)
var data = texture.get_data()
data.lock()
print(data)
print(position, ": ", data.get_pixelv(position).to_html(false))
data.unlock()

I get:

[TextureRect:1141]
[GradientTexture:1135]
[Image:2231]
(447.540558, 218.679306): 000000

even though the color in that position is not 00000. How do I fix this?

:bust_in_silhouette: Reply From: Xrayez

GradientTexture produces one-dimensional texture (2048x1 by default). If you use it for TextureRect it will just fill and repeat the texture along the region.

To workaround this, you can create a Viewport node containing TextureRect, and then fetch the resulting viewport texture with $viewport.get_texture(), from which you can download Image with ViewportTexture.get_data().

Also, consider supporting the proposal for adding GradientTexture2D class in Godot.

Isn’t there an easier approach to get a pixel at a given position from a Gradient Texture in Godot 3.5?

TGMG | 2023-04-05 07:04