Scaling Rotated Parts bugging out and moving?

Hello, I have a system where you click one spot, and it places one corner of a part there, then the said part will scale with your mouse until you click again and it will place the part accordingly.

This works perfectly, unless the part is rotated 90 or 270 degrees. It then does not stick where it should and scales awkwardly, unless it is perfectly even on both sides. It’s clearly a math problem with me as it’s not my strong suit, its been a lot of trial and error just getting here. Like switches from Euler angles to Quaternions to fix a mirror problem thanks to some help I got here.

Here is what it looks like when it works, the part is not rotated at all:
RobloxStudioBeta_B4npXZt6sC

Here is what is looks like when rotated 90 degrees:
RobloxStudioBeta_k67roiY3ji

I am really not sure whats going on here, I’m sure the rotations messing with it but I do not know at all why. Here is the code for that system:


local function QuaternionFromEulerYXZ(yaw, pitch, roll)
	local cy = math.cos(math.rad(yaw) * 0.5)
	local sy = math.sin(math.rad(yaw) * 0.5)
	local cp = math.cos(math.rad(pitch) * 0.5)
	local sp = math.sin(math.rad(pitch) * 0.5)
	local cr = math.cos(math.rad(roll) * 0.5)
	local sr = math.sin(math.rad(roll) * 0.5)

	local qx = sr * cp * cy - cr * sp * sy
	local qy = cr * sp * cy + sr * cp * sy
	local qz = cr * cp * sy - sr * sp * cy
	local qw = cr * cp * cy + sr * sp * sy

	return CFrame.new(0, 0, 0, qx, qy, qz, qw)
end

local function applyQuaternionRotation(part, rotationY)
	local quaternionRotation = QuaternionFromEulerYXZ(rotationY, 0, 0)
	part.CFrame = part.CFrame * quaternionRotation
end

local function updatePreviewBlock()
	if startPosition and endPosition then
		-- Calculate the size differences between start and end positions
		local sizeX = math.abs(endPosition.X - startPosition.X)
		local sizeZ = math.abs(endPosition.Z - startPosition.Z)
		local sizeY = bottomHeight.Value

		-- Midpoint position calculation
		local positionX = (startPosition.X + endPosition.X) / 2
		local positionZ = (startPosition.Z + endPosition.Z) / 2
		local positionY = initialY + sizeY / 2

		-- Update the preview block's position and size
		bottomPreviewBlock.Size = Vector3.new(sizeX, sizeY, sizeZ)
		bottomPreviewBlock.Position = Vector3.new(positionX, positionY, positionZ)

		-- Apply the quaternion rotation to the block
		applyQuaternionRotation(bottomPreviewBlock, currentRotation)

	end
end

Any help would be very appreciated :slight_smile: Bonus points if you can explain to me where my problem is so I understand but I am more than happy to accept just a fix, any kind of help at all. Thank you