Given a position, upVector, and lookVector. I want a function that creates a cframe that
- Has the same position as the given position
- Has the same upVector as the given upVector
- Has a lookVector that is as close as possible to the given lookVector
Here is an demonstration done with constraints which is pretty close to what I want
test_snap.rbxl (24.2 KB)
Green is the upVector.
Red is the lookVector.
Grey is the position (grey ball is covered by the cube).
The balls’ position are the target vectors. The lines coming out of the cube represent’s the cube’s vectors.
As you can see, the green upVector of the cube points straight at the green ball at all times.
The red lookVector is doing its best to point in the general direction of the red ball,
but does not change the upVector in the process.
I am trying to achieve the same rough results with a function instead of constraints. Something like
function calculateCframeFromWorldVectors(pos: Vector3 ,up: Vector3 ,targetLook: Vector3): CFrame
For testing, I will be using the balls’ position as parameter’s for the function and applying the resulting cframe to the cube.
calculateCframeFromWorldVectors(greyBall.Position, greenBall.Position, redBall.Position)
and return a cframe similar to the cube’s cframe now.
This has to be calculated without relying on the physics system as the goal is to do this in a plugin.
I believe I should be able to achieve this with CFrame.fromMatrix()
, but haven’t conceived a reliable formula… and in the end just became extremely confused.
I originally wanted the function to take unit vectors for up * targetLook, but have reached the point where I don’t trust myself to calculate anything…
Here is the broken demo world. The broken function is at the top of the script in game.Workspace.PublicTest
. To test, you can push run (Do not push play
or play here
).
The very transparent cube is the physics based implimentation, and the smaller, more opaque cube is the one using the function. If the function is fixed then the opaque cube should align itself close to the transparent one (but the transparent physics one isn’t perfect, so it shouldn’t be a perfect fit)
test_snap.rbxl (24.2 KB)