I want to implement an entity component system, but I've been some trouble as of late. Let's say that I have a fire ball spell that spawns a ball of fire which moves towards a random enemy in 500 units range. In an OO architecture, I would have a Player class and I could simply detect a keypress and cast the spell like so:
function player:update(dt)
if is_key_pressed('e') then
self:cast_fire_ball()
end
end
and the cast fireball spell implementation would be something close to this:
function Player:cast_fire_ball()
-- query the world for nearby units, filter the allies out and select a
-- random enemy
local units_in_range = self.world:query('circle', 250)
local enemies = filter(units_in_range, function(unit)
return unit.is_hostile
end)
local target = random(enemies)
-- create a new projectile of type fireball and set the position and
-- direction vectors
self.world:add(Projectile:new(FIREBALL, self.pos, target.pos - self.pos)
end
Now the projectile has an on_collide method that is called by the world whenever a collision occurs between the projectile and any unit.
In an entity component system however, the player isn't an instance of a class, it's just a uuid like 1234 or in some implementations, an id with an array of components that maybe has a bitset to work out what components it has. I can imagine the player having an InputComponent that detects keypresses, and the InputSystem takes care of that. But what happens from there ? and where does the code for the `cast_fire_ball` spell live ?