local Player = game.Players.LocalPlayer local Mouse = Player:GetMouse() local PosX local PosY local PosZ local Model = game.ReplicatedStorage.Crate:Clone() Model.Parent = workspace local GridSize = 5 local function snap() PosX = math.floor(Mouse.Hit.X / GridSize + 0.5) * GridSize PosY = Model.PrimaryPart.Position.y PosZ = math.floor(Mouse.Hit.Z / GridSize + 0.5) * GridSize end local function Movement() Mouse.TargetFilter = Model snap() Model:SetPrimaryPartCFrame(CFrame.new(PosX, PosY, PosZ)) end Mouse.Move:Connect(Movement)
At the snap function, all it does is add 5 to the position. Why does adding + 5 not have the same effect?
math.floor(x)
rounds things down
math.floor(0.9) math.floor(1.0) math.floor(1.1)
gives 0, 1, 1
math.floor(x + 0.5)
rounds things normally
math.floor(0.9 + 0.5) = math.floor(1.4) = 1 math.floor(1.0 + 0.5) = math.floor(1.5) = 1 math.floor(1.1 + 0.5) = math.floor(1.6) = 1 math.floor(1.4 + 0.5) = math.floor(1.9) = 1 math.floor(1.5 + 0.5) = math.floor(2.0) = 2
math.floor(x / y + 0.5) * y
rounds to the nearest y.
math.floor(6.73 / 2 + 0.5) * 2 = math.floor(3.865) * 2 = 3 * 2 = 6 math.floor(6.73 / 5 + 0.5) * 5 = 5 math.floor(6.73 / 10 + 0.5) * 10 = 10 math.floor(6.73 / 20 + 0.5) * 20 = 0
In snap
, x
is Mouse.Hit.X
and Mouse.Hit.Z
and y
is GridSize
.
local function snap() PosX = math.floor(Mouse.Hit.X / GridSize + 0.5) * GridSize PosY = Model.PrimaryPart.Position.y PosZ = math.floor(Mouse.Hit.Z / GridSize + 0.5) * GridSize end
snap
is using this to round X and Z to be multiples of GridSize
.