sprat r,m; void setup(){ size(400,400); String[] a = {"lam.gif","lin.gif"}; m = new sprat(220,230,a); r = new sprat(229,200,"lin.gif"); } int c; void draw(){ m.x = mouseX; m.y = mouseY; c++; if(c % 50 == 0){ m.changeframe(m.currentframe==0?1:0); } if(m.overlap(r)){ background(255,0,0); } else { background(128); } r.draw(); m.draw(); } class sprat{ int x,y,w,h; int framecount; int currentframe; PImage img[]; sprat(int px,int py, String imgname){ String s[] = new String[1]; s[0] = imgname; init(px,py,s); } sprat(int px,int py, String[] imgname){ init(px,py,imgname); } void init (int px,int py, String[] imgname){ x = px; y = py; img = new PImage[imgname.length]; for(int i = 0; i < imgname.length; i++){ img[i] = loadImage(imgname[i]); } changeframe(0); } void changeframe(int whatframe){ currentframe = whatframe; w = img[currentframe].width; h = img[currentframe].height; } void draw(){ image(img[currentframe],x,y); } //so we have a physical x and y on screen //find the pixel for this thing //WARNING no bounds checking color pixelAtPhysicalLocation(int px, int py){ int rx = px - x; int ry = py - y; return img[currentframe].pixels[rx + (ry * w)]; } boolean overlap(sprat other){ intRange vOverlap = spratOverlapVert(other); intRange hOverlap = spratOverlapHoriz(other); if(vOverlap == null || hOverlap == null){ return false; } //hrrm, why couldn't this be <= ???? for(int a = hOverlap.min; a < hOverlap.max; a++){ for(int b = vOverlap.min; b < vOverlap.max; b++){ if(alpha(this.pixelAtPhysicalLocation(a,b)) > 128 && alpha(other.pixelAtPhysicalLocation(a,b)) > 128 ){ return true; } } } return false; } // to see if things overlap on one dimension // we sort the 4 points. if both points of // one thing are lesser than both points of the other, // they can't be overlapping... intRange spratOverlapHoriz(sprat b){ sprat a = this; intWithRef vals[] = new intWithRef[4]; vals[0] = new intWithRef((int)a.x,a); vals[1] = new intWithRef((int)(a.x+a.w),a); vals[2] = new intWithRef((int)b.x,b); vals[3] = new intWithRef((int)(b.x+b.w),b); Arrays.sort(vals); if (vals[0].src == vals[1].src){ return null; } return new intRange(vals[1].val,vals[2].val); } intRange spratOverlapVert(sprat b){ sprat a = this; intWithRef vals[] = new intWithRef[4]; vals[0] = new intWithRef((int)a.y,a); vals[1] = new intWithRef((int)(a.y+a.h),a); vals[2] = new intWithRef((int)b.y,b); vals[3] = new intWithRef((int)(b.y+b.h),b); Arrays.sort(vals); if (vals[0].src == vals[1].src){ return null; } return new intRange(vals[1].val,vals[2].val); } } class intRange{ int min, max; intRange(int p1, int p2){ min = p1p2?p1:p2; } } class intWithRef implements Comparable{ int val; Object src; intWithRef(int pval,Object psrc){ val = pval; src = psrc; } public int compareTo(Object o){ return val - ((intWithRef)o).val; } }