Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Define the Button class
- local Button = {}
- Button.__index = Button
- -- Constructor for creating a new Button object
- function Button.new(x, y, width, height, text, onClick)
- local self = setmetatable({}, Button)
- self.x = x
- self.y = y
- self.width = width
- self.height = height
- self.text = text
- self.onClick = onClick
- return self
- end
- -- Function to check if the button is clicked
- function Button:isClicked(mouseX, mouseY)
- return mouseX >= self.x and mouseX <= self.x + self.width and
- mouseY >= self.y and mouseY <= self.y + self.height
- end
- -- Function to handle click event
- function Button:handleClick(mouseX, mouseY)
- if self:isClicked(mouseX, mouseY) and self.onClick then
- self.onClick()
- end
- end
- -- Function to draw the button
- function Button:draw()
- love.graphics.setColor(0.5, 0.5, 0.5) -- Set button color
- love.graphics.rectangle('fill', self.x, self.y, self.width, self.height) -- Draw button
- love.graphics.setColor(1, 1, 1) -- Set text color
- love.graphics.printf(self.text, self.x, self.y + self.height / 2 - 10, self.width, 'center') -- Draw text
- end
- -- Example usage:
- -- Assume we have a love2d framework for graphics and input handling
- local button1
- function love.load()
- button1 = Button.new(100, 100, 200, 50, "Click me", function()
- print("Button clicked!")
- end)
- end
- function love.update(dt)
- -- Update logic here
- end
- function love.draw()
- button1:draw()
- end
- function love.mousepressed(x, y, button)
- button1:handleClick(x, y)
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement