- Home /
Can I rotation a bone with a script?
Hey Everyone,
New user here on Unity 4. I have a background with C, Java and Blender3D, so I've been working with programming and development tools of all kinds for some time now. I'm initially quite impressed with Unity and I'm hoping to utilize it to eliminate a metric ton of code (particularly around physics, collision and animation).
What I would like to achieve now is bone control via script. As a test case, I just want to click the mouse and send the head rotating around continuously. I can do this fine when I attach the script to the top Parent GameObject, but if I attach the script to the Head "bone" nothing happens.
Looks like there is a great community here. Hope to hear back soon.
-Jeremiah
Answer by Loius · Feb 12, 2013 at 06:35 PM
When animating bones by code, there's a couple caveats:
If your animation has no animation data for that bone, you can animate the bone freely and/or combine animations. I know that Blender always exports animation for all bones, whether or not they're animated. It's a simple fix to change this in Blender 2.49 (export_fbx.py), but if you just want to animate by code, then...
If you animate in LateUpdate instead of Update, you'll override any animation transforms (since animation happens between Update and LateUpdate).
Thanks for the tips, I'll have to have a look at the blender fbx exporter (not familiar with the format but it may be worth the research).
I'm not sure about the override... what I'm seeing is that the animation reads the data from the bone, sets it in Update, and then in LateUpdate I'm having to compensate for the fact that the position was reset during Update, i.e. rather than just transform.Rotate(1,0,0) I have to rotateValue += 1.0; transform.Rotate(rotateValue, 0, 0);
It's better to use absolute rotations (rather than incremental) if you're using overrides (and I'd say it's almost always the right choice, regardless) - something like "head.rotation = Quaternion.LookRotation( target.position - transform.position)"
If you're storing a rotation for, say, using the mouse to aim a bone, it's easiest to store a float value or two ("var rotY : float = 0") and alter those according to your input ("rotY += mouseDeltaX"), then derive a rotation from that ("head.localRotation = Quaternion.Euler(0, rotY, 0)")