I’m quite a beginner and I’m writing some test code, a very simple game, that requires to press some buttons.
In my draw function I have this:
function draw()
-- This sets a dark background color
background(223, 210, 175, 255)
-- Do your drawing here
fader:draw()
score:draw()
scene()
for i = 1, buttons.number do
buttons[i].state(i)
buttons[i].m:draw()
end
end
buttons[i].state is a pointer to another function like run or stop.
Here is an example of the run state:
function run(i)
buttons[i].m.shader.freq = freq
buttons[i].m.shader.time = buttons[i].m.shader.time + 0.25
if buttons[i].m.shader.time > 10 then
buttons[i].m.shader.freq = 0
end
if buttons[i].m.shader.time > 15 then
buttons[i].state = stop
buttons[i].m.shader.time = 0
print("button stopped = "..i)
end
end
Can I make a cleaner code? I don’t like that buttons[i].state[i]. Problem is that I have 6 different buttons.
function setup()
-- create your buttons in setup
for i=1,6 do
buttons[i] = Button(i)
end
end
function draw()
-- This sets a dark background color
background(223, 210, 175, 255)
-- Do your drawing here
fader:draw()
score:draw()
scene()
for i,b in pairs(buttons) do
b:state()
b.m:draw()
end
end
Button = class()
function Button:init(i)
self.i = i
end
function Button:run()
self.m.shader.freq = freq
self.m.shader.time = buttons[i].m.shader.time + 0.25
if self.m.shader.time > 10 then
self.m.shader.freq = 0
end
if self.m.shader.time > 15 then
self.state = stop
self.m.shader.time = 0
print("button stopped = "..self.i)
end
end
Thanks!
I did not post the entire code thinking it was too long. I’ll try with your advice and in case I’ll post the entire code if still in difficulty.
@Kotas I made a menu class that held a set of related buttons. I pass touch to the menu class and it handles which button was pressed and draws them accordingly. It then returns the index of which button was pressed that corresponds to the index that I put that button into the parameters for the menu instance, and then touch makes the required calls for what that button controls. Don’t know if this helped but good luck.
@Goatboy76 It’s very similar to what I need. I’ll try to structure based on your suggestion. This is for me a good way to make practive and understand better the language.