Skip to content

Instantly share code, notes, and snippets.

@appdojoStudios
Last active December 12, 2015 04:08
Show Gist options
  • Save appdojoStudios/4711944 to your computer and use it in GitHub Desktop.
Save appdojoStudios/4711944 to your computer and use it in GitHub Desktop.
--[[
Paste in main.lua then call the function with these parameters.
If anything doesn't make sense or there is code that could be shortened please comment!
And I will be adding sound and making it so everything can just not be used by putting nil.
-----FEATURES----
-Scaling when pressed
-Scaling size and time are editable
-Different Image for when button is pressed
-Change scene when button is pressed
-Do a different function that you can specify and you can remove the changeScene by just putting nil there
-----USAGE------
local button = displayNewButton(group, "image.png", "imageDown.png", 100, 250, true, 0.8, 250, "game", "Play", "Helvetica", 30, customFunction)
]]
function displayNewButton(group, image, imageDown, x, y, shouldScale, scaleX, timeToScale, sceneToGoTo, text, font, textSize, customFunction)
local btnGroup = display.newGroup()
group:insert(btnGroup)
local newBtn = display.newImage(image, 0, 0 )
btnGroup:insert(newBtn)
--newBtn.x = x
local overlayBtn
local btnText
newBtn.alpha = 1
local btnText
if text ~= nil then
newBtn.text = btnText
btnText = display.newText( text, newBtn.x, newBtn.y, font, textSize )
btnText.x, btnText.y = newBtn.x, newBtn.y - 5
btnGroup:insert(btnText)
end
local function onNewBtnTouch (event)
if event.phase == "began" then
if shouldScale == true then
transition.to(newBtn, {time=timeToScale, xScale = scaleX, yScale = scaleX})
transition.to(btnText, {time=timeToScale, xScale = scaleX, yScale = scaleX})
end
if imageDown ~= nil then
overlayBtn = display.newImage(btnGroup, imageDown, 0, 0)
btnGroup:insert(overlayBtn)
btnText:toFront()
btnText.alpha = 0.7
end
elseif event.phase == "ended" then
if customFunction ~= nil then
customFunction()
end
if shouldScale == true then
transition.to(newBtn, {time=timeToScale, xScale = 1, yScale = 1, onComplete=function()transition.cancel(newBtn) if sceneToGoTo ~= nil then director:changeScene(sceneToGoTo)end end})
transition.to(btnText, {time=timeToScale, xScale = 1, yScale = 1, onComplete=function()transition.cancel(newBtn) if sceneToGoTo ~= nil then director:changeScene(sceneToGoTo)end end})
elseif shouldScale == false then
if sceneToGoTo ~= nil then
if overlayBtn then
--btnGroup:removeSelf()
end
director:changeScene(sceneToGoTo)
end
end
end
end
newBtn:addEventListener("touch", onNewBtnTouch)
btnGroup.x = x
btnGroup.y = y
return btnGroup
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment