How to use/make modular sprites in code?

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

So I’m making a top down pixel art game, where the characters can handle any number of weapons and equipment.

I’d like to make a base sprite for holding objects, then swap what object he is holding using code. Do I have to make one individual sprite for every combination? Or is there something I can hack together to make this work?

I thought about using a Cutout Animation, but with a generic, replaceable shaft for the weapon. Then I could swap the resource for that shaft with code. Although I’m not sure if this is the correct approach, or even reasonable. This also doesn’t really help with the hitbox of the new weapon, as I’d just be replacing the texture.

Ideally, I’d want to be able to make a scene for each weapon, pop that in some folder, and just instantiate what I need, when I need it.

:bust_in_silhouette: Reply From: albinaask

Greetings, this is a rather common problem, that you may solve if you’re a little creative. It could be done using either approach, but I’d suggest the latter since you that way can define a weapon however you like and then just plop it in ass needed as a child of the player. If you want to be extra fancy, you make a template scene and just fill it dynamically with the things that is picked in-game, aka you may have a sprite for the barrel, being the base of the scene, adding a script, exposing a var with a path for the desired projectile, scope, silencer, stock, grip, et.c. Then you may just populate the file paths from the game and the script automatically loads them and adds nodes containing them. But as you mention, there’s many ways of solving this, but this way, even though complicated is rather flexible and provides loads of customizability later

Thanks for the answer, really insightful. But I’m unsure on how to begin implementing such a thing. Do you have an example in a codebase, or some pseudo code?

From what I gathered, I’d make a base class for “Gun” with some preset nodes

classname Gun

onready var base = "../stuff/weapons/"
onready var weapon = $base

Then, whenever I want to set or change the properties of this weapon/part

base += "some_weapon"

Then, to implement new weapons, I’d just need to make a scene and add it to the weapons folder. Is this correct? Thanks again for the answer.

wndr | 2020-07-15 02:08