0 votes

I want to create a texture cropped from the texture used by a tileset.

I have this code:

var txr = _tile_map.tile_set.tile_get_texture(id)
var img = txr.get_data()
var imgDest = Image.new()
imgDest.blit_rect(img, Rect2(0, 0, 128, 128), Vector2(0, 0))
var imgTxr = ImageTexture.new()
imgTxr.create_from_image(imgDest)
btn.texture_normal = imgTxr

When using txr directly it works fine... But the whole texture is used and I want it the button to have it cropped to the tile size.

While debugging I found txr.get_data() returns [null]

Why is this happening?
Is there another way to corp a texture retrieved from a tileset?

in Engine by (12 points)

1 Answer

0 votes

You can use AtlasTexture for this.

Your code would look something like this:

var texture = _tile_map.tile_set.tile_get_texture(id)
var region_to_crop = Rect2(0, 0, 128, 128)
var atlas_texture = AtlasTexture.new()
atlas_texture.set_atlas(texture)
atlas_texture.set_region(region_to_crop)
btn.texture_normal = atlas_texture

An alternative way to write the same code:

func your_function_here():
    var texture := _tile_map.tile_set.tile_get_texture(id)
    var region_to_crop := Rect2(0, 0, 128, 128)
    btn.texture_normal = get_cropped_texture(texture, region_to_crop)

func get_cropped_texture(var texture : Texture, var region : Rect2) -> AtlasTexture:
    var atlas_texture = AtlasTexture.new()
    atlas_texture.set_atlas(texture)
    atlas_texture.set_region(region)
    return atlas_texture
by (18 points)
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.