1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | local screenW, screenH = display.contentWidth, display.contentHeight local friction = 0.8 local gravity = .09 local speedX, speedY, prevX, prevY, lastTime, prevTime = 0, 0, 0, 0, 0, 0 local background = display.newImage( "metal_bg.png", true ) background.x = screenW / 2 background.y = screenH / 2 local infoLabel = display.newText( "Drag or fling ball to bounce", 0, 0, native.systemFontBold, 20 ) infoLabel:setTextColor( 0, 0, 0 ) infoLabel.x = screenW / 2 infoLabel.y = 60 local ball = display.newCircle( 0, 0, 40) ball:setFillColor(255, 255, 255, 166) ball.x = screenW * 0.5 ball.y = ball.height function onMoveCircle(event) local timePassed = event.time - lastTime lastTime = lastTime + timePassed speedY = speedY + gravity ball.x = ball.x + speedX*timePassed ball.y = ball.y + speedY*timePassed if ball.x >= screenW - ball.width*.5 then ball.x = screenW - ball.width*.5 speedX = speedX*friction speedX = speedX*-1 --change direction elseif ball.x <= ball.width*.5 then ball.x = ball.width*.5 speedX = speedX*friction speedX = speedX*-1 --change direction elseif ball.y >= screenH - ball.height*.5 then ball.y = screenH - ball.height*.5 speedY = speedY*friction speedX = speedX*friction speedY = speedY*-1 --change direction elseif ball.y <= ball.height*.5 then ball.y = ball.height*.5 speedY = speedY*friction speedY = speedY*-1 --change direction end end -- A general function for dragging objects local function startDrag( event ) local t = event.target local phase = event.phase if "began" == phase then display.getCurrentStage():setFocus( t ) t.isFocus = true -- Store initial position t.x0 = event.x - t.x t.y0 = event.y - t.y -- Stop current motion, if any Runtime:removeEventListener("enterFrame", onMoveCircle) -- Start tracking velocity Runtime:addEventListener("enterFrame", trackVelocity) elseif t.isFocus then if "moved" == phase then t.x = event.x - t.x0 t.y = event.y - t.y0 elseif "ended" == phase or "cancelled" == phase then lastTime = event.time Runtime:removeEventListener("enterFrame", trackVelocity) Runtime:addEventListener("enterFrame", onMoveCircle) display.getCurrentStage():setFocus( nil ) t.isFocus = false end end -- Stop further propagation of touch event! return true end function trackVelocity(event) local timePassed = event.time - prevTime prevTime = prevTime + timePassed speedX = (ball.x - prevX)/timePassed speedY = (ball.y - prevY)/timePassed prevX = ball.x prevY = ball.y end ball:addEventListener("touch", startDrag) Runtime:addEventListener("enterFrame", onMoveCircle) |