It looks like you're new here. If you want to get involved, click one of these buttons!
I made this button class after seeing @Brucewe project, wanted to personalize it and also make it simpler to make the button call a function (atleast I find it simple this way). So here's the code also added an example but what you need is only the Buttons tab.
--# Buttons
Buttons = class()
function Buttons:init(x,y,txt,funct,radius)
self.x = x
self.y = y
self.txt = txt
self.funct = funct
self.radius = radius
end
function Buttons:draw()
fill(140, 50, 238, 255)
fontSize(30)
font("AmericanTypewriter-Bold")
text(self.txt,self.x,self.y)
w = textSize(self.txt)
if self.radius == nil then
self.radius = w + 20
end
pushStyle()
noFill()
strokeWidth(5)
stroke(0, 114, 255, 198)
ellipse(self.x,self.y,self.radius)
end
function Buttons:touched(touch)
tx = touch.x
ty = touch.y
if touch.state == BEGAN then
if tx<=self.x + self.radius/2 and tx>=self.x - self.radius/2 and
ty>=self.y - self.radius/2 and ty<=self.y + self.radius/2 then
self.funct()
end
end
end
--# Functions
--the functions that the button will call when pressed
function Test()
print("button works")
end
function ChangePosition()
print("position changed")
sound(SOUND_HIT, 19021)
if x == WIDTH/2 then
x = WIDTH/2 + 200
else
x = WIDTH/2
end
end
--# Main
function setup()
x = WIDTH/2
b2 = Buttons(WIDTH/2 - 200,HEIGHT/2,"test",ChangePosition) --radius is set on its own
end
function draw()
background(0, 0, 0, 255)
b1 = Buttons(x,HEIGHT/2,"test",Test,100) --radius is user defined
b1:draw()
b2:draw()
end
function touched(touch)
b1:touched(touch)
b2:touched(touch)
end
Comments
very nice
Thanks!!
I am glad it helped.
Nice. Just an advice: you redefine (create) a new button object 60 times per second. (b1). This is not a good practice. You should define it in setup, as for b2, and change just the property you want to change in draw(). This will be very important for speed if you make bigger programs and bigger classes.
Yeah I realized that after writing a few of such codes and have edited all of them except for on the forum. Thanks anyways!!