Skip to content

Instantly share code, notes, and snippets.

@aefreedman
Created December 3, 2021 23:06
Show Gist options
  • Save aefreedman/42b44f61d353cb8cedf55a14eea9887a to your computer and use it in GitHub Desktop.
Save aefreedman/42b44f61d353cb8cedf55a14eea9887a to your computer and use it in GitHub Desktop.
/// <summary>
/// Returns the signed angle between two transforms, from the perspective of the From transform, ignoring the Y axis
/// </summary>
/// <param name="fromTransform"></param>
/// <param name="toTransform"></param>
/// <returns></returns>
public static float InverseSignedAngleBetweenXZ(this Transform fromTransform, Transform toTransform)
{
// Remove the Y coordinate from the reference position and the target position
var toPosition = new Vector3(toTransform.position.x, 0, toTransform.position.z);
var fromPosition = new Vector3(fromTransform.position.x, 0, fromTransform.position.z);
// Get the direction to the target position, using the From position as the reference position
var directionToTarget = fromTransform.InverseTransformDirection(toPosition - fromPosition);
var localForward = fromTransform.InverseTransformDirection(fromTransform.forward);
return Vector3.SignedAngle(localForward, directionToTarget, fromTransform.up);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment