using System; using UnityEngine; namespace CSharpESP { public static class MathUtils { /// /// Converts a world coordinate into Unity GUI screen coordinates. /// Returns false if the point is behind the camera frustum. /// public static bool WorldToScreen(Camera camera, Vector3 worldPos, out Vector2 screenPos) { screenPos = Vector2.zero; if (camera == null) return false; Vector3 viewPos = camera.WorldToScreenPoint(worldPos); if (viewPos.z <= 0.01f) { return false; } // Invert Y coordinate for GUI coordinate space screenPos = new Vector2(viewPos.x, Screen.height - viewPos.y); return true; } /// /// Calculates the 8 world-space corner vertices of an axis-aligned bounding box. /// public static Vector3[] GetBoundsVertices(Bounds bounds) { Vector3 center = bounds.center; Vector3 ext = bounds.extents; return new Vector3[8] { new Vector3(center.x - ext.x, center.y - ext.y, center.z - ext.z), // 0: Bottom-Left-Back new Vector3(center.x + ext.x, center.y - ext.y, center.z - ext.z), // 1: Bottom-Right-Back new Vector3(center.x + ext.x, center.y - ext.y, center.z + ext.z), // 2: Bottom-Right-Front new Vector3(center.x - ext.x, center.y - ext.y, center.z + ext.z), // 3: Bottom-Left-Front new Vector3(center.x - ext.x, center.y + ext.y, center.z - ext.z), // 4: Top-Left-Back new Vector3(center.x + ext.x, center.y + ext.y, center.z - ext.z), // 5: Top-Right-Back new Vector3(center.x + ext.x, center.y + ext.y, center.z + ext.z), // 6: Top-Right-Front new Vector3(center.x - ext.x, center.y + ext.y, center.z + ext.z) // 7: Top-Left-Front }; } /// /// Computes a screen-aligned 2D rectangle encapsulating the 3D bounds vertices. /// public static bool GetScreenRectFromBounds(Camera camera, Bounds bounds, out Rect screenRect) { screenRect = Rect.zero; Vector3[] vertices = GetBoundsVertices(bounds); float minX = float.MaxValue; float maxX = float.MinValue; float minY = float.MaxValue; float maxY = float.MinValue; bool anyVisible = false; for (int i = 0; i < 8; i++) { if (WorldToScreen(camera, vertices[i], out Vector2 screenPoint)) { minX = Mathf.Min(minX, screenPoint.x); maxX = Mathf.Max(maxX, screenPoint.x); minY = Mathf.Min(minY, screenPoint.y); maxY = Mathf.Max(maxY, screenPoint.y); anyVisible = true; } } if (!anyVisible || maxX <= minX || maxY <= minY) { return false; } screenRect = new Rect(minX, minY, maxX - minX, maxY - minY); return true; } /// /// Calculates distance in meters between camera and target position. /// public static float GetDistance(Camera camera, Vector3 targetPos) { if (camera == null) return 0f; return Vector3.Distance(camera.transform.position, targetPos); } } }