Entity.lua 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. local Entity = {}
  2. local function IsFunction(x)
  3. return (type(x) == "function")
  4. end
  5. function Entity.new(...)
  6. local self = setmetatable({},{__index=Entity})
  7. local ComponentsToAdd = {...}
  8. self.World = nil
  9. self.Components = {}
  10. for _,val in pairs(ComponentsToAdd) do
  11. self:AddComponent(val)
  12. end
  13. return self
  14. end
  15. function Entity:GetComponent(componentType)
  16. return self.Components[componentType]
  17. end
  18. function Entity:AddComponent(component)
  19. if IsFunction(component.Adding) then
  20. component:Adding(self)
  21. end
  22. self.Components[component.ComponentType] = component
  23. end
  24. function Entity:RemoveComponent(component)
  25. if IsFunction(component.Removing) then
  26. component:Removing()
  27. end
  28. self.Components[component.ComponentType] = nil
  29. end
  30. -- Called when added to world
  31. function Entity:Create(world)
  32. self.World = world
  33. for _, component in pairs(self.Components) do
  34. if IsFunction(component.Create) then
  35. component:Create(world)
  36. end
  37. end
  38. end
  39. function Entity:Removing() -- Cleaning from world
  40. self.World = nil
  41. for _, component in pairs(self.Components) do
  42. if IsFunction(component.EntityRemoving) then
  43. component:EntityRemoving()
  44. end
  45. end
  46. end
  47. function Entity:Destroy() -- Destroy self and components
  48. -- if it's part of a world remove it
  49. if self.World and self.World:GetEntity(self) then
  50. self.World:CleanEntity(self)
  51. end
  52. -- detach each component and destroy.
  53. for _, component in pairs(self.Components) do
  54. self:RemoveComponent(component)
  55. if IsFunction(component.Destroy) then
  56. component:Destroy()
  57. end
  58. end
  59. end
  60. function Entity:PreStep(time,dt)
  61. for _, component in pairs(self.Components) do
  62. if IsFunction(component.Step) then
  63. component:PreStep(time,dt)
  64. end
  65. end
  66. end
  67. function Entity:Step(time,dt)
  68. for _, component in pairs(self.Components) do
  69. if IsFunction(component.Step) then
  70. component:Step(time,dt)
  71. end
  72. end
  73. end
  74. function Entity:PostStep(time,dt)
  75. for _, component in pairs(self.Components) do
  76. if IsFunction(component.Step) then
  77. component:PostStep(time,dt)
  78. end
  79. end
  80. end
  81. function Entity:RenderStepped(time,dt)
  82. for _, component in pairs(self.Components) do
  83. if IsFunction(component.Step) then
  84. component:RenderStep(time,dt)
  85. end
  86. end
  87. end
  88. return Entity