If you're trying to create a "food object" here's the method I use for creating objects (Only one of many methods)
Code: Select all
sample_object = {}
function sample_object:load(...)
local _i = {}
setmetatable(_i, {__index = self})
_i:setup(...)
return _i
end
function sample_object:setup(...)
local arg = ... or {}
self.kind = "sample_object_kind"
self.x = arg.x or 0
self.y = arg.y or 0
self.anotherArgument = arg.anotherArgument or "default value"
end
You'd create all your game objects using this template (Again, there are other methods. Look up some class modules on the forum if you want. Some of them make it simpler than having to use this code every time. Also, everything in the setup function will vary depending on what the object is.) and update them and draw them all as such:
To create the objects:
Code: Select all
game_object_list = {}
game_object_list["sampleObject1"] = sample_object:create { x = 100, y = 100, etc... }
game_object_list["sampleObject2"] = sample_object:create { x = 300, y = 200, etc... }
...
Inside the game's update function:
Code: Select all
local objects_to_remove = {}
for i, o in pairs(game_object_list) do
o:update(dt)
if o.isDead then
objects_to_remove[#objects_to_remove+1] = i
end
end
for i = 1, #objects_to_remove do
game_object_list[objects_to_remove[i]] = nil
end
(I added code for removing "dead" objects using the method I use. Basically in game, when an object is defeated or eaten or otherwise finished being used, you'd set it's isDead flag to true and the game will clean it up.)
Inside the game's draw function:
Code: Select all
for i, o in pairs(game_object_list) do
o:draw()
end
By using an object model, you can keep all that objects variables inside the object itself and create as many instances of an object type as you need. And all objects, whether they're enemies or players, can be put in the same pool of objects or separate pools if you need to.
By no means is this the only method for doing this. But it's how I do it.