Can't position part correctly on top of another part

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!

I want to figure out why the issue is happening.

  1. What is the issue? Include screenshots/videos if possible!

Whenever I put my mouse on top (y-axis) of “part2” while placing “part1” part1 will sink about half of its size into part2. However, nothing happens when I put it on the sides of part2. (x, z axis).

Example image that shows how part1 (the transparent part) is sinking a bit into part2

Here is a simplified version of the part of the code that includes the position calculating issue. Any help is greatly appreciated.

local function functionname()
	local MousePos = UserInputService:GetMouseLocation()
	local Origin = workspace.CurrentCamera:ViewportPointToRay(MousePos.X, MousePos.Y)

	local IgnoreParams = RaycastParams.new()
	IgnoreParams.FilterDescendantsInstances = {Part1}
	IgnoreParams.FilterType = Enum.RaycastFilterType.Exclude

	local RayDistance = 10000
	local Result = workspace:Raycast(Origin.Origin, Origin.Direction * RayDistance, IgnoreParams)

	if Result then
		local HitPosition = Result.Position
		local PartHalfSize = Part1.Size / 2

		local Step = tonumber(moveincrementvalue) -- 1 in most cases
		local NewPosition = roundToStep(HitPosition, Step) + (PartHalfSize*Result.Normal)
         -- round to step rounds vector3s to the step. Vector3.new(5.6, 2.3, 6.7) --> Vector3.new(6, 2, 7)
		return CFrame.new(NewPosition)
	else
		return CFrame.new(Origin.Origin + Origin.Direction * RayDistance)
	end
end

Please do not ask people to write entire scripts or design entire systems for you. If you can’t answer the two questions above, you should probably pick a different category.