Advertisement
alestane

button.lua

Feb 7th, 2012
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.49 KB | None | 0 0
  1. local button = {}
  2.  
  3. local function trackButton(event)
  4.     local button = event.target
  5.     if event.phase == "began" then
  6.         display.getCurrentStage():setFocus(button)
  7.         button._isFocused = true
  8.         button._down = true
  9.         button:dispatchEvent{name='Button.State'; target=button, down=true}
  10.     elseif button._isFocused then
  11.         if event.phase == "moved" then
  12.             local bounds = button.contentBounds
  13.             local isWithinBounds = bounds.xMin <= event.x and bounds.xMax >= event.x and bounds.yMin <= event.y and bounds.yMax >= event.y
  14.             if isWithinBounds ~= button._down then
  15.                 button._down = isWithinBounds
  16.                 button:dispatchEvent{name='Button.State'; target=button, down=button._down}
  17.             end
  18.         elseif event.phase == "ended" or event.phase == "cancelled" then
  19.             button:dispatchEvent{name='Button.State'; target=button, down=false}
  20.             button:dispatchEvent{name='Button'; target=button, activate=button._down and event.phase == "ended"}
  21.             display.getCurrentStage():setFocus(button, nil)
  22.             button._down = nil
  23.             button._isFocused = nil
  24.         end
  25.     end
  26.     return true
  27. end
  28.  
  29. function button.new(object)
  30.     object:addEventListener('touch', trackButton)
  31. end
  32.  
  33. local function spriteButton(event)
  34.     event.target.currentFrame = event.down and 2 or 1
  35. end
  36.  
  37. function button.sprite(object)
  38.     object = button.new(object)
  39.     object:addEventListener('Button.State', spriteButton)
  40.     return object
  41. end
  42.  
  43. return button
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement