Checking if rectangles intercect only working if they intersect on first check
-
20-12-2019 - |
Question
public void update() {
speedY = bg.getSpeedY() / 2;
tileY += speedY;
r.set(tileX, tileY, 50, 48);
// Collision with cycle here:
if (tileY > 480) {
r = null;
}
if (tileY < 480) {
checkCollision();
}
}
private void checkCollision() {
if (type != 0) {
boolean val = Rect.intersects(Cycle.rect, r);
if (val) {
test = true;
}
}
}
Using the debugger I determined that all the Rectangles are updating correctly, and the Cycle.rect returns the correct rectangle location. If the rectangles are intersecting on the very first check it works fine. However, as the update runs the intersects never returns true. Why might this be happening? I used the boolean val only to help in debugging.
I Logged two values where I believe the rectangles should be intersecting but is not:
r: 02-24 23:32:50.762: V/Rect(16624): Rect(50, 314 - 50, 48) Cycle.rect: 02-24 23:32:50.762: V/Rect(16624): Rect(49, 329 - 100, 100)
Solution
The problem lies on the coordinate system in Java, where top-left is considered as 0. Therefore, a Rect
is "defined" if top
coordinate is less than bottom
. Otherwise, it's considered as empty.
From Rect API reference,
Note: most methods do not check to see that the coordinates are sorted correctly (i.e. left <= right and top <= bottom).
Also for set()
(note: emphasize on mine),
Set the rectangle's coordinates to the specified values. Note: no range checking is performed, so it is up to the caller to ensure that left <= right and top <= bottom.
And isEmpty()
Returns true if the rectangle is empty (left >= right or top >= bottom)