Entity System - Mjdgithuber/AstroCorps GitHub Wiki
The Entity System
Entities are objects that live on top of the tile map. Entities also have functionality unlike the static tiles that are part of the tilemap. In order to interface with the engine's Entity system, a user must use the Entity Lua user type.
First lets look at how to write a new type of entity:
--[[
first we will setup a metatable for our new entity
this metatable will define some of the common functions
that every entity should have like the update function
NOTE: every key in the metatable should exactly match
the names shown below.
Ex: if you want your entity to be able to be update
sensitive, you must have a function named 'update'
that takes in only one parameter of self
]]
local EntityMetatable = {
--[[ update is a function that gets called each frame
and it has NO parameters other than self ]]
update = function(self)
-- Fill with anything that needs to be updated
end,
-- to name our entity we must give a value to 'entity_type'
entity_type = 'Our New Type'
}
-- for object orientedness we must set the index method to our new metatable
PlayerMetatable.__index = PlayerMetatable
-- next we need a constructor
local OurEntityConstructor = {
-- We need to define a function named 'new' that takes in 3 parameters
new = function(name, x, y)
DEBUG('Created New Entity, Name: ' .. name .. ' X: ' .. x .. ' Y: ' .. y)
--[[
create our new Entity. In this line we make a new
empty table that has the metatable we defined earlier
which allows common functions like update to work
on every new instance of our new Entity type
]]
local our_en = setmetatable({}, EntityMetatable)
--[[
Next we need to make sure that our entity gets linked
with our engine. We will use the GameManager to get a
reference to the tile map. Once we get that reference
we can call 'new_entity' to add our entity to the engine
NOTE: we must use the return value of new_entity to save
the engine's version of our entity within lua. We
MUST call this cpp_entity
]]
our_en.cpp_entity = GameManager.get_tile_map():new_entity(name, x, y, 1, 1)
our_en.cpp_entity:set_texture_sheet(0) -- set the texture
-- return it
return our_en
end
}
-- finally load our entity into the global constructor table
EntityCreator.OurEntityName = OurEntityConstructor
Now that we have made our new entity we should see how we can actually use it.