
Share Your Code
Browse Code
- All (907)
-
(94)
-
(85)
-
(44)
-
(4)
-
(42)
-
(137)
-
(21)
-
(41)
-
(13)
-
(65)
-
(151)
-
(210)
Basic drawing code
This is a very simply point drawing piece of code. Click on the simulator to create dots. Each new dot is joined to the last by a line. The length of the line is displayed next to it. The dots can be dragged and the first dot is green. Tap a dot to remove it.
main.lua:
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 | local stage = display.getCurrentStage() local dots, lines = display.newGroup(), display.newGroup() local points = {} function lengthOf( a, b ) local width, height = b.x-a.x, b.y-a.y return math.sqrt(width*width + height*height) end function drawLine( a, b ) local line = display.newLine( lines, a.x, a.y, b.x, b.y ) line:setColor( 0,0,255 ) line.width = 2 local myText = display.newText(lines, math.round(lengthOf(a,b)), (a.x+b.x)/2, (a.y+b.y)/2, native.systemFont, 16) myText:setTextColor(255, 255, 255) end function render() lines:removeSelf() lines = display.newGroup() if (#points > 1) then for i=2, #points do drawLine( points[i-1], points[i] ) end drawLine( points[1], points[#points] ) end end function createPoint( event ) local point = display.newCircle( dots, event.x, event.y, 12 ) if (#points == 0) then point:setFillColor( 0,255,0 ) else point:setFillColor( 255,0,0 ) end function point:touch(event) if (event.phase == "began") then stage:setFocus( point, event.id ) point.x, point.y = event.x, event.y elseif (event.phase == "moved") then point.x, point.y = event.x, event.y else stage:setFocus( point, nil ) end render() return true end function point:tap(event) for i=1, #points do if (points[i] == point) then table.remove( points, i ) end end point:removeSelf() point = nil render() return true end points[ #points+1 ] = point render() point:addEventListener("touch", point) point:addEventListener("tap", point) return true end Runtime:addEventListener("tap", createPoint) |
Replies
Posted on Thu, 2012-01-12 10:23
#2
please test code before post, don't work.
error: Runtime error
bad argument #1 to '_newCircle' (number expected, got nil)
stack traceback:
Posted on Fri, 2012-01-13 00:29
#3
Crikey - sorry about that - overzealous editing just prior to posting, I'm afraid...
Fixed now :)
Posted on Sun, 2012-02-05 15:54
#4
Very nice! Works great thank you :)


Nice. Thank you for sharing!
Naomi