前言
絕大部分的應用,都會需要 Button,但在 LÖVE 沒有內建的 Button,因此需要自己實作。
範例程式下載
情境說明
左上角建立了三個 Button,都會偵測 hover 事件;上面兩個 Button 按下去時,會在畫面中央印出 Button 上面的文字,而 Clear Button 按下去的時候,將會清除畫面中央的文字。
Screenshot
程式碼(都在範例檔案內)
main.lua
require("lua/button.lua")function love.load()
text = ""
-- 可在建立 Button 時宣告屬性 buttons = { button1 = Button.create("Hello"), button2 = Button.create("World", {y = 20,
fontcolor = {255, 0, 0}}),
button3 = Button.create("Clear", {y = 40,
font = love.graphics.newFont(15),
fontcolor = {0, 255, 0}})
}
buttons.button2.text = "HELLO WORLD" -- 也可隨時調整文字endfunction love.update(dt)
-- 主要畫面更新資訊時,也一併更新所有 button 的資訊for dummy, button in pairs(buttons) do
button:update(dt) endendfunction love.mousepressed(x, y, button) -- 按下滑鼠按鍵時,將資訊傳給 Button:mousepressed 做判斷,可得知是否觸發 pressif buttons.button1:mousepressed(x, y, button) then
text = text .. buttons.button1.text .. "\n"
endif buttons.button2:mousepressed(x, y, button) then
text = text .. buttons.button2.text .. "\n"
endif buttons.button3:mousepressed(x, y, button) then
text = ""
endendfunction love.draw() -- 繪製主要畫面時,也一併繪製所有的 Buttonfor dummy, button in pairs(buttons) do
button:draw()
endlove.graphics.setColor(255, 255, 255)
-- 如果 Button hover 狀態為 true,顯示文字在 (600, 0) 的地方for dummy, button in pairs(buttons) do
if button.hover then love.graphics.print(button.text .. " hover", 600, 0) end
end love.graphics.print(text, 400, 0)endlua/button.lua
Button = {}Button.__index = Button
function Button.create(text, attributes)
attrs = attributes or {} local button = {}setmetatable(button, Button)
-- hover 狀態紀錄,會隨時更新,不可設定 button.hover = false -- 可設定的屬性,除 text 外皆有 default 值button.text = text
button.x = attrs.x or 0 button.y = attrs.y or 0 button.font = attrs.font or love.graphics.newFont(12) button.fontcolor = attrs.fontcolor or {255, 255, 255} return buttonendfunction Button:update(dt)
-- 動態更新 Button 的寬與高self.width = self.font:getWidth(self.text)
self.height = self.font:getHeight()
-- 抓取滑鼠座標 local x, y = love.mouse.getPosition() -- 滑鼠座標落在 Button 內,將 hover 狀態更新為 true 反之為 falseif x > self.x and x < self.x + self.width and
y > self.y and y < self.y + self.height then
self.hover = true else self.hover = false endendfunction Button:mousepressed(x, y, button) -- hover 狀態為 true,此時偵測到滑鼠按鍵按下,才會回傳 true 反之為 falseif self.hover then
return true
elsereturn false
endendfunction Button:draw()love.graphics.setFont(self.font)
love.graphics.setColor(self.fontcolor)
love.graphics.print(self.text, self.x, self.y)end
沒有留言:
張貼留言