| | | 1 | | using UnityEngine; |
| | | 2 | | |
| | | 3 | | // Utility functions for 2D coordinates. |
| | | 4 | | // In Cartesian coordinates, the x-axis points right, and the y-axis points up. The coordinates are |
| | | 5 | | // given by (x, y). |
| | | 6 | | // In polar coordinates, the angle is measured in degrees from the x-axis counterclockwise to the |
| | | 7 | | // y-axis. The coordinates are given by (r, theta). |
| | | 8 | | public static class Coordinates2 { |
| | 4 | 9 | | public static Vector2 ConvertCartesianToPolar(in Vector2 cartesian) { |
| | 4 | 10 | | float r = cartesian.magnitude; |
| | 4 | 11 | | float theta = Mathf.Atan2(cartesian.y, cartesian.x) * Mathf.Rad2Deg; |
| | 4 | 12 | | return new Vector2(r, theta); |
| | 4 | 13 | | } |
| | 0 | 14 | | public static Vector2 ConvertCartesianToPolar(float x, float y) { |
| | 0 | 15 | | return ConvertCartesianToPolar(new Vector2(x, y)); |
| | 0 | 16 | | } |
| | | 17 | | |
| | 10 | 18 | | public static Vector2 ConvertPolarToCartesian(in Vector2 polar) { |
| | 10 | 19 | | float x = polar.x * Mathf.Cos(polar.y * Mathf.Deg2Rad); |
| | 10 | 20 | | float y = polar.x * Mathf.Sin(polar.y * Mathf.Deg2Rad); |
| | 10 | 21 | | return new Vector2(x, y); |
| | 10 | 22 | | } |
| | 0 | 23 | | public static Vector2 ConvertPolarToCartesian(float r, float theta) { |
| | 0 | 24 | | return ConvertPolarToCartesian(new Vector2(r, theta)); |
| | 0 | 25 | | } |
| | | 26 | | } |