Rotating a Motor6d's Next Joint towards a target vector

Hello, I’m trying to make a motor6d rotate a joint in a way such that the limb’s next joint along the limb aligns along with a vector’s end position.

So far my method works only if the model face forwards as seen in below’s clip where the knee joint aligns with the pink block.

Notes on the video:

The pink block represents the world position of where that knee joint is supposed to be according to the algorithm.

The Yellow block represents the joint position of where the knee joint would be given that the motor6d remains in it’s original orientation.

The working condition model is facing forwards towards -z axis:

External Media

Failure condition model is rotated anywhere beyond that:
https://streamable.com/doikoj

Here is the model’s rig for reference:

Photo of rig

https://streamable.com/5x4qzr

And finally the code that is continually every heatbeat:

 -- obtains a vector that is from the hipjoint to the knee joint given Motor6D original orientation
   local vectorToCFrame = CFrame.new(Vector3.new(),vecOne)
   local rotationOffset = (hipCFrame-hipCFrame.p)
   local lookRelativeToHip = rotationOffset*vectorToCFrame
   local vectorOneRelativeToHip = lookRelativeToHip.LookVector*limbLengthTable[1]

    --Position of the yellow block
    part4.Position = hipJointCFrame.p+vectorOneRelativeToHip

    -- Obtain angle between new hip-upperleg vector and its original position
    local rotateUpperLegAngle = math.acos(vectorOneRelativeToHip.Unit:Dot(v1New.Unit))
    local rotationAxisUpperLeg = vectorOneRelativeToHip:Cross(v1New) -- obtain the rotation axis

    lHipToLegMotor.C0 = hipToLegStore*CFrame.fromAxisAngle(rotationAxisUpperLeg,rotateUpperLegAngle)

Before the heartbeat loop

-- store the original c0 position
local hipToLegStore = lHipToLegMotor.C0

If you need more information you can download my place file
on my GitHub and test it out yourself.

Edit: To access the place file download the entire project as a zip file, click the green Code button, then download the zip file then open up the rbxlx file with studio

Edit 2: Drag around LTarget to move the leg and replicate what I do in the video

1 Like

After hours of frustration I made it work. It’s the CFrame order of operations:

    lHipToLegMotor.C0 = hipCFrame:Inverse()*CFrame.new(upperLegPos)*CFrame.fromAxisAngle(rotationAxisUpperLeg,rotateUpperLegAngle)*CFrame.new(empty,hipCFrame.LookVector)

Vid of it working even after rotating the mech base:

External Media

In the words of a valve programmer:

I don’t know why, I don’t want to know why, I shouldn’t have to wonder why, but for whatever reason I have to do it this way

edit: Though if you can explain to me why that would be nice I guess but it’s optional as it works for now.