How to implement common code and resources in different game objects?


#1

My roguelike has a main hero character, enemies and npcs. Some of their behaviours are common, such has catching on fire when walking over a fire trap. At the moment, the code to handle this is duplicated in the script file for each character’s game object. Also the fire animation has to be added separately to each game object.

Is there a way of somehow having a common game object or another way of just having one set of code and resources for these common things?


#2

Hello Ben,

Getting ahead of @britzl, have you tried a Lua script to share the code between your objects? :grin:

I don’t know your code but an idea would be something like (pseudocode):

on your scripts:
npc.script
enemy.script
hero.script

-- somewhere in the upper part of the script
local fire_trap = require('fire_trap')

-- later...
function on_message(...)

   if message.id == contact_point
       if message.group == FIRE_TRAP
           fire_trap.catchFire(self)


#3

Yes, I had thought of that approach - I could also simply add a common script file to the various game objects. Either of those would solve part of the problem but still leaving the issue of other shared resources being duplicated across the game objects.


#4

:thinking: Hmmm…

Shared resources…

(by the way, I edited my previous answer to add an idea in pseudocode)


#5

For the shared resources, have you tried using a factory in those objects?

a catch_fire_factory…


#6

Thanks for the pseudocode :slight_smile:

Now using a factory to create a child game object sounds like it could work. I’ll do some experiments…

Thanks again for your input!


#7

I’m not a big fan of having a ton of scripts per game object, but maybe you could have a catch_fire.script on the game objects and have go.property("enabled", false) that decides if it is enabled or not? Or, as @Edgaronfo suggests, Lua modules with this behaviour and require that code from the npc, enemy and hero?