Prevent Chase Camera unwinding

When you turn twice with your character, the chase camera eventually unwinds, causing the camera to go on opposite direction until it positions itself behind your back. This causes that when you are making circles counter clock wise in your car, eventually the camera will go clock wise until it positions it self behind your back again.

I found that everything that goes wrong happens because of the code snippet below. This code comes from the C:\Program Files (x86)\jmonkeyplatform\jmonkeyplatform\libs\\com\jme3\input\ that comes with the stable build of JMonkey.

So, how do I prevent this from happening? All I want the camera to do is to always stay on my back without it ever going in front of me to unwind, just like the CameraNode class never positions itself in front of you.

You can try the code yourself by trying the walking character demo where there is a robot named Otto.

[java]if (targetMoves)
//computation if the inverted direction of the target
Vector3f a = targetDir.negate().normalizeLocal();
//the x unit vector
Vector3f b = Vector3f.UNIT_X;
//2d is good enough
a.y = 0;

                    //computation of the rotation angle between the x axis and the trail
                    if (targetDir.z > 0) {
                        targetRotation = FastMath.TWO_PI - FastMath.acos(;
                    } else {
                        targetRotation = FastMath.acos(;
                    if (targetRotation - rotation > FastMath.PI || targetRotation - rotation < -FastMath.PI) {
                        targetRotation -= FastMath.TWO_PI;

                    //if there is an important change in the direction while trailing reset of the lerp factor to avoid jumpy movements
                    if (targetRotation != previousTargetRotation && FastMath.abs(targetRotation - previousTargetRotation) > FastMath.PI / 8) {
                        trailingLerpFactor = 0;
                    previousTargetRotation = targetRotation;