Advertisement
psicubed

Untitled

May 12th, 2024
649
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.57 KB | None | 0 0
  1. -- Define the Button class
  2. local Button = {}
  3. Button.__index = Button
  4.  
  5. -- Constructor for creating a new Button object
  6. function Button.new(x, y, width, height, text, onClick)
  7.     local self = setmetatable({}, Button)
  8.     self.x = x
  9.     self.y = y
  10.     self.width = width
  11.     self.height = height
  12.     self.text = text
  13.     self.onClick = onClick
  14.     return self
  15. end
  16.  
  17. -- Function to check if the button is clicked
  18. function Button:isClicked(mouseX, mouseY)
  19.     return mouseX >= self.x and mouseX <= self.x + self.width and
  20.            mouseY >= self.y and mouseY <= self.y + self.height
  21. end
  22.  
  23. -- Function to handle click event
  24. function Button:handleClick(mouseX, mouseY)
  25.     if self:isClicked(mouseX, mouseY) and self.onClick then
  26.         self.onClick()
  27.     end
  28. end
  29.  
  30. -- Function to draw the button
  31. function Button:draw()
  32.     love.graphics.setColor(0.5, 0.5, 0.5) -- Set button color
  33.     love.graphics.rectangle('fill', self.x, self.y, self.width, self.height) -- Draw button
  34.     love.graphics.setColor(1, 1, 1) -- Set text color
  35.     love.graphics.printf(self.text, self.x, self.y + self.height / 2 - 10, self.width, 'center') -- Draw text
  36. end
  37.  
  38. -- Example usage:
  39. -- Assume we have a love2d framework for graphics and input handling
  40.  
  41. local button1
  42.  
  43. function love.load()
  44.     button1 = Button.new(100, 100, 200, 50, "Click me", function()
  45.         print("Button clicked!")
  46.     end)
  47. end
  48.  
  49. function love.update(dt)
  50.     -- Update logic here
  51. end
  52.  
  53. function love.draw()
  54.     button1:draw()
  55. end
  56.  
  57. function love.mousepressed(x, y, button)
  58.     button1:handleClick(x, y)
  59. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement