Page 1 of 1
Looping through a table and calculating distance
Posted: Tue Mar 15, 2022 6:50 am
by HarshKnarsh
I've been making a little program that allows the user to draw lines by clicking with the mouse with the ability to close them off with lctrl, making polygons. I do this by inserting the x and y position of the cursor into a table that I then pass into love.graphics.line(). I thought it would be cool if I could move the vertices around after they were drawn, so I looped through the table with ipairs() when the user presses tab, calculating the distance each vertex is from the mouse, and then setting the position of the vertex to the mouse if the distance is less than 50. The results look cool, but are absolutely not what I was going for. I've tried tweaking what I've got for a while, but it usually just ends up doing more of the same thing. At this point, I'm kinda stumped. Hopefully you guys can nudge me in the right direction!
I'll attach the .love if anyone wants to see some seriously nasty code.
Re: Looping through a table and calculating distance
Posted: Tue Mar 15, 2022 10:18 pm
by darkfrei
Just store the line in the list as {{x=x1, y=y1}, {x=x2, y=y2}, {x=x3, y=y3}}.
When the user ends this new line / polygon, convert it to the Löve's list as line / vertices as {x1, y1, x2, y2, x3, y3}.
Re: Looping through a table and calculating distance
Posted: Thu Mar 17, 2022 1:57 am
by pgimeno
I disagree with darkfrei; it's far less expensive in terms of memory and objects to keep the list flat like you do. The problem is that the list is made of x, y, x, y, x, y... but ipairs() iterates over each item, not over each pair of items. Just replace the `for i in ipairs(vertices) do` with this:
Now, vertices[
i] is the x coordinate, and vertices[i + 1] is the y coordinate. Replace them inside the loop so that the y coordinate appears as vertices[i + 1] and it will work, somewhat.
Re: Looping through a table and calculating distance
Posted: Thu Mar 17, 2022 2:28 am
by HarshKnarsh
That did it, thanks! I just kept trying to use pairs() and ipairs() that I never stopped to realize they didn't work in that scenario.
Re: Looping through a table and calculating distance
Posted: Thu Mar 17, 2022 8:26 am
by darkfrei
Yes, this position tables {x=x, y=y} needs a much more memory, but it's not a problem before thousands and thousands of them. If you have just only one line in this notation, it will be buch easier to manipulate this data structure (for you as coder) and when you are ready with that line, just convert it to the flat positions pairs list to store them.
Code: Select all
function toFlat (tabl)
local list = {}
for i, v in ipairs (tabl) do
table.insert (list , v.x)
table.insert (list , v.y)
end
return list
end
Code: Select all
function fromFlat (list)
local tabl = {}
for i = 1, #list -1, 2 do
table.insert (tabl, {x=list [i], y=list [i+1]}
end
return tabl
end