Skip to content

Instantly share code, notes, and snippets.

@markeahogan
Last active June 2, 2021 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markeahogan/7a58c0073a3df919da17b2294facccc4 to your computer and use it in GitHub Desktop.
Save markeahogan/7a58c0073a3df919da17b2294facccc4 to your computer and use it in GitHub Desktop.
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