--[[ Local Script ]]--
local Players = game:GetService("Players")
local RunService = game:GetService("RunSerivce")
local localPlayer = Players.LocalPlayer
local Mouse = localPlayer:GetMouse()
local partToPlace = Instance.new("Part")
partToPlace.Parent = game.Workspace
local gridSize = 3
local function snapToGrid(position: Vector3)
local function round(num)
return math.floor(num/gridSize) * gridSize
end
return Vector3.new(round(position.X), round(position.Y), round(position.Z))
end
RunderService.RenderStepped:Connect(function()
local gridLocation = snapToGrid(mouse.Hit.Position)
part.Position = gridLocation
end)
-- Untested btw
boostttttttttttt ttttttttttttttttt
It rounds each value of the vector3 to the nearest gridSize, which in this case is 3, and returns the result.
FYI, in the future you may want to use AI to answer questions like this, even the built-in AI in studio could answer this for you
I can! It’s actually wrong though. This doesn’t round to the nearest grid position, it floors to the nearest grid position.
The way it works is by utilizing rounding, which I’m sure you know. If you round a vector on all of its axis, it is ‘snapped’ to the nearest multiple of which you are rounding to.
As for how rounding works, think about the floor function as well as what rounding itself is. We’ll consider rounding to the nearest integer for now, for simplicity.
Looking at the edge-cases is the best way to find the constraints of your problem. For example, we know that the smallest number that rounds up is a number that ends in 0.5. In other words, what is the smallest adjustment we can make to floor(0.5) such that it ‘rounds up’?
Hopefully it is clear that the answer is floor(0.5 + 0.5), because floor(1) = 1.
This is the simple rounding formula for integer values. For any number, adding 0.5 and flooring it results in what we know as ‘rounding’.
To expand this to any grid size, not just integers, you can utilize normalization. For example, if you wanted to round 15 to the nearest multiple of 10 using our current formula. You would do 15/10 = 1.5, then you would round 1.5 to the nearest multiple of 1 (which is 2), finally you multiply the result by 10 again to un-normalize it (resulting in 20, the correct answer).
The final rounding function:
local function Round(x, m)
return m * math.floor(x/m + 0.5)
end