Quadtree/BoundingBox2.cs

82 lines
2.2 KiB
C#

using System.Numerics;
namespace Quadtree
{
public enum IntersectionType { Contains, Intersects, Disjoint }
public class BoundingBox2
{
/// <summary>
/// Vector containing the lowest X and Y coordinates contained in the bounding box.
/// </summary>
public Vector2 Min;
/// <summary>
/// Vector containing the highest X and Y coordinates contained in the bounding box.
/// </summary>
public Vector2 Max;
public Vector2 Center => (Max + Min) * 0.5f;
public Vector2 Size => Max - Min;
public BoundingBox2(Vector2 min, Vector2 max)
{
Min = min;
Max = max;
}
public bool Contains(Vector2 position)
{
return Min.X <= position.X && position.X <= Max.X && Min.Y <= position.Y && position.Y <= Max.Y;
}
public IntersectionType Intersects(BoundingBox2 other)
{
if (Min.X <= other.Min.X && other.Max.X <= Max.X && Min.Y <= other.Min.Y && other.Max.Y <= Max.Y)
{
return IntersectionType.Contains;
}
if ((other.Max.X <= Min.X || Max.X <= other.Min.X) && (other.Max.Y <= Min.Y || Max.Y <= other.Min.Y))
{
return IntersectionType.Disjoint;
}
return IntersectionType.Intersects;
}
public void Translate(Vector2 translation)
{
Min += translation;
Max += translation;
}
public void Expand(float expansion)
{
Min.X -= expansion;
Min.Y -= expansion;
Max.X += expansion;
Max.Y += expansion;
}
public void Include(Vector2 position)
{
if (Min.X > position.X)
{
Min.X = position.X;
}
else if (Max.X < position.X)
{
Max.X = position.X;
}
if (Min.Y > position.Y)
{
Min.Y = position.Y;
}
else if (Max.Y < position.Y)
{
Max.Y = position.Y;
}
}
}
}