Hi Jasoco,
Using any of the existing OOP libraries will help you make what you want more easily.
Allow me to present how you could do that with middlecass. The other libraries are similar, with changes in the syntax.
First, if you are making classes, you don't need to add "type" - you can call your class Enemy instead of "enemyType":
Code: Select all
require 'middleclass.init'
Enemy = class('Enemy')
function Enemy:initialize(x,y)
self.hp = 1
self.x = x
self.y = y
end
function Enemy:update(dt) end
function Enemy:draw() end
function Enemy:delete() end
I've put empty update & draw methods (functions in classes are usually called like that, 'methods'). These ensure that no matter what type of enemy you are working with, if you call "update", you will get no errors.
initialize would be your "onLoad" function, and delete could be your "onDeath". I've taken the liberty of adding a couple parameters to initialize, and using them to set up the enemy's x and y.
You can create your first enemy already, using Enemy:new(x,y)
And you can call billy:draw() and billy:update(dt). However, since they are empty functions, this will not do anything.
Now your Blob enemy type can be a subclass of Enemy. This is were the magic begins:
Code: Select all
Blob = class('Blob', Enemy) -- note the Enemy mention here
function Blob:initialize(x,y)
Enemy.initialize(self, x, y)
self.hp = 2
end
function Blob:draw()
-- Assuming that blobImage is loaded somewhere else
love.graphics.draw(blobImage, self.x, self.y)
end
First, I've changed the initialize method so it changes the initial hp of blobs to 2. But I'm still using the Enemy.initialize method for the "common Enemy creation parts" - in this case, setting up x and y.
Then I have overridden the default Enemy.draw implementation, which did nothing, with a Blob-specific one, which draws each blob on the coordinates it has (self.x, self.y).
You can create a Blob enemy by using Blob:new()
Code: Select all
local timmy = Blob:new(300, 400)
timmy:draw() -- draws it on 300, 400
timmy.x, timmy.y = 100, 200
timmy:draw() -- draws on 100, 200
It is also worth noting that timmy will also have inherited from Enemy the default update() and delete() methods; you could have overriden them if you wanted to.
This is completely extensible. For example, you could create a "FireBlob", as a subclass of Blob, with a different image, hp and update function. Or you could create a totally different Enemy subclass, called "Orc". An then add a "ShamanOrc". And so on.
This is with middleclass alone; with middleclass-extras you can do more stuff - for example automating the addition/deletion of all enemies to an "enemies" table using
Apply. But I hope this gives you a taste.