Skip to content

Commit

Permalink
Add tests for Plane.Raycast() extension
Browse files Browse the repository at this point in the history
  • Loading branch information
Exanite committed Jul 4, 2024
1 parent fdaaccb commit f1a2a82
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
28 changes: 28 additions & 0 deletions Tests/Utilities/MathUtilityTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#endif

using System.Numerics;
using Exanite.Core.Numerics;
using Exanite.Core.Utilities;
using NUnit.Framework;

Expand Down Expand Up @@ -79,5 +80,32 @@ public void CreatePlane_ReturnsExpectedResult2()
Assert.IsTrue(MathUtility.IsApproximatelyEqual(-1, plane.D));
Assert.IsTrue(MathUtility.IsApproximatelyEqual(Vector3.UnitX, plane.Normal));
}

[TestCase]
public void PlaneRaycast_ReturnsExpectedResult1()
{
var expectedDistance = 10;
var expectedPosition = new Vector2(1, 2);

var plane = MathUtility.CreatePlane(Vector3.UnitZ, Vector3.Zero);
var ray = new Ray(new Vector3(expectedPosition.X, expectedPosition.Y, -expectedDistance), Vector3.UnitZ, 0);

var isHit = plane.Raycast(ray, out var distance);

Assert.IsTrue(isHit);
Assert.IsTrue(MathUtility.IsApproximatelyEqual(expectedDistance, distance));
Assert.IsTrue(MathUtility.IsApproximatelyEqual(expectedPosition.Xy0(), ray.GetPoint(distance)));
}

[TestCase]
public void PlaneRaycast_ReturnsExpectedResult2()
{
var plane = MathUtility.CreatePlane(Vector3.UnitZ, Vector3.Zero);
var ray = new Ray(new Vector3(1, 2, -10), -Vector3.UnitZ, 0);

var isHit = plane.Raycast(ray, out _);

Assert.IsFalse(isHit);
}
}
}
9 changes: 7 additions & 2 deletions Utilities/MathUtility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -286,21 +286,26 @@ public static Plane CreatePlane(Vector3 normal, Vector3 position)
return new Plane(normal, distance);
}

/// <summary>
/// Casts a ray against the specified plane.
/// <para/>
/// The ray's length is ignored during this check.
/// </summary>
public static bool Raycast(this Plane plane, Ray ray, out float distance)
{
var vdot = Vector3.Dot(ray.Direction, plane.Normal);
var ndot = -Vector3.Dot(ray.Origin, plane.Normal) - plane.D;

if (IsApproximatelyEqual(vdot, 0f))
{
distance = 0.0F;
distance = 0f;

return false;
}

distance = ndot / vdot;

return distance > 0.0F;
return distance > 0f;
}

#endregion
Expand Down

0 comments on commit f1a2a82

Please sign in to comment.