The greetings,
I did not know exactly where to put this so I decided to put it here.
I am working on IK for my rigs and found a way to get rotation constraints with as little code as possible. There might be even eleganter solutions, but compared to my previous “attempts” this is almost divine.
What it does extra is keep the local up-axis local, and you can see a very clumsy demonstration of it here on her shin:
The code is as follows:
using UnityEngine;
using Unity.Mathematics;
public class ConstrainTest: MonoBehaviour
{
public Transform Form;
public Vector3 EulerAnglers = Vector3.zero;
public float2 Xlimits = new float2(-90f, 90f);
public float2 Ylimits = new float2(-90f, 90f);
public float2 Zlimits = new float2(-90f, 90f);
private Quaternion _startRotation = Quaternion.identity;
void Start()
{
if(!Form)
{
Form = transform;
}
_startRotation = Form.localRotation;
}
void Update()
{
EulerAnglers.x = math.clamp(EulerAnglers.x, Xlimits.x, Xlimits.y);
EulerAnglers.y = math.clamp(EulerAnglers.y, Ylimits.x, Ylimits.y);
EulerAnglers.z = math.clamp(EulerAnglers.z, Zlimits.x, Zlimits.y);
Form.localRotation = _startRotation * Quaternion.Euler(new Vector3(EulerAnglers.x, 0f, EulerAnglers.z)) * Quaternion.Euler(new Vector3(0f, EulerAnglers.y, 0f));
}
}
It can be tested out by being put on a limb of choice and then spin around the publicly exposed variables in the inspector window.