Hello, I am in the process of writing a system that lets you snap various building pieces together when I came upon an interesting problem.
I’m trying to figure out how to “snap” two parts together while preserving the orientation to the nearest 90 degrees of a specific face. This is a vague and abstract explanation, so let me try to do explain it visually:
Imagine two CFrames, represented by these two parts. (The arrow doesn’t indicate movement or any functionality, it’s simply there as a show of the red part’s orientation)
Before “snapping” these two parts, there is typically going to be some angular difference, such as here.
In this case, snapping should produce this result: Note how the arrow’s overall orientation hasn’t changed relative to the “face” it ended up on.
So far, it should be simple enough. In the example above, it’s a one-dimensional rotation. But where things get difficult is when you have an offset like this, involving multiple dimensions of rotation:
In this case, the goal would be to rotate it such that it ends up like this: (the arrow is pointing to the right this time because the previous offset’s arrow is the closest to this result)
This behavior to be active for all faces of the blue part, and the complete system would only match the nearest face of the red part to the nearest relative face of the blue part, if that makes sense.
I’ve tried previously to solve this with some trial-and-error with dot and cross products but never managed to crack it on my own. I hope my explanation is enough to get my curiosity across. If any of you are familiar with this problem, can point me towards an explanation for it, or in general have any tips, tricks, or mathematical know-how that could be useful, I would be very grateful!