What's the best way to change a sprite's texture?

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


What’s the most efficient (CPU/GPU usage) way of changing the texture of a Sprite?

I’m making a roguelike. The visible screen is made up of 80x40 tiles like so:

enter image description here

Game, Stage and the first two tiles

I’m using a single .png for the Sprites’ textures and using region_rect to display only a section of it:

enter image description here

CP437 example

When the character moves (say, from 0,0 to 0,1) both tiles must update the portion of the texture being shown (0,0 to the ‘ground’ part of the texture and 0,1 to the ‘player’ part of the texture). Currently, I’m using set_region_rect on the Sprites to change the area of the .png to be displayed.

Is this the best way? With roughly 130 of the tiles changing every 0.2s, the game only runs at ~40fps which seems low for such a simple system.


:bust_in_silhouette: Reply From: epark009

You might be better off using a TileMap node which is designed for this sort of thing. Check out this tutorial: Using tilemaps — Godot Engine (3.1) documentation in English

That’s a good idea but I don’t think it will work. My texture is all white so I need to use shaders or a sprite’s modulate to change the color. TileMaps don’t support doing either of those per cell.

someantics | 2019-09-24 20:19

In that case, you can try splitting up each tile into individual images and swap them, instead of using region rect. If you’re worried about load times, you can use the ResourcePreloader node to load all of the tiles whenever the scene is loaded, then all of the tiles will be there in memory or in the cache. I’m unsure if this is faster than what you’re currently doing because I don’t know how well Godot optimizes region rects, but you can give it a try. I do know the entire image is present even when you only show a small portion of it, because when I tried to apply shaders to my region rects, the adjacent images would bleed into the current image, so I had to split it up to avoid that.

epark009 | 2019-09-25 00:08

Yeah, good idea. I’m not sure why I’d resisted splitting the tiles up but I’ll give it a go. Thanks!

someantics | 2019-09-25 12:18