Mouse position offset is wrong, build part clipping into other objects after rotation

So, I have been fixing a build script and I tried to add a Y axis rotation because it only had a Z axis rotation, so the script gets the pos of the mouse and then adds a offset which is half part size so it doesn’t clip in the ground or in the object you are trying to place the part on ,but in this case it is only working for the Z axis when I rotate the part and not the Y axis, because when I rotate the Y axis the offset is wrong and the length becomes the height, the only exception where everything works fine is when the part is a perfect cube, exemple in the video

sorry if the explanation is difficult to understand

the part rotation works in increments of 90 degrees ,so if rotationY = 3 then 3 times 90…


local rayParams = RaycastParams.new()
rayParams.FilterDescendantsInstances = ignore
rayParams.FilterType = Enum.RaycastFilterType.Blacklist

	repeat

		local mousePos = uis:GetMouseLocation()
		local unitRay = cam:ScreenPointToRay(mousePos.X, mousePos.Y - 35)
		local rayResult = workspace:Raycast(unitRay.Origin, unitRay.Direction * 500, rayParams)

		if rayResult then
			
			local HitBoxsize = preview.HitBox.Size

			if CheckIfEven(rotation) and CheckIfEven2(rotationY) then

				HitBoxsize = HitBoxsize

			else

				HitBoxsize = Vector3.new(HitBoxsize.Z, HitBoxsize.Y, HitBoxsize.X)

			end
			
			local offset2 = rayResult.Normal * (HitBoxsize/2) 
		
			
			
		
			preview.PrimaryPart = preview.HitBox

			preview:SetPrimaryPartCFrame(CFrame.new(rayResult.Position + offset2) * CFrame.Angles(0, math.rad(90 * rotationY), math.rad(90 * rotationZ)))

			for _, v in pairs(preview:GetDescendants()) do

				if v:IsA("Part") or v:IsA("WedgePart") or v:IsA("TrussPart") or v:IsA("MeshPart") then

					if (preview.HitBox.Position - player.Character.HumanoidRootPart.Position).Magnitude <= 35 then

						v.Color = Color3.fromRGB(70, 200, 70)
						valid = true

					else

						v.Color = Color3.fromRGB(200, 70, 70)
						valid = false

					end

				end

			end

		else

			valid = false

		end

		rs.RenderStepped:Wait()

	until equipped == false or preview == nil

end

end

any ways to fix it? I have tried detecting the rotation increment then changing Y to Z but no success
the code you see is the version that works the best right now with the z axis.

I fixed it by adding a if condition, so in order for the y axis to rotate properly it needs to have the same axis and the if condition have to be false, if the axes are not the same then it makes the y axis the z axis
local HitBoxsize = preview.HitBox.Size
if rotationY%2 == 0 then

HitBoxsize = HitBoxsize

else

HitBoxsize = Vector3.new(HitBoxsize.Z, HitBoxsize.Y, HitBoxsize.X)

end

wow thanks I’ll try that for sure, I will let you know.