Hi all,
Below you can find my take on a function for drawing dashed lines. Now I’m just curious if any of you perhaps know a shorter, more efficient way of doing this?
function draw()
background(255)
xx,yy = CurrentTouch.x,CurrentTouch.y+50
noStroke()
fill(255, 0, 0, 255)
ellipse(xx, yy, 20)
stroke(0)
strokeWidth(4)
lineCapMode(SQUARE)
dashed(0,0,xx,yy, 20)
end
function dashed(x1, y1, x2, y2, seg)
local length = math.sqrt((x2-x1)^2 + (y2-y1)^2)
-- n, integer number of segements in length
local n = math.floor(length/seg)
local angle = math.atan((y2-y1)/(x2-x1))
-- dx, dy, leftover length shorter than segmentsize seg
local dx = (length-n*seg)*math.cos(angle)
local dy = (length-n*seg)*math.sin(angle)
local u1,v1,u2,v2
if length-n*seg>=seg/2 then
-- Draw extra segment if leftover is long enough
m = 1
else
-- Else, draw a shorter ending segment
m = 0
u1 = x1 + (x2-x1-dx)
v1 = y1 + (y2-y1-dy)
u2,v2 = x2,y2
line(u1,v1,u2,v2)
end
-- Draw all the line segments
for i = 0,n-1+m do
u1 = x1 + i/n*(x2-x1-dx)
v1 = y1 + i/n*(y2-y1-dy)
u2 = x1 + (i+.5)/n*(x2-x1-dx)
v2 = y1 + (i+.5)/n*(y2-y1-dy)
line(u1,v1,u2,v2)
end
end