[SOLVED] Snapping position to a 4x4 grid

Hey, devs!
I’m making a Minecraft-like voxel game and working on a block placement system.

This is my local script function to calculate the snapped pos from the hitPosition

function getGridPosition(hitPosition)
	local gridPosition = Vector3.new(
		math.round(hitPosition.X / 4) * 4,
		math.round(hitPosition.Y / 4) * 4,
		math.round(hitPosition.Z / 4) * 4
	)
	return gridPosition
end

I have a problem that sometimes it rounds badly and the position is wrong.

Does anybody see some problem in that function?

1 Like

What do you mean by rounding badly? Could you post a image or video of it

1 Like

The problem was about having the right offset near to the camera:

fixed code:

function getGridPosition(hitPosition)
	hitPosition = hitPosition:Lerp(camera.CFrame.Position, 0.02)
	
	local OFFSET = 0.5
	local gridPosition = Vector3.new(
		math.floor(hitPosition.X / 4 + OFFSET) * 4,
		math.floor(hitPosition.Y / 4 + OFFSET) * 4,
		math.floor(hitPosition.Z / 4 + OFFSET) * 4
	)
	return gridPosition
end
1 Like