几种矩形碰撞算法

找了几种碰撞检测算法,个人感觉,效率是一致的,因为个人认为总是没有碰撞的几率要多得多! 

【碰撞检测】

【sun的sprite实现:】

    /**
     * Detect rectangle intersection
     *
     * @param r1x1 left co-ordinate of first rectangle
     * @param r1y1 top co-ordinate of first rectangle
     * @param r1x2 right co-ordinate of first rectangle
     * @param r1y2 bottom co-ordinate of first rectangle
     * @param r2x1 left co-ordinate of second rectangle
     * @param r2y1 top co-ordinate of second rectangle
     * @param r2x2 right co-ordinate of second rectangle
     * @param r2y2 bottom co-ordinate of second rectangle
     * @return True if there is rectangle intersection
     */
    private boolean intersectRect(int r1x1, int r1y1, int r1x2, int r1y2,
                                  int r2x1, int r2y1, int r2x2, int r2y2) {
        if (r2x1 >= r1x2 || r2y1 >= r1y2 || r2x2 <= r1x1 || r2y2 <= r1y1) {
            return false;
        } else {
            return true;
        }
    }

【一种实现】

/*

RectX;去做碰撞的矩形左上顶点x坐标

RectY;去做碰撞的矩形左上顶点y坐标

RectWidth;去做碰撞的矩形的宽度

RectHeight;去做碰撞的矩形的高度

ObjX;被碰撞的矩形左上顶点的x坐标

ObjY;被碰撞的矩形左上顶点的y坐标

ObjWidth;被碰撞的矩形的宽度

ObjHeight;被碰撞的矩形的高度

*/

public boolean isCollide(int RectX,int RectY,int RectWidth,int RectHeight,int ObjX,int ObjY,int ObjWidth,int ObjHeight){

    if((RectX+RectWidth>ObjX)&&(RectX<ObjX+ObjWidth)&&
        (RectY+RectHeight>ObjY)&&(RectY<ObjY+ObjHeight))

        return true;//true表示两个矩形发生了碰撞

    return false;

}

【另外一种】

ax ay aw ah 分别是矩形的左顶点X Y坐标和矩形的 长和宽

public static final boolean isIntersectingRect(int ax, int ay,
    int aw, int ah,
    int bx, int by,
    int bw, int bh)
{
    if (by + bh < ay || // is the bottom b above the top of a?
    by > ay + ah || // is the top of b below bottom of a?
    bx + bw < ax || // is the right of b to the left of a?
    bx > ax + aw) // is the left of b to the right of a?
        return false;
    
    return true;
}