在使用android 做一些小游戏的时候,可能需要用到碰撞检测,而矩形的
Rect.intersect(Rect a)方法可能被用到
但是需要注意的是:这个方法是用来取两个矩形的相交部分,并设置给Rect
/**
* If the rectangle specified by left,top,right,bottom intersects this
* rectangle, return true and set this rectangle to that intersection,
* otherwise return false and do not change this rectangle. No check is
* performed to see if either rectangle is empty. Note: To just test for
* intersection, use {@link #intersects(Rect, Rect)}.
*
* @param left The left side of the rectangle being intersected with this
* rectangle
* @param top The top of the rectangle being intersected with this rectangle
* @param right The right side of the rectangle being intersected with this
* rectangle.
* @param bottom The bottom of the rectangle being intersected with this
* rectangle.
* @return true if the specified rectangle and this rectangle intersect
* (and this rectangle is then set to that intersection) else
* return false and do not change this rectangle.
*/
@CheckResult
public boolean intersect(int left, int top, int right, int bottom) {
if (this.left < right && left < this.right && this.top < bottom && top < this.bottom) {
if (this.left < left) this.left = left;
if (this.top < top) this.top = top;
if (this.right > right) this.right = right;
if (this.bottom > bottom) this.bottom = bottom;
return true;
}
return false;
}
如果不知道这一点,在写游戏时会发现有时候碰撞检测没有作用,很是恼火。
正确的应该使用这一个方式:
/**
* Returns true if this rectangle intersects the specified rectangle.
* In no event is this rectangle modified. No check is performed to see
* if either rectangle is empty. To record the intersection, use intersect()
* or setIntersect().
*
* @param left The left side of the rectangle being tested for intersection
* @param top The top of the rectangle being tested for intersection
* @param right The right side of the rectangle being tested for
* intersection
* @param bottom The bottom of the rectangle being tested for intersection
* @return true iff the specified rectangle intersects this rectangle. In
* no event is this rectangle modified.
*/
public boolean intersects(int left, int top, int right, int bottom) {
return this.left < right && left < this.right && this.top < bottom && top < this.bottom;
}
在调试时,可以将Rect 以红色画出来,方便观察。