Here is Bresenham's line algorithm in Lua/Corona if anyone is interested...
A few points:
1) It can probably be optimized, so maybe one of your Lua/Corona developers who eek out an extra bit of performance.
2) It uses display.newCircle and maybe display.newRect would be faster
3) The group llGroup is used to store all the points plotted so they can be deleted when necessary.
1 2 3 4 5 6 | local function swap(a,b) local temp = b b = a a = temp return a, b end |
1 2 3 4 | -- Bresenham's line algorithm local function drawLine(x0, y0, x1, y1) local steep = false if math.abs(y1 - y0) > math.abs(x1 - x0) then steep = true end |
1 2 3 4 | if steep then x0, y0 = swap(x0, y0) x1, y1 = swap(x1, y1) end |
1 2 3 4 5 | if x0 > x1 then x0, x1 = swap(x0, x1) y0, y1 = swap(y0, y1) end |
1 2 3 4 5 6 | local deltax = x1 - x0 local deltay = math.abs(y1 - y0) local err = deltax / 2 local ystep = 0 local y = y0 if y0 < y1 then ystep = 1 else ystep = -1 end |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | for x=x0,x1 do if steep then local c = display.newCircle( y, x, 2 ) c:setFillColor(0,0,0) llGroup:insert(c) else local c = display.newCircle( x, y, 2 ) c:setFillColor(0,0,0) llGroup:insert(c) end err = err - deltay if err < 0 then y = y + ystep err = err + deltax end end end |
Thanks,
Gary
afyzendo,
Thanks... I have updated my original post and now the code appears as expected.
Many thanks,
Gary
One handy thing you can do in lua is swap variables really easily.
a, b = b, a
will perform the swap for you.
Scott
Thanks for the script. This line algo will become usefull for me in the future!
You have to end the code tag and start it again if you want to have an empty line in your code. Took me a while to figure that out.