Hi, I was wondering if there was any way to snap a part to the closest position in a table. I have made a table with a bunch of different positions, and I want to be able to drag the part around and have it always snap to the closest one. I think I could do this with a for loop, rotating through the positions and finding the closest one, but I am not quite sure how it might work. Also, I want this to happen whenever the mouse moves, so maybe there is a simpler solution. Thank you in advance for your help.
Is there a pattern to the the table? This might be easier to do with math if so.
You can just use a minimum algorithm using the .Magnitude property of the subtraction of the two thingies like so:
local position = --whatever you're snapping
local newPosition = tabl[1]
local min = (tabl[1]-position).Magnitude
for i = 2,#tabl do
local dist = (tabl[i]-position).Magnitude
if dist < min then --find the local minimum from index=1 to index=i
min = dist
newPosition = tabl[i]
end
end
print(newPosition)
You probably could simplify it but this code I would say is small enough that this is fine
It’s just a grid, all the positions are 11 studs apart.
If that’s the case, it should be a lot more efficient to do some math and rounding. Does the grid have 0 rotation? If so, it’s as easy as this.
local xGrid = math.round(xPos/11)*11
local yGrid = math.round(yPos/11)*11
I suppose I should also mention that xPos and yPos are the positions on the grid. You might need to subtract the position of a corner of the grid from the mouse position to make this work.
That is much easier than what I was thinking, just took a bit of tweaking to make it align and not go outside the grid. Thank you for your help.
You can use this formula to push to the nearest multiple(basiclly rounding).
local result = input - (input % 11)
That works great, although I forgot I could just round it. I will use this in the future as well though. Thank you for your help
One more thing. This is a good example of the XY Problem. Essentially, it’s what happens when you ask a question about how to do something specific, when the issue itself is more broad. For future reference, you will get a lot more out of a question by wording it something like this so that it includes the general problem as well as your specific approach:
I’m trying to align placement of parts to a grid with 11 stud spacing. My current approach is to store the points in a table, and my issue with that is working out an efficient way to find the closest point in the table.
This way, I can just tell you the best ways I know of to align things to a grid. Or, if I think you’re on the right track, I can help with the table issue. The more people who learn to ask questions which satisfy the XY Problem, the better.