Answered by
6 years ago Edited 6 years ago
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:
01 | local mouse = game.Players.LocalPlayer:GetMouse() |
10 | posX = math.floor(mouse.Hit.X / gridSize + 0.5 ) * gridSize |
12 | posZ = math.floor(mouse.Hit.Z / gridSize + 0.5 ) * gridSize |
15 | mouse.Move:Connect( function () |
18 | Part.Position = Vector 3. new(posX, posY, posZ) |
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:
01 | local mouse = game.Players.LocalPlayer:GetMouse() |
08 | posX = math.floor(mouse.Hit.X) |
10 | posZ = math.floor(mouse.Hit.Z) |
13 | mouse.Move:Connect( function () |
16 | Part.Position = Vector 3. new(posX, posY, posZ) |
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!