Also, I haven't explained yet the aim of this part of code:
-- Modify metatable of hero to make carried entities follow him with hero:on_position_changed().
local hero_metatable = sol.main.get_metatable("hero")
function hero_metatable:on_position_changed()
if self.custom_carry then
local x, y, layer = self:get_position()
self.custom_carry:set_position(x, y+2, layer)
end
end
To make a custom entity follow the hero when carried, its position is changed when the event "hero:on_position_changed()" is called. When a custom entity has been lifted by the hero, a reference to that entity is stored in "hero.custom_carry" (this is automatically done in the generic_portable.lua script), so that the function above can move that entity position too.
Note that, by default, custom entities are drawn in Z-order (the creation order), which does not allow to draw the entity above the hero since the hero is drawn in Y-order (an entity with bigger Y-coordinate is drawn above the others with smaller Y-coordinate). In the generic_portable.lua entity, I chose Y-order to drawn a custom entity carried by the hero; and since we position the carried entity using "self.custom_carry:set_position(x, y+2, layer)" (see the function above), the carried entity will be drawn after the hero (above the hero). Obviously, the sprite of the carried entity is shifted with "drawable:set_xy(x,y)" to draw the carried entity in the correct position, which is done in the generic_portable.lua script.
This is a bit technical, but I did not find another workaround and probably there is not another solution to draw the custom entity above the hero (and in the same layer).
If you are already using the event "hero:on_position_changed()" you would need to combine the code above with yours to avoid overriding one function with the other.