Most efficient way to round Coordinates for Block Placement

I’m making a script that rounds the position of your mouse when you click it to multiples of four. Its like the block placement system in TheDevKing’s Minecraft video, except my script only creates new parts on the x and z axes when I click in two directions; the other two directions just make me tower upward. Here’s the script:
(I have a separate local script that sends the mousePos to the server script)
(FistsClicked is a remote event)

local fistsClicked = game.ReplicatedStorage["Fists-Clicked"]

fistsClicked.OnServerEvent:Connect(function(player, mousepos)
	local x = 4 * math.floor(mousepos.x/4 + 0.5)
	local y = 4 * math.floor(mousepos.y/4 + 0.5)
	local z = 4 * math.floor(mousepos.z/4 + 0.5)
	
	local roundedpos = Vector3.new(x, y - 2, z)
	
	local part = Instance.new("Part")
	part.Size = Vector3.new(4, 4, 4)
	part.Position = roundedpos
	part.Parent = workspace
	part.Anchored = true
	
	local health = Instance.new("IntValue")
	health.Name = "Health"
	health.Value = 10
	health.Parent = part
end)

Is there any way I could detect when to floor or ceil the coordinates based of which way the player wants to build?

I’ve tried using math.round but that hasn’t worked either.

It looks good, but maybe try creating a function that rounds a Vector3 coordinate so you can use it more often without wasting line space

local roundCoords = function(coords, roundNum)
   return roundNum * Vector3.new(math.floor(coords.x/roundNum+ 0.5), math.floor(coords.y/roundNum+ 0.5), math.floor(coords.z/roundNum+ 0.5))
end

Hope this helps, let me know if it has a problem!

Edit: The roundNum parameter is what you want it to be rounded to, so for your example, it would be 4

I think he had it right.
roundVector(Vector3.new(3, 0, 0), 4) = math.round(12)/4 = 3

Oh shoot you’re right, I was thinking about rounding to some factor of 100 whoops

1 Like

So I’m having the same problem that’s in this thread:
https://devforum.roblox.com/t/grid-placing-system/

Is there any way I accomplish the same action without the raycasts used in the aforementioned thread and by just using rounds?

local roundedResult = unrounded - (unrounded % roundTo)