jesterxl

Corona SDK Touch Joint Example

Feb 16th, 2012
472
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.75 KB | None | 0 0
  1. require "physics"
  2. physics.start()
  3. physics.setGravity(0, 9.8)
  4. physics.setDrawMode("hybrid")
  5.  
  6. stage = display.getCurrentStage()
  7.  
  8. function getWall(x, y, width, height)
  9.     local wall = display.newRect( x, y, width, height)
  10.     wall:setFillColor( 255, 0, 0, 100)
  11.     physics.addBody(wall, "static", { friction=0.5, bounce=0.0, density=2 } )
  12.     return wall
  13. end
  14.  
  15. function getBall(x, y, radius, type, props)
  16.     if props == nil then
  17.         props = {density=0.3, friction=0.3, bounce=0.3}
  18.     end
  19.     local ball = display.newCircle(x, y, radius)
  20.     ball:setFillColor(0, 255, 0)
  21.     physics.addBody(ball, props)
  22.     return ball
  23. end
  24.  
  25. floor = getWall(0, 460, 320, 20)
  26. leftWall = getWall(0, 0, 20, 500)
  27. rightWall = getWall(320, 0, 20, 500)
  28. roof = getWall(0, 0, 460, 20)
  29.  
  30. ball1 = getBall(100, 100, 10, {density=0.3, friction=0.3, bounce=2})
  31. ball2 = getBall(200, 150, 10, {density=0.3, friction=0.3, bounce=2})
  32.  
  33. touchJoint = nil
  34.  
  35. function onTouch(event)
  36.     print(tostring(system.getTimer()) .. " phase: ", event.phase)
  37.     if event.phase == "began" then
  38.         dragging = true
  39.         stage:setFocus(ball1)
  40.         ball1.bodyType = "kinetic"
  41.         if touchJoint then
  42.             touchJoint:removeSelf()
  43.         end
  44.         touchJoint = physics.newJoint( "touch", ball1, event.x, event.y )
  45.         --touchJoint.maxForce = 10000000
  46.         touchJoint.frequency = 0.5
  47.         touchJoint.dampingRatio = 0
  48.         return true
  49.     elseif event.phase == "moved" then
  50.         if dragging == false then return false end
  51.         touchJoint:setTarget(event.x, event.y)
  52.         return true
  53.     elseif event.phase == "ended" or event.phase == "cancelled" then
  54.         if dragging == true then
  55.             dragging = false
  56.             ball1.bodyType = "dynamic"
  57.             touchJoint:removeSelf()
  58.             touchJoint = nil
  59.             return true
  60.         else
  61.             return false
  62.         end
  63.     end
  64. end
  65.  
  66.  
  67. Runtime:addEventListener("touch", onTouch)
Advertisement
Add Comment
Please, Sign In to add comment