Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Code 03 - Button Extended
- -- Can be uploaded to Codea
- -- uses code by David Such
- -- Bruce Elliott
- -- April 2013
- -- Button returns its label when pressed
- --# Button
- Button = class()
- function Button:init(displayName)
- -- you can accept and set
- -- parameters here
- self.displayName = displayName
- self.pos = vec2(0,0)
- self.size = vec2(0,0)
- self.action = nil
- self.color = color(68, 65, 190, 255)
- end
- function Button:draw()
- -- Codea does not automatically
- -- Determine button size based on displayName
- -- Draw the button (uses rect)
- -- Use text to draw text on button
- pushStyle()
- fill(self.color)
- font("ArialRoundedMTBold")
- fontSize(22)
- local w, h = textSize(self.displayName)
- w = w + 20
- h = h + 20
- rect(self.pos.x - w/2,
- self.pos.y - h/2,
- w, h)
- self.size = vec2(w, h)
- textMode(CENTER)
- fill(54,65,96,255)
- text(self.displayName,
- self.pos.x, self.pos.y)
- popStyle()
- end
- function Button:hit(p)
- -- Accepts p - x and y of the touch
- -- Button knows its position
- -- If touch is inside button return true
- -- otherwise return false
- local l = self.pos.x - self.pos.x/2
- local r = self.pos.x + self.pos.x/2
- local t = self.pos.y + self.pos.y/2
- local b = self.pos.y - self.pos.y/2
- if p.x > l and p.x < r
- and p.y > b and p.y < t then
- return true
- end
- return false
- end
- function Button:touched(touch)
- -- if touch has ended and the touch was on the button
- -- set newName and call action
- if touch.state == ENDED and
- self:hit(vec2(touch.x, touch.y)) then
- if self.action then
- newName = self.displayName
- self.action()
- end
- end
- end
- function Button:action()
- -- call buttonPressed in main to display newName
- buttonPressed(newName)
- end
- --# Main
- -- ButtonDemo
- -- Use this function to perform
- -- our initial setup
- function setup()
- -- Create button with a name
- print("Button Test Project")
- button = Button("Test")
- end
- -- This function gets called once every frame
- function draw()
- -- calls drawButton to put button on screen
- -- This sets a dark background color
- background(0)
- -- This sets the line thickness
- -- strokeWidth(5)
- -- Do your drawing here
- drawButton()
- end
- function drawButton()
- -- set button position
- -- call button draw
- button.pos = vec2(400, HEIGHT/2)
- button:draw()
- end
- function touched(touch)
- -- if touched call button:touched
- button:touched(touch)
- end
- function buttonPressed(keyName)
- -- display button name if it was pressed
- print("Button: "..keyName)
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement