Home > Software engineering >  How to scale textures stored in/called from a Godot array
How to scale textures stored in/called from a Godot array

Time:11-23

I have 100 .png images loaded into a Godot 3.5.1 array of objects (named splash_planets) as StreamTextures. I need to know how to reference them to allow scaling. I am able to draw them using the following:

for splash_planet in splash_planets:
    center = Vector2(splash_planet._x, splash_planet._y)
    draw_texture(splash_planet._texture, center)

Now I want to do something like:

    draw_texture(splash_planet._texture, center, (scale_x, scale_y))

Thanks in advance for any advice.

CodePudding user response:

First of all, in this line:

draw_texture(splash_planet._texture, center)

You would be drawing the texture with the upper left corner on the coordinates of center. If you want to draw the texture with the center on center, you do this:

var texture := splash_planet._texture
var size := texture.get_size()
draw_texture(texture, center - size * 0.5)

Since you are using draw_texture and you want to scale, you can use draw_set_transform:

    draw_set_transform(Vector2.ZERO, 0.0, Vector2(scale_x, scale_y))

As you can see the third parameter is the scale. The first two parameters are translation and rotation. Once you have set the transform you can do the draw call as usual:

    draw_set_transform(Vector2.ZERO, 0.0, Vector2(scale_x, scale_y))

    var texture := splash_planet._texture
    var size := texture.get_size()
    draw_texture(texture, center - size * 0.5)

Calling draw_set_transform again (or calling draw_set_transform_matrix) will overwrite the previos transform.


Alternatively you can use draw_texture_rect:

    var texture := splash_planet._texture
    var size := texture.get_size() * Vector2(scale_x, scale_y)
    var rect := Rect2(center - size * 0.5, size)
    draw_texture_rect(texture, rect, false)

In this case we compute the rectangle where to draw the texture. We also specify we don't want to tile it (the false as third argument), so Godot will stretch it.

You might also be interested in draw_texture_rect_region, which allows you to draw a rectangular region of the source texture.

  • Related