Programmatically set up an AnimatedSprite2D from a spritesheet

Godot Version

4.4

Question

I want to programmatically set up an AnimatedSprite2D from a spritesheet. Since I also want to make use of a normal map I first create a canvas texture, then I extract the single frames into an atlas texture and add these into the different animations.
I added the @tool command to see the result in the editor. And everything seems to work since I see the desired result in the editor. The problem is that when I run the game I don’t see anything. I seem to be missing something. Why is this working in the editor but not in the game?

@tool
extends AnimatedSprite2D

@export_category("Settings")
@export var animation_name:String
@export var diffuse_texture:Texture2D
@export var normal_texture:Texture2D
@export var hframes:int = 8
@export var vframes:int = 8


func _ready():
	create_animation()


func create_animation():
	var canvas_texture:CanvasTexture = CanvasTexture.new()
	var frame_width:int = diffuse_texture.get_width() / hframes
	var frame_height:int = diffuse_texture.get_height() / vframes

	canvas_texture.diffuse_texture = diffuse_texture
	
	if normal_texture:
		canvas_texture.normal_texture = normal_texture
		
	sprite_frames = SpriteFrames.new()
	
	for vframe in vframes:
		sprite_frames.add_animation(animation_name + str(vframe))
		
		for hframe in hframes:
			var region:Rect2 = Rect2(hframe * frame_width, vframe * frame_height, frame_width, frame_height)
			var atlas_texture = AtlasTexture.new()
			atlas_texture.atlas = canvas_texture
			atlas_texture.region = region
			
			sprite_frames.add_frame(animation_name + str(vframe), atlas_texture)
			
	sprite_frames.remove_animation("default")

It might be worth logging a bunch of info during the setup and seeing if any of it looks off.

If you replace the guts of this with a simple opaque rectangle, does that show up in game?

I just found out what the problem was: I thought if I delete the default animation then the next animation in line is going to be the one showing up. Which is the case in the editor. But when I start the game the default animation is removed but it is still set as the animation to play. Somehow I didn’t get any error message for that.
So the solution in the end is: set the animation to play at the end.

1 Like