Reputation: 67
I am aware that there are other solutions to this problem, but I am learning and for that purpose would like to understand why my algorithm doesn't work
Here is how my solution works:
It gets the coordinates for the 4 vertices of each rectangle, translates them so they are relative to 0, 0 rather than the rectangles' origins, and rotates them respectively using these formulas:
rotatedX = unrotatedX * cos( radiansOfCounterClockwiseRotation ) -
unrotatedY * sin( radians );
and
rotatedY = unrotatedX * sin( radians ) + y * cos( radians );
and translates them so they are relative to their rectangles' origins
Then it calculates x and y values of the axis to compare separation on by subtracting the upper left, and lower right vertices' coordinates from those of the upper right vertice, for a total of 4 axis (1 for each pair of parallel edges of the 2 rectangles)
Then it calculates an x value for each of the rotated vertices, which lies on the axis, using this formula:
x = -( -( axis.x / axis.y ) * vertice.x - vertice.y ) /
( axis[i].y / axis[i].x + axis[i].x / axis[i].y );
which is derived from getting the point of intersection between the axis line and the line perpendicular to the axis that passes through the vertice
It compares these values for each axis and checks whether:
maxXValueForRect0 >= minXValueForRect1 AND minXValueForRect0 <= maxXValueForRect1;
if that is true for every axis, then there is a collision
However, during debugging I discovered that the min x values area always lower than the max x values, regardless of positions and sizes of the rectangles
Can anyone tell me what is wrong here?
Upvotes: 0
Views: 588
Reputation: 67
This works perfectly and I made an intensely minor error in my code itself that caused both groups of vertices to be translated relative to the first rectangle after their rotation. So the logic presented here is solid and will work provided you don't make a silly mistake like I did :D
Upvotes: 0