Skip to content

Instantly share code, notes, and snippets.

@jrenner
Created May 7, 2013 01:46
Show Gist options
  • Save jrenner/5529720 to your computer and use it in GitHub Desktop.
Save jrenner/5529720 to your computer and use it in GitHub Desktop.
void steerToDesiredFacing() {
if (desiredFacing == null) {
return;
}
float facing = getForwardFacing();
// this contrain method keeps the angle between 180 and -180
float diff = constrainAngle180(facing - desiredFacing);
// steer within n degrees of desired facing, use this to control precision
float angularThreshold = 1;
float angularVel = body.getAngularVelocity();
// if we are turning too fast for the remaining turn distance, we slow down with this hack
// this can prevent an over-steering behavior that causes wobble
if (Math.abs(angularVel / diff) > 0.1f) {
body.setAngularVelocity(angularVel * 0.90f);
}
float torque = rotationForce;
// turn one way
if (diff >= angularThreshold) {
body.applyTorque(-torque, true);
// or turn the opposite way
} else if (diff <= -angularThreshold) {
body.applyTorque(torque, true);
// if we are within 5 degrees of desired facing
// we want to kill our turn gradually, but strong enough to stop
} else if (diff < 5) {
if (angularVel < 0.2) {
// turning slow enough to be on target
body.setAngularVelocity(0);
removeDesiredFacing();
} else {
body.setAngularVelocity(angularVel * 0.5f);
}
}
}
@lokifrit
Copy link

lokifrit commented Feb 9, 2015

what does the method : removeDesiredFacing(); do?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment