android 学习:多矩形碰撞检测

来源:互联网 发布:夏米d5支持电信网络吗 编辑:程序博客网 时间:2024/04/20 13:53

1. 检测两个矩形是否重叠

public class RectCollision {/** * @return true 相交 */public static boolean isCollision(Rect[] rectArray, Rect[] rect2Array) {for (Rect r1 : rectArray) {for (Rect r2 : rect2Array) {if (isCollision(r1, r2))return true;}}return false;}/** * r1在r2的上面,下面,左面,右面 * r1和r2相交 * @param r1 * @param r2 * @returntrue 相交 */public static boolean isCollision(Rect r1, Rect r2) {int x1 = r1.left;int y1 = r1.top;int w1 = r1.right - r1.left;int h1 = r1.bottom - r1.top;int x2 = r2.left;int y2 = r2.top;int w2 = r2.right - r2.left;int h2 = r2.bottom - r2.top;if (y1+h1 < y2 /*上*/ || x1+w1 < x2 /*左*/ || y2+h2 < y1 /*下*/|| x2+w2 < x1 /*右*/) {return false;}return true;}}

2. 效果


好久没写算法了,一个矩形检测都想半天,看来ACM有时候还是要练练。

0 0