I am making a placement system for my game but when I try to place blocks that are rotated (not axis-alinged) the offsets break.

local function GetPlacementPosition(gridSize, partSize, position, normal, target)


	local gridCorner = Vector3.new(
		math.floor(position.X / gridSize + 0.5) * gridSize,
		math.floor(position.Y / gridSize + 0.5) * gridSize,
		math.floor(position.Z / gridSize + 0.5) * gridSize
	)
	return gridCorner + partSize * normal  / 2 
end

local pos = GetPlacementPosition(grid.Value, preview.Parts.Hitbox.Size, target, ray.Normal, plrMouse.Target)

local cf = CFrame.new(clamp pos to plot walls)

preview:SetPrimaryPartCFrame(cf)

Rotated 90 deg: prnt.sc/131hf0l

Rotated 45 deg: prnt.sc/131hdtp

If the links dont work try copying them and pasting on your browser's search bar