Keyboard controlled knee. (QWOP mechanic)

Hiya guys. I am tring to create a human body with fully controllable joints. In the end it probably would look something like this: QWOP (I am also working in 2d)

I am using configurable joint with these settings:

  • XMotion : Locked
  • YMotion : Locked
  • ZMotion : Locked
  • Angular XMotion :
    Limited
  • Angular YMotion : Locked
  • Angular ZMotion : Locked
    Low angular XLimit : Limit -70
    High angular XLimit : Limit 70
  • Rotation Drive Mode : X & YZ
  • Angular XDrive: Mode : Position
  • Position Spring : 1000
  • Position Damper : 200
  • Maximum Force : 10

The script to control the movement is this:

    void Update()
{
    targetAngle += Input.GetAxis("Vertical") * Time.deltaTime * rotateSpeed;
    Quaternion targetRotation = Quaternion.AngleAxis( targetAngle, Vector3.right );
    thisConfJoint.targetRotation = targetRotation;
}

So THE PROBLEM is basically this - it doesn`t work the way I want to. The value of “targetAngle” can go higher or lower than the angle the leg can bend, and that causes the legs to jump around (if I hold down long enough for targetAngle go from +70 to -70 the wrong way) or a lag between movements (when targetAngle crosses the 70* line, and I have to wait for it to move back).

I am pretty new both to Unity and programming, and cant seem to find a way to limit targetAngles value in the boundaries, or think of alternative solution for this.
This is where I come to you guys - could anyone at least hint me the right direction to look at? :slight_smile:

Fixed it with this line
targetAngle = Mathf.Clamp( targetAngle, -70, 70);