// Calculates how much to steer in a particular direction when orienting towards the given point private float CalculateSteeringTowards(Vector3 position) { // Determine which way to turn Vector3 desiredDirection = position - carTrans.position; // How different are we from desired angle float angleFromDesiredDirection = Vector3.Angle(carTrans.forward, desiredDirection); if (angleFromDesiredDirection < MaximumAngleDelta) { return(0); } else { return(MathExtension.AngleDir(carTrans.forward, desiredDirection, Vector3.up)); } }
// Orients towards the given point IEnumerator TurnToFace(Vector3 point) { // Determine which way to turn Vector3 desiredDirection = point - carTrans.position; float angleDirection = MathExtension.AngleDir(carTrans.forward, desiredDirection, Vector3.up); // How close are we to the given facing? float angleFromDesiredDirection = Vector3.Angle(carTrans.forward, desiredDirection); while (angleFromDesiredDirection > MaximumAngleDelta) { // Full steering, minimal gas car.updateInput(angleDirection, OrientGas); // Wait til next frame yield return(null); // Track how close we are to desired angle angleFromDesiredDirection = Vector3.Angle(carTrans.forward, desiredDirection); } }
// Drives towards the given point whilst orienting towards it IEnumerator DriveTowards(Vector3 position) { float distanceToTarget = Vector3.Distance(carTrans.position, position); // How much distance has been covered? while (distanceToTarget > MaximumDistanceDelta) { Vector3 desiredDirection = position - carTrans.position; float angleDirection = MathExtension.AngleDir(carTrans.forward, desiredDirection, Vector3.up); // Orient towards, full gas! car.updateInput(angleDirection, 1); // Wait til next frame yield return(null); // Track distance covered distanceToTarget = Vector3.Distance(carTrans.position, position); } // Stop applying gas (car will continue to drift) car.updateInput(0, 0); }