Last active
June 2, 2021 11:36
-
-
Save markeahogan/7a58c0073a3df919da17b2294facccc4 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 UnityEngine; | |
public static class BoundsExtensions | |
{ | |
/// <summary> | |
/// Modifies the bounds center position so that it's min and max are within the container | |
/// It doesnt modify the bounds size, if bounds are larger then the container it will be centered | |
/// </summary> | |
public static void MoveInside(ref this Bounds bounds, Bounds container) | |
{ | |
bounds.center = ClampWithSize(bounds.center, bounds.size, container.min, container.max); | |
} | |
private static Vector3 ClampWithSize(Vector3 center, Vector3 size, Vector3 min, Vector3 max) | |
{ | |
for (int i = 0; i < 3; i++) { center[i] = ClampWithSize(center[i], size[i], min[i], max[i]); } | |
return center; | |
} | |
private static float ClampWithSize(float center, float size, float min, float max) | |
{ | |
float containerSize = max - min; | |
//if the size cant be contained in the other put it in the middle | |
if (size > containerSize) { return containerSize * 0.5f + min; } | |
float extent = size * 0.5f; | |
return Mathf.Clamp(center, min + extent, max - extent); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment