Force Bone Rotation

Hello

I am trying to wrap my head around bone rotations through code, I am almost getting what I want but not quite.

I want the bottom half of my body to move toward movement (Which I have), while the upper part of the body is always looking forward. I basically have what I want except for the Spine bone that I am rotating just above the hips is kind of… freaking out… and I don’t understand why…

So… two methods with the best results ive got so far

All this code is in lateupdate

  1. Best results so far
torsoBone.transform.LookAt(testObj.transform, Vector3.forward);

“testObj” is the little cube in front of me that is just a child of the top parent object. The character model is also a child of that top parent object, so they are in the same place in the hierarchy.

This is what I get facing East (not really east of course just a reference)

The above gets me the best results. It all works perfectly, until I turn west. (Pic below)

I assume this has to do with world space and local space, I’ve looked how to do it in my scenario but cant get anything to work so far.

  1. Second best
        float damping = 5f;
        Vector3 lookPos = transform.position - Camera.main.transform.position;
        lookPos.z = 0;
        Quaternion rot = Quaternion.LookRotation(lookPos);
        torsoBone.transform.rotation = Quaternion.Slerp(transform.rotation, rot, Time.deltaTime * damping);

This works perfectly in all directions except for my body is rotated at a 90 degree

In the above picture ive tried to force the bone to rotate the right way but it will not move not matter what I try.

Anyway, if anyone could help me out or point me in the right direction I would really appreciate it. Let me know if you need more info from me, I am glad to give.

The second parameter to LookAt is the “up” direction. It’s very strange, to say the least, to see Vector3.forward there. Vector3.up is more common/reasonable, but is also not always necessarily correct. (It will be correct most of the time if your player doesn’t do any tilting or flipping.

I started with that but unfortunately with Vector3.Up i get the same result as Method 2

Found a fix to my issue!

        float preRot = torsoBone.transform.rotation.eulerAngles.z;
        torsoBone.transform.LookAt(testObj.transform);
        Vector3 rot = torsoBone.transform.eulerAngles;
        rot.z = preRot;
        torsoBone.transform.rotation = Quaternion.Euler(rot);

Not really sure how it works yet! if someone understands it please explain but I am looking into why its works now and will update this if I figure it out!