/* * @author Valentin Simonov / http://va.lent.in/ */ using UnityEngine; namespace TouchScript.Utils.Geom { /// /// A class with 2D helper functions. /// public static class TwoD { /// /// Calculates distance from line to point. /// /// Line "starting" point. /// Line "ending" point. /// Point to calculate the distance to. /// Distance between point and line. public static float PointToLineDistance(Vector2 lineStart, Vector2 lineEnd, Vector2 point) { var dx = lineEnd.x - lineStart.x; var dy = lineEnd.y - lineStart.y; return (dy * point.x - dx * point.y + lineEnd.x * lineStart.y - lineEnd.y * lineStart.x) / Mathf.Sqrt(dx * dx + dy * dy); } /// /// Calculates distances from line to each of 2 points. /// /// Line "starting" point. /// Line "ending" point. /// Point to calculate the distance to. /// Point to calculate the distance to. /// Contains returned distance from line to the first point. /// Contains returned distance from line to the second point. public static void PointToLineDistance2(Vector2 lineStart, Vector2 lineEnd, Vector2 point1, Vector2 point2, out float dist1, out float dist2) { var dx = lineEnd.x - lineStart.x; var dy = lineEnd.y - lineStart.y; var c = lineEnd.x * lineStart.y - lineEnd.y * lineStart.x; var length = Mathf.Sqrt(dx * dx + dy * dy); dist1 = (dy * point1.x - dx * point1.y + c) / length; dist2 = (dy * point2.x - dx * point2.y + c) / length; } /// /// Rotates a point around (0,0) by an angle. /// /// Point to rotate. /// Angle in degrees to rotate by. /// Transformed point. public static Vector2 Rotate(Vector2 point, float angle) { var rad = angle * Mathf.Deg2Rad; var cos = Mathf.Cos(rad); var sin = Mathf.Sin(rad); return new Vector2(point.x * cos - point.y * sin, point.x * sin + point.y * cos); } } }