
Share Your Code
Browse Code
- All (907)
-
(94)
-
(85)
-
(44)
-
(4)
-
(42)
-
(137)
-
(21)
-
(41)
-
(13)
-
(65)
-
(151)
-
(210)
Track Velocity
This code sample creates a circle that bounces off the edges of the screen. You can touch the circle and throw it around. It tracks velocity. When the user touches the circle and starts moving it, the change in distance over time is captured and given to the circle as it's new speed when the user lets go.
Code
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 | local screenW, screenH = display.stageWidth, display.stageHeight local friction = 0.8 local gravity = .9 local speedX, speedY = 0, 0 local prevX, prevY = 0, 0 local ball = display.newCircle( 0, 0, 25) ball:setFillColor(255, 255, 0) ball.x = screenW*.5 ball.y = 20 function onMoveCircle(event) speedY = speedY + gravity ball.x = ball.x + speedX ball.y = ball.y + speedY 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 end if( 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 display.getCurrentStage():setFocus( nil ) t.isFocus = false Runtime:removeEventListener("enterFrame", trackVelocity) Runtime:addEventListener("enterFrame", onMoveCircle) end end -- Stop further propagation of touch event! return true end function trackVelocity() speedX = ball.x - prevX speedY = ball.y - prevY prevX = ball.x prevY = ball.y end ball:addEventListener("touch", startDrag) Runtime:addEventListener("enterFrame", onMoveCircle) |
Compatibility:
Corona 1.0
- Type:
- Tags:

Thanks a lot for this. Just what I was looking for!