✓ Accepted answer
Fixing bugs
First off Mouse.Hit.Position.X is incorrect. You should write it like this: Mouse.Hit.X this will return the x axis of the mouse position. You need to do this for the z as well. If you want to return the position on all axis use Mouse.Hit.p.
Snapping to grid
You can divide the mouse position by your grid size and round it up or down and then multiply it by grid size to snap to a grid. For rounding you can use math.floor() and math.ceil(). Floor rounds down and ceil rounds up. In this case it does not matter which one you use. I will use floor.
Example:
local mouse = game.Players.LocalPlayer:GetMouse()
local posX
local posY
local posZ
local gridSize = 1
local function Snap()
posX = math.floor(mouse.Hit.X / gridSize + 0.5) * gridSize
posY = mouse.Hit.Y
posZ = math.floor(mouse.Hit.Z / gridSize + 0.5) * gridSize
end
mouse.Move:Connect(function()
Snap()
Part.Position = Vector3.new(posX, posY, posZ)
end
Since you are snapping to a 1x1x1 grid you only have to round down (or up). I just showed you the above because in the future you may want a bigger grid. Here's the simpler way:
local mouse = game.Players.LocalPlayer:GetMouse()
local posX
local posY
local posZ
local function Snap()
posX = math.floor(mouse.Hit.X)
posY = mouse.Hit.Y
posZ = math.floor(mouse.Hit.Z)
end
mouse.Move:Connect(function()
Snap()
Part.Position = Vector3.new(posX, posY, posZ)
end
One other thing is you may not want to move the mouse using the Move event. Instead use RunService.
End
The only down side to this way is you cannot add studs to it.
Hope this helps!
2 comments
Round it to the nearest stud, egomoose actually made a really good tutorial on this recently callled creating a furniture placement system
Also, i would use runservice instead of a while loop