Love Object Orientated Programming
Posted: Wed Sep 01, 2010 3:41 am
I've decided to assign myself the project of developing Object Orientated classes (theoretically) for the Love 2D Engine. I believe that all games should be done with Object Orientation because it usually just makes the tasks a thousand times easier. To create what would be a class in lua you actaully use a table. And define it as the name of what you want your class. Then you simply write a function to create your class and a more functions to be used with it. Surprisingly simple. But at the same time - strangely harder than object orientation in most other langauges (IMO).
My first class that i've developed was my Image class.
I proceeded to derive from that class (once again theorectically) to make my sprite class and replicate the 'Hamster Ball' only without key movement. it just rolls off the screen. I hope to work to create even more classes and spread my classes throughout the community.
The Code Below Is Still Under Testing!
To those of you who don't know much about Object Orientated Programming this probably looks longer and unnecessary but with the use of objects you can create new functions that will work for themselves and add them multiple times without creating a million new definitions.
ex. I could have a table filled with my Sprite Class and just run through the table rather than each sprite class over and over.
My first class that i've developed was my Image class.
I proceeded to derive from that class (once again theorectically) to make my sprite class and replicate the 'Hamster Ball' only without key movement. it just rolls off the screen. I hope to work to create even more classes and spread my classes throughout the community.
The Code Below Is Still Under Testing!
Code: Select all
-- Love OO Library Class Sets
Image = {} -- Create a table to hold the class methods
function Image:Create(filepath) -- The constructor
local object = { img = love.graphics.newImage(filepath) }
setmetatable(object, { __index = Image }) -- Inheritance
return object
end
function Image:Draw(x,y)
love.graphics.draw(self.img,x,y)
end
-- Sprite
Sprite = {} -- Create a table to hold the class methods
function Sprite:Create(filepath) -- The constructor
local object = { img = Image:Create(filepath), x = 0,y = 0 }
setmetatable(object, { __index = Sprite }) -- Inheritance
return object
end
function Sprite:Update(xacc,yacc)
self.x = self.x+xacc
self.y = self.y+yacc
end
-- Using this as a test.
-- Tutorial 1: Hamster Ball
-- Add an image to the game and move it around using
-- the arrow keys.
-- compatible with löve 0.6.0
function love.load()
hamster = Sprite:Create("ball.png")
end
function love.update(dt)
hamster:Update(1,1)
end
function love.draw()
hamster.img:Draw(hamster.x,hamster.y)
end
ex. I could have a table filled with my Sprite Class and just run through the table rather than each sprite class over and over.