How do I make a GUI snap to grid relative to my mouse position

  1. What do I want to achieve?
    I want to move an image relative to my mouse position, but also snap it to grid.
    I am needing this because I’m making a game that you can place objects / blocks on a GUI.

    Here’s the GIF I would want to achieve:
    achieving

  2. What is the issue?
    I can’t seem to find a way since I’m new these 2D maths. I did my best but, unfornately it didn’t even work and this is always the output, they are not snapping to grid: problem

  3. What solutions have I tried so far?
    I tried setting the Image position from the GUI by the MouseX and MouseY then divided them by 32 and multiplied by 32. That’s the best solution I could think of, and yet still didn’t work.

Here is my source code:

local localPlayer = game.Players.LocalPlayer
local mouse = localPlayer:GetMouse()

mouse.Move:Connect(function()
	script.Parent.Position = UDim2.new(0, mouse.X, 0, mouse.Y)
end)
1 Like
local localPlayer = game.Players.LocalPlayer
local mouse = localPlayer:GetMouse()

local gridSize = 32

mouse.Move:Connect(function()
	script.Parent.Position = UDim2.fromOffset(math.floor(mouse.X/gridSize)*gridSize, math.floor(mouse.Y/gridSize)*gridSize)
end)

I’m assuming you just didn’t get rid of the decimal which is why it wouldn’t work when you tried something similar.

5 Likes