Grid building system not working

My grid building system kinda works but on certain sides it phases through the block

-- Find the block prefab in the ReplicatedStorage object
local blockPrefab = game.ReplicatedStorage:FindFirstChild("Block")
local player = game:GetService("Players").LocalPlayer
local ms = player:GetMouse()
local gridSize = 3 -- Set the size of the grid (in studs)
local outlinePrefab = blockPrefab:Clone() -- Create a copy of the block prefab
outlinePrefab.Parent = game.ReplicatedStorage -- Move the outline prefab to the ReplicatedStorage object
outlinePrefab.Transparency = 1 -- Make the outline prefab fully transparent

-- Add a script to the Player object that listens for the MouseButton1Down event
player.CharacterAdded:Connect(function(character)
    ms.Button1Down:Connect(function()
        -- Create a new block using the block prefab
        local distance = (character.HumanoidRootPart.Position - ms.Hit.Position).magnitude
        if distance <= 20 then
            local newBlock = blockPrefab:Clone()
            newBlock.Parent = game.Workspace
            local pos = ms.Hit.p
            local x = math.floor(pos.X / gridSize + 0.5) * gridSize
            local y = math.floor(pos.Y / gridSize + 0.5) * gridSize
            local z = math.floor(pos.Z / gridSize + 0.5) * gridSize
            newBlock.Position = Vector3.new(x, y, z)
        end
    end)

    -- Show a preview of where the block will be placed
    ms.Move:Connect(function()
        -- Round the position of the mouse to the nearest grid point
        local outlineBlock = outlinePrefab:Clone()
        outlineBlock.Name = "outlineblock"
        if game.Workspace:FindFirstChild("outlineblock") then
            game.Workspace:FindFirstChild("outlineblock"):Destroy()
        end
        local pos = ms.Hit.p
        local x = math.floor(pos.X / gridSize + 0.5) * gridSize
        local y = math.floor(pos.Y / gridSize + 0.5) * gridSize
        local z = math.floor(pos.Z / gridSize + 0.5) * gridSize
        local previewPos = Vector3.new(x, y, z)

        -- Create a new outline block at the preview position
        local outlineBlock = outlinePrefab:Clone()
        outlineBlock.Name = "outlineblock"
        if game.Workspace:FindFirstChild("outlineblock") then
            game.Workspace:FindFirstChild("outlineblock"):Destroy()
        end
        outlineBlock.Parent = game.Workspace
        outlineBlock.Position = previewPos
        outlineBlock.CanCollide = false
        outlineBlock.Transparency = 0.8
        local distance = (character.HumanoidRootPart.Position - ms.Hit.Position).magnitude
        if distance <= 20 then
            outlineBlock.BrickColor = BrickColor.new("Lime green")
        else
            outlineBlock.BrickColor = BrickColor.new("Really red")
        end
        outlineBlock.CanQuery = false
    end)
end)