Created
January 12, 2023 23:36
-
-
Save gustavopsantos/e142f66d5c573e4746ef115206415e8d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public static class GetBoundsAtScreenSpace | |
{ | |
private static readonly List<Vector3> _localSpaceVerticesBuffer = new List<Vector3>(); | |
public static Bounds Get(MeshFilter meshFilter, Camera camera) | |
{ | |
var mesh = meshFilter.sharedMesh; | |
mesh.GetVertices(_localSpaceVerticesBuffer); | |
var worldToClipMatrix = camera.projectionMatrix * camera.worldToCameraMatrix * meshFilter.transform.localToWorldMatrix; | |
Span<Vector3> screenSpaceVertices = stackalloc Vector3[mesh.vertexCount]; | |
for (int i = 0; i < mesh.vertexCount; i++) | |
{ | |
var clipSpaceVertex = worldToClipMatrix.MultiplyPoint(_localSpaceVerticesBuffer[i]); | |
screenSpaceVertices[i] = ClipToScreenPoint(clipSpaceVertex); | |
} | |
var minX = float.MaxValue; | |
var maxX = float.MinValue; | |
var minY = float.MaxValue; | |
var maxY = float.MinValue; | |
foreach (var vertex in screenSpaceVertices) | |
{ | |
minX = Mathf.Min(minX, vertex.x); | |
maxX = Mathf.Max(maxX, vertex.x); | |
minY = Mathf.Min(minY, vertex.y); | |
maxY = Mathf.Max(maxY, vertex.y); | |
} | |
var center = new Vector2((minX + maxX) / 2f, (minY + maxY) / 2f); | |
var size = new Vector2(maxX - minX, maxY - minY); | |
return new Bounds(center, size); | |
} | |
private static Vector3 ClipToScreenPoint(Vector3 point) | |
{ | |
// Clip -> Viewport / (-1, +1) -> (0, 1) | |
var viewportSpaceX = (point.x + 1f) / 2f; | |
var viewportSpaceY = (point.y + 1f) / 2f; | |
var viewportSpaceZ = (point.z + 1f) / 2f; | |
// Viewport -> Screen / (0, 1) -> (0, Resolution) | |
var screenSpaceX = viewportSpaceX * Screen.width; | |
var screenSpaceY = viewportSpaceY * Screen.height; | |
return new Vector3(screenSpaceX, screenSpaceY, viewportSpaceZ); // (0, Resolution) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment