4

Goal

I would like to rotate a head of a humanoid character given x, y, z rotation values using a script (without using any other object in the scene as "look" direction).

What I want to do

When setting-up the rigging of a Humanoid character (humanoid prefab --> Rig --> Animation Type: Humanoid --> Configure --> Muscles & Settings), you see the following interface: https://docs.unity3d.com/Manual/MuscleDefinitions.html

In this menu, under Head, you can drag a slider to move e.g. your humanoid head up and down. I want to achieve the same with a script, but I don't know how to do this.

Resources

This question never received a proper answer with example code: https://answers.unity.com/questions/824628/can-we-using-script-to-moving-the-muscles-in-unity.html

I presume I have to do something with HumanPose.muscles (https://docs.unity3d.com/ScriptReference/HumanPose-muscles.html), however with the lack of code samples, I have no idea how to approach this.

Edit 3: This link has a code sample for HumanPose, but I didn't get it to work yet: https://forum.unity.com/threads/humanposehandler.430354/

Question

How to get the head muscles of a humanoid character and rotate them by giving values through a script? (Or any other way how to rotate the head using head rotation values, without another object in the scene). Any help would be appreciated.

Edit 1 & 2: Sample code

I receive a JSON formatted message from which I extract the radian values and change it into degrees:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json.Linq;  // JSON reader; https://assetstore.unity.com/packages/tools/input-management/json-net-for-unity-11347

public class HeadRotator : MonoBehaviour {

    Quaternion rotation = Quaternion.identity;

    // Radians to degree
    float Rad2Degree = 180 / Mathf.PI;

    // Human muscle stuff
    HumanPoseHandler humanPoseHandler;
    HumanPose humanPose;
    Animator anim;
    //Transform head;

    // Use this for initialization
    void Start () {
        // get attached Animator controller
        anim = GetComponent<Animator>();

        //head = anim.GetBoneTransform(HumanBodyBones.Head);
        //Debug.Log (head);
    }


    // Use JSON message to set head rotation and facial expressions;
    // IEnumerator to run in main thread (needed for SetBlendShapeWeight)
    public IEnumerator RequestHeadRotation(JObject head_pose)
    {
        // rotate head of character with received x, y, z rotations in radian
        List<float> head_rotation = new List<float> ();
        foreach (KeyValuePair<string, JToken> pair in head_pose) {
            //Debug.Log(pair);
            // store head rotation in degrees
            head_rotation.Add(float.Parse(pair.Value.ToString())*Rad2Degree*10);
        }

        Debug.Log ("" + head_rotation[0] + ", " + head_rotation[1] + ", " + head_rotation[2]);
        //Quaternion rotation = Quaternion.Euler(new Vector3(head_rotation[0], head_rotation[1], head_rotation[2]));
        //Debug.Log ("" + rotation[0] + ", " + rotation[1] + ", " + rotation[2] + ", " + rotation[3]);
        // head.Rotate (rotation);

        // https://docs.unity3d.com/ScriptReference/Quaternion-eulerAngles.html
        rotation.eulerAngles = new Vector3 (head_rotation[0], head_rotation[1], head_rotation[2]);

        // Animator.GetBoneTransform()
        anim.SetBoneLocalRotation(HumanBodyBones.Head, rotation);

        yield return null;
    }
}
  • Head rotation data: 3.208564, 0.4583662, 0.1145916
  • Quaternion data: 0.0280001, 0.003970424, 0.0008876149, 0.9995997

I don't really know well how to set either the head bone or the muscles. Most examples provide only a snippet of the code, so I'm struggling in figuring out how it works.

Edit 2: I feel I'm getting close, but anim.SetBoneLocalRotation(HumanBodyBones.Head, rotation); seems to get ignored.

Edit 4: I put on Github a simple version of my head rotation attempt: https://github.com/NumesSanguis/Basic-Unity-Head-Rotation

3
  • Why don't you rotate the Bone related to head from script?
    – ZayedUpal
    Feb 12, 2018 at 6:27
  • Could you tell me how you do that? I added a code snippet with how I get the rotation values, but don't know how to apply that to the head bone. Feb 12, 2018 at 8:18
  • Will the humanoid be animated?
    – ZayedUpal
    Feb 12, 2018 at 18:26

3 Answers 3

7

After testing for a while, I figured it out.

  1. Firstly, set the animator to IK Pass.

enter image description here

  1. Then use SetBoneLocalRotation inside OnAnimatorIK method. You can know more about this method here: https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnAnimatorIK.html
    Following is the modified code that worked for me

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HeadRotator : MonoBehaviour
{
	public Vector3 rot = new Vector3(20, 30, 10);
	Animator anim;

	//  Bone stuff
	Transform head;

	//  !!! Head bone rotation approach !!!
	void Start () {
	  	// get attached Animator controller
		anim = GetComponent<Animator>();
		head = anim.GetBoneTransform(HumanBodyBones.Head);
	}

	void OnAnimatorIK (int layerIndex) {
		print ("OnAnimatorIK - running");
		anim.SetBoneLocalRotation(HumanBodyBones.Head, Quaternion.Euler(rot));
	}
}

1
  • Thanks for the effort, it's working! I accepted your answer, because you were first, and your method can have an AnimateController attached. See my answer for the muscle value approach and link to full Unity project with both your, and my friend's solution. Feb 13, 2018 at 1:57
2

Thanks to @ZayedUpal head bone rotation is working, and thanks to a friend, setting muscle values is also working!

The full Unity 3D project for both options can be found here: https://github.com/NumesSanguis/Basic-Unity-Head-Rotation

Code snippet of muscle values approach:

//   !!! Human Pose approach !!!
void Start () {
    // https://forum.unity.com/threads/humanposehandler.430354/

    // get attached Animator controller
    anim = GetComponent<Animator>();

    // run this if you want the indexes to muscles on your character
    LookUpMuscleIndex();

    // TODO keeping body above plane
    //Vector3 current_position = transform.position;

    // get human pose handler
    humanPoseHandler = new HumanPoseHandler(anim.avatar, transform);
    // get human pose
    humanPose = new HumanPose();

    // TODO keeping body above plane
    //humanPose.bodyPosition = current_position;

    // reference pose to pose handler
    humanPoseHandler.GetHumanPose(ref humanPose);

    // set a specific musle; 9: Neck Nod Down-Up
    humanPose.muscles[9] = -20f; 
    Debug.Log(humanPose.muscles[9]);

    // use pose information to actually set the pose;
    humanPoseHandler.SetHumanPose(ref humanPose);
}
1
  • I had trouble with this script. The character to which it was applied moved quite far from where he was supposed to be when humanPoseHandler.SetHumanPose(ref humanPose); was set. The Bone example worked nicely though....
    – DrMcCleod
    Aug 15, 2018 at 22:41
0

Two addition to the muscle answer

1, To solve the problem:

The character to which it was applied moved quite far from where he was supposed to be when humanPoseHandler.SetHumanPose(ref humanPose); was set.

You need to add:

humanPose.bodyPosition = transform.position;
humanPose.bodyRotation = transform.rotation;

That will keep your character exactly where it is located.

2, Actually the muscle solution is still valid when an AnimatorController is attached to current humanoid character. You just need to switch Update Mode to Animate Physics and put your muscle code in Update(). That will make your muscle code (which executes in Update()) executes after the AnimationController effects (which executes in FixedUpdate(), which is called earlier than the Update()).

This approach will allow you directly control some muscle, and use Unity IK effect at the same time.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.