Answered by
6 years ago Edited 6 years ago
I know this is a year old but I thought I could help anyway.
First you want to create a function
to do the movement. To move a part to the mouse position you use Mouse.Hit
. I am creating three variables one for each axis. Also I am creating two functions that will be used later on in the script. Make a simple model with a primary part so that we can move the model around in our space.
02 | local Player = game.Players.LocalPlayer |
03 | local Mouse = Player:GetMouse() |
09 | local Model = game.ReplicatedStorage.Model:Clone() |
21 | local function Movement() |
22 | Mouse.TargetFilter = Model |
26 | Model:SetPrimaryPartCFrame(CFrame.new(PosX, PosY, PosZ)) |
30 | local function StartPlacement() |
31 | Model.Parent = workspace |
34 | game.Players.PlayerAdded:Connect(StartPlacement) |
To snap to a grid we round either up or down to the nearest whole. math.floor()
and math.ceil()
will work for snapping. math.floor() rounds down and math.ceil() rounds up
02 | local Player = game.Players.LocalPlayer |
03 | local Mouse = Player:GetMouse() |
09 | local Model = game.ReplicatedStorage.Model:Clone() |
16 | PosX = math.floor(Mouse.Hit.X) |
18 | PosZ = math.floor(Mouse.Hit.Z) |
21 | local function Movement() |
22 | Mouse.TargetFilter = Model |
26 | Model:SetPrimaryPartCFrame(CFrame.new(PosX, PosY, PosZ)) |
30 | local function StartPlacement() |
31 | Model.Parent = workspace |
34 | game.Players.PlayerAdded:Connect(StartPlacement) |
You will notice that the model is snapping but only on a 1x1x1 grid. To add grid size it gets a little more complex (not really though). First you divide the mouse pos by the grid then add 0.5 then round and finally multiply by grid size. Example:
02 | local Player = game.Players.LocalPlayer |
03 | local Mouse = Player:GetMouse() |
11 | local Model = game.ReplicatedStorage.Model:Clone() |
18 | PosX = math.floor(Mouse.Hit.X / GridSize + 0.5 ) * GridSize |
20 | PosZ = math.floor(Mouse.Hit.Z / GridSize + 0.5 ) * GridSize |
23 | local function Movement() |
24 | Mouse.TargetFilter = Model |
28 | Model:SetPrimaryPartCFrame(CFrame.new(PosX, PosY, PosZ)) |
32 | local function StartPlacement() |
33 | Model.Parent = workspace |
36 | game.Players.PlayerAdded:Connect(StartPlacement) |
This is the simplest way to snap to a grid.
Hope this helps (if you see this.)