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;
}
}
}
使用调试器,我确定所有矩形都正确更新,并且 Cycle.rect 返回正确的矩形位置。如果矩形在第一次检查时相交,则效果很好。但是,当更新运行时,相交永远不会返回 true。为什么会发生这种情况?我使用 boolean 值只是为了帮助调试。
我记录了两个值,我认为矩形应该相交,但事实并非如此:
r: 02-24 23:32:50.762: V/矩形(16624): 矩形(50, 314 - 50, 48) Cycle.rect: 02-24 23:32:50.762: V/矩形(16624): 矩形(49, 329 - 100, 100)最佳答案
问题在于 Java 中的坐标系,其中左上角被视为 0。因此,如果 top
坐标为 ,则 Rect
被“定义” >小于底部
。否则,它被认为是空的。
Note: most methods do not check to see that the coordinates are sorted correctly (i.e. left <= right and top <= bottom).
也适用于set()
(注意:强调我的),
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.
和isEmpty()
Returns true if the rectangle is empty (left >= right or top >= bottom)
关于java - 检查矩形是否相交仅在第一次检查时相交时才起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22004260/