In my two tests you will see a ray/rectangle intersection test, one is working fine, the other one not. I do not understand why the result ist false, because the ray obviously hits the rectangle.
Perhaps i really miss something here and i hope you can give me a hint.
[Fact]
public void TestRayAgainstRectangle_DoesNotWork()
{
var ray = new Ray2(new Vector2(33.0f, 33.0f), new Vector2(-0.45f, -0.55f));
var rect = new RectangleF(0, 0, 32, 32);
//this is false
var b = ray.Intersects(rect, out float near, out float dist);
Assert.True(b);
}
[Fact]
public void TestRayAgainstRectangle_DoesWork()
{
var ray = new Ray2(new Vector2(33.0f, 33.0f), new Vector2(-0.5f, -0.5f));
var rect = new RectangleF(0, 0, 32, 32);
//this is true
var b = ray.Intersects(rect, out float near, out float dist);
Assert.True(b);
}
Where is the source-Code of Ray2? I can’t find it on github.
I would calculate it this way:
Calculate the normal of the ray.
Calculate the lines between the ray origin and the every corner of the rectangle.
Calculate the dot-product between the ray-normal and every corner-line.
if all results are positive or all are negative, than there is no intersection.
Otherwise the ray intersect the rectangle.
Hope this helps.
Yes, both rays should intersect in your example.
The idea behind the above source code seems to be, that the distance-scale of the ray must be in both directions the same (x and y). May be, in one of these (few) calculation steps is an unexpected result.
You can find it out by copying the source code of the two used functions in your programm and trace all result-steps.
Or you use the method I decribed in my first answer.
Good luck!