Reputation: 1211
I want to make a game where the character is a rectangular prism that can be rotated, and the rest of the map are axis-aligned rectangular prisms. Everything other than the character will be static, so I was wondering what would be the best algorithm for finding if the character is colliding with any parts in the map. Any tutorials/code/advice would be much appreciated :)
Also, the character will only be rotated on the Y axis, if that helps.
Upvotes: 1
Views: 1678
Reputation: 3636
I believe one way to test for this is to check the 16 cases of line intersections:
http://www.math.niu.edu/~rusin/known-math/95/line_segs
If you want to optimize you could also check if the rectangles have no chance of overlapping, i.e. if all corners are to the right/left/above/below of the other rectangle.
Edit:
Se comment below.
Upvotes: 0
Reputation: 8823
In the special case that the character only rotates around its axis parallel to the Y-axis, the collision detection with another axis-aligned rectangular prism reduces to:
Check if the character's Y-interval intersects the other prism's Y-interval.
Check if the corresponding XZ-cross-sections of the two prisms intersect, which amounts to a problem of collision detection between two rotated rectangles.
If the answer to both the above is yes, then and only then do the prisms overlap.
Having reduced the particular problem to that of overlapping intervals and intersecting (rotated) rectangles, there are a number of good code resources for each of these tasks. The first task is pretty trivial:
Overlapping intervals
Two closed intervals [a,b] and [c,d] intersect if and only c ≤ b and a ≤ d. Here we also assume the intervals' notation is consistent, i.e. that a ≤ b and c ≤ d (otherwise swap the endpoints as necessary to make it so).
Intersecting rotated rectangles
A highly rated SO answer to this specific question is here. A Lua implementation I wrote for a slightly more general problem, Shortest distance between two rectangles, includes "early exit" optimizations (bounding circle and vertex in rectangle) that I mentioned on this thread. My Lua code returns "false" if the rotated rectangles intersect, otherwise the distance between them. For Java purposes the return value of zero in the collision cases would serve.
Upvotes: 0