Maybe every 25% of the things I try to add work out the same way. Most things I add are small, and sometimes create errors, but every here and there I add a bit thing and it can take me up to a few days to debug it and eventually revert to its original state after I rage about how I can’t figure out why it’s not working.
And, as for classes, it could be all in the main loop, but classes make things a lot easier and cleaner. For instance, if you’re making a game, and want to have multiple enemies of the same type, you can create a class for them that handles initializing, drawing, getting touched, possibly when a key on the keyboard is pressed, the orientation is changed, or there’s a physics collision. And it’s all kept away in a separate tab so you don’t have 2K lines in your main tab and you don’t have to look at it. I’m not joking about the 2K lines, by the way. And you can keep all the instances of that class in a table, and whenever you call draw() or touched(touch) or whatever, you can just say
for k, v in pairs(entities) do
v:draw()
end
or whatever. It just looks a bit nicer and takes up less lines of code. As for how they work…
--# exampleClass
exampleClass = class() -- Create a class.
function exampleClass:init(x, y) -- Initialize exampleClass with two variables: x and y.
self.x, self.y = x, y -- Set them as variables in our class.
end
function exampleClass:draw() -- Seperate draw function.
sprite("Cargo Bot:Codea Icon", self.x, self.y) -- Draw the Codea icon at our variables, x and y.
end
function exampleClass:hello()
print("Hello World!")
end
--# myClass
myClass = class(exampleClass) -- Create another class, that inherits all the functions of exampleClass.
function myClass:init()
exampleClass.init(self, WIDTH / 2, HEIGHT / 2) -- Call the init function from exampleClass, with the instance as self.
self:hello() -- Call the hello function, inherited from exampleClass.
end
function myClass:draw()
exampleClass.draw(self) -- Call the draw function from exampleClass, with the instance as self.
text("Hello World!", WIDTH / 2, 200) -- Draw some text, after drawing from the superclass.
end
--# Main
-- Classes
function setup()
class = myClass() -- Initialize a new instance of our class.
end
function draw()
background(255, 255, 255, 255)
fill(0)
class:draw() -- Have our class instance handle its own drawing.
end
I think that was fairly well commented. You can paste into a project with the correct tabs by copying that and long pressing on add new project, and selecting paste into project.
This message would have come sooner, but my cat came along and meowed very loudly, demanding to be pet.