Skip to content

Instantly share code, notes, and snippets.

@nicloay
Last active March 23, 2019 20:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicloay/9b5c105bbdf96e134c55361ed8347ad7 to your computer and use it in GitHub Desktop.
Save nicloay/9b5c105bbdf96e134c55361ed8347ad7 to your computer and use it in GitHub Desktop.
Defold gui button which change scale on press event
local PRESSED_BUTTON_SCALE = vmath.vector3(1.15)
local NORMAL_BUTTON_SCALE = vmath.vector3(1)
local ANIMATION_TIME = 0.2
local Button = {}
Button.__index = Button
function Button.new(context, node_name, handler)
local self = setmetatable({}, Button)
assert(handler)
assert(node_name)
self.node = gui.get_node(node_name)
self.handler = handler
self.button_pressed = false
self.context = context
return self
end
function Button:press()
-- uncoment following line if you want to add sound (must be located on main collection "sound" game object and "click" sound controller
-- msg.post("main:/sound#click", "play_sound")
gui.animate(self.node, "scale", PRESSED_BUTTON_SCALE, gui.EASING_OUTBACK, ANIMATION_TIME)
self.button_pressed = true
end
function Button:release()
gui.animate(self.node, "scale", NORMAL_BUTTON_SCALE, gui.EASING_OUTBACK, ANIMATION_TIME)
self.button_pressed = false
end
function Button:on_input(action)
if action.pressed then
if gui.pick_node(self.node, action.x, action.y) then
self:press()
end
elseif action.released and self.button_pressed then
self:release()
if gui.pick_node(self.node, action.x, action.y) then
self.handler(self.context)
end
end
end
return Button
local Button = require("main.gui.button") -- change path to your location
function another_handler(self)
-- do something here
end
function init(self)
-- "facebook" and "another_button" is a nodes on your gui scene
self.fb_button = Button.new(self, "facebook", function() sys.open_url("https://www.facebook.com/pipler/") end)
self.another_button = Button.new(self, "another_button", another_handler)
end
function on_input(self, action_id, action)
-- make sure that you use ":" colon here, each button required personal on_input call
self.fb_button:on_input(action)
self.another_button:on_input(action)
end
@ReydVires
Copy link

Love this implementation, I have some change that play 2 sprite in animation that not always use scale to button for implementation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment