My collision detection is inconsistent. I am testing between 2 rectangles. When they are un-rotated, it says they are intersecting way before they touch, but when I rotate one, it works properly. I do not understand why.
When rect1 is rotated 0 or 180 degrees it starts saying collision detected about one rect width apart, but when its rotated at a non 90 degree angle, it works properly.
// storing rotated points in lists for easy looping to avoid duplicate code
FixedList512<float2> points1 = new FixedList512<float2>();
points1.Add( bl_r );
points1.Add( br_r );
points1.Add( tl_r );
points1.Add( tr_r );
FixedList512<float2> points2 = new FixedList512<float2>();
points2.Add( bl_r2 );
points2.Add( br_r2 );
points2.Add( tl_r2 );
points2.Add( tr_r2 );
bool intersects = true;
for ( int shape = 0; shape < 2; shape++ )
{
if ( shape == 1 )
{
var temp = new FixedList512<float2>();
temp.Add( bl_r );
temp.Add( br_r );
temp.Add( tl_r );
temp.Add( tr_r );
points1 = points2;
points2 = temp;
}
for ( int a = 0; a < points1.Length; a++ )
{
int b = ( a + 1 ) % points1.Length;
float2 axisProjection = new float2( -( points1[ b ].y - points1[ a ].y ) , points1[ b ].x - points1[ a ].x ); // invert points for normal to line segement
float minR1 = float.MaxValue;
float maxR1 = -float.MaxValue;
for ( int p = 0; p < points1.Length; p++ )
{
float q = points1[ p ].x * axisProjection.x + points1[ p ].y * axisProjection.y; // dot product of current point and axis of projection
minR1 = math.min( minR1 , q );
maxR1 = math.max( maxR1 , q );
}
float minR2 = float.MaxValue;
float maxR2 = -float.MaxValue;
for ( int p = 0; p < points2.Length; p++ )
{
float q = points2[ p ].x * axisProjection.x + points2[ p ].y * axisProjection.y; // dot product of current point and axis of projection
minR2 = math.min( minR2 , q );
maxR2 = math.max( maxR2 , q );
}
if ( !( maxR2 >= minR1 && maxR1 >= minR2 ) ) // break if points dont overlap as we dont have a collision
{
intersects = false;
break;
}
}
}
if ( intersects )
{
Debug.Log( "Intersects" );
}
```