Hello all, I’ve been driving myself crazy trying to find a way to do this. I’m trying to make a card-based game where the cards might get flipped. To avoid creating a million mini-scenes for each card (e.g. ace_of_clubs.tscn, etc.), I want to have a single scene card.tscn that loads a folder of .pngs (the folder would change based on some integer assigned as the card scene is created in the main) to use as its animation, using the _ready function in gdscript. Does anyone know how to do this? Thank you for your help!
You can create a SpriteFrames and assign it to the AnimatedSprite2D, then use an AtlasTexture to preload a PNG and cut out sections to add to the frames. You can use something like this:
extends AnimatedSprite2D
const COLUMNS_PER_CARD = 5
const CARD_HEIGHT = 64
const CARD_WIDTH = 64
@onready var list_of_spritesheets = ["res://spritesheet1.png", "res://spritesheet2.png", "res://spritesheet3.png", "res://spritesheet4.png", "res://spritesheet5.png"]
func _ready():
var rng = RandomNumberGenerator.new()
rng.randomize()
var selected_texture = preload(list_of_spritesheets[rng.randi_range(0, 4)])
sprite_frames = SpriteFrames.new()
for i in range(COLUMNS_PER_CARD):
var atlas = AtlasTexture.new()
atlas.atlas = selected_texture
atlas.region = Rect2(CARD_WIDTH * i, CARD_HEIGHT * i, CARD_WIDTH, CARD_HEIGHT)
sprite_frames.add_frame(atlas)