I have a grid of imagebuttons, I am trying to make them detect the closest 9 (3x3) other UI elements, I’ve tried calculating the positions, maybe I was just wrong, maybe there’s an easier way, any help is appreciated.
One way to do this considering it’s a grid of UI elements is to name them according to their grid positions. “X:Y” for example. To get the closest surrounding elements from that UI element, first get the name of that UI element, then index the other ones by name.
Assuming there are no missing cells in your grid, this should work. Otherwise, replace the [X..":"..Y]
with :FindFirstChild(X..":"..Y)
.
local MinX: number = 1
local MinY: number = 1
local MaxX: number = (Max number of cells X axis)
local MaxY: number = (Max number of cells Y axis)
local FromX, FromY = SelectedUI.Name:match("(%d+):(%d+)")
FromX = tonumber(FromX); FromY = tonumber(FromY)
for X = math.max(FromX - 1, MinX), math.min(FromX + 1, MaxX) do
for Y = math.max(FromY - 1, MinY), math.min(FromY + 1, MaxY) do
local OtherUI = GUI[X..":"..Y] -- Guaranteed to be there if all cells in bounds exist
if SelectedUI ~= OtherUI then
-- Do what you want here
end
end
end
I hope this helps!
In theory this would be perfect however I have one small hangup, I have no way to round udim2 values down as my buttons are looking like this
I’ve tried converting and then trying math.floor but still nothing, is my knowledge just too limited to know an easy solution to this?
Assuming the increments are 0.05, you’d multiply that by 20 to get the cell number and math.round should fix any float point precision issue since it’ll be an integer. Once you get the rounded number, then you can set the names accordingly.
UI.Name = math.round(UI.Position.X.Scale * 20)..":"..math.round(UI.Position.Y.Scale * 20)