Add Contains Vector2 method to Box2Rotated (#1851)

This commit is contained in:
metalgearsloth
2021-07-11 22:49:59 +10:00
committed by GitHub
parent aea5f83002
commit e0b1a7d64a
2 changed files with 52 additions and 0 deletions

View File

@@ -149,6 +149,26 @@ namespace Robust.Shared.Maths
return new Box2(X0, Y0, X1, Y1);
}
public bool Contains(Vector2 worldPoint)
{
// Get the worldpoint in our frame of reference so we can do a faster AABB check.
var localPoint = GetLocalPoint(worldPoint);
return Box.Contains(localPoint);
}
/// <summary>
/// Convert a point in world-space coordinates to our local coordinates.
/// </summary>
private Vector2 GetLocalPoint(Vector2 point)
{
// Could make this more efficient but works for now I guess...
var boxCenter = Box.Center;
var result = point - boxCenter;
result = Origin + Rotation.RotateVec(result - Origin);
return result + boxCenter;
}
#region Equality
/// <inheritdoc />

View File

@@ -77,5 +77,37 @@ namespace Robust.UnitTesting.Shared.Maths
var rotated = new Box2Rotated(baseBox, rotation, origin);
Assert.That(rotated.CalcBoundingBoxSse(), Is.Approximately(expected));
}
// Offset it just to make sure the rotation is also gucci.
private static readonly Vector2 Offset = new Vector2(10.0f, 10.0f);
private static Box2Rotated IntersectionBox = new(Box2.UnitCentered.Translated(Offset), Angle.FromDegrees(45));
private static IEnumerable<Vector2> InboundPoints => new Vector2[]
{
Offset,
Offset - new Vector2(-0.5f, 0.0f),
Offset + new Vector2(0.1f, 0.1f),
};
[Test]
public void TestPointIntersect([ValueSource(nameof(InboundPoints))] Vector2 point)
{
Assert.That(IntersectionBox.Contains(point), $"Rotated box doesn't contain {point}");
}
private static IEnumerable<Vector2> OutboundPoints => new Vector2[]
{
Offset + new Vector2(-0.48f, -0.48f),
Offset + new Vector2(-0.48f, 0.48f),
Offset + new Vector2(0.48f, 0.48f),
Offset + new Vector2(0.48f, -0.48f),
};
[Test]
public void TestPointNoIntersect([ValueSource(nameof(OutboundPoints))] Vector2 point)
{
Assert.That(!IntersectionBox.Contains(point), $"Rotated box contains {point}");
}
}
}