Stumped regarding CFrames and relativity

This is kind of hard to explain, so I will do my best to explain this issue. If you guys want me to elaborate more on the issue I will be happy to reply.

I have recently been working on a building system that involves the rotation and placing of builds. It works great! But there’s 1 problem I’m trying to fix.

My initial problem is that the buildings would phase inside of each other, instead of actually offsetting to make building easier.

I (kind of not really) fixed it with these lines of code

		if Mouse.TargetSurface == Enum.NormalId.Right then
			BuildPreview:SetPrimaryPartCFrame(BuildPreview.PrimaryPart.CFrame * CFrame.new(BuildPreview.BoundingBox.Size.X/2,0,0))
		end
		if Mouse.TargetSurface == Enum.NormalId.Left then
			BuildPreview:SetPrimaryPartCFrame(BuildPreview.PrimaryPart.CFrame * CFrame.new((BuildPreview.BoundingBox.Size.X/2) * -1,0,0))
		end
		if Mouse.TargetSurface == Enum.NormalId.Front then
			BuildPreview:SetPrimaryPartCFrame(BuildPreview.PrimaryPart.CFrame * CFrame.new(0,0,(BuildPreview.BoundingBox.Size.Z/2) * -1))
		end
		if Mouse.TargetSurface == Enum.NormalId.Back then
			BuildPreview:SetPrimaryPartCFrame(BuildPreview.PrimaryPart.CFrame * CFrame.new(0,0,BuildPreview.BoundingBox.Size.Z/2))
		end

This makes it to where the builds actually do offset instead of phasing inside of each other. But it doesn’t work when I rotate the part.

Problem:

To restate, I want to make it offset no matter what the rotation is. But in my case it just simply does not work.

I’m gonna be honest, I’m not that great at math at all, but does anyone know any way I could fix this issue?

Do you use this fix for the code before or after the rotation? Also what is the code you use for the rotation?

After. I use orientation to rotate it? The rotations not the issue. It’s my crappy math

When the build preview is rotating it isn’t doing so around it’s centre so something is off with the rotating too surely?

It is doing it around the center. The code I implemented is just making it seem like its not. Trust me. I actually think I have the solution but I still don’t know how to fix it.

Capture

Basically, If my mouse is hovering over the top parts back (shown as the red circle), The game places the bottom part’s cframe on the mouses position, and then moves it back to where the bottom part is against the top part, and it does it no matter what the part’s rotations are and that’s what I’m trying to do but I cannot figure it out for the life of me. I’m really stumped here.

You can clearly see in the video how the build preview is rotating around an axis that lies within one of its surfaces rather than the centre of the box?

The process seems to me like you have the Mouse Target, get the surface normal, find out the width of the build in that direction and then move by normal * width/2. After which you could apply rotations around that point.