* @brief Test the collision by the "hot" texture * @author XadillaX * @email admin@xcoder.in * @date 2011/10/18 * @http://xcoder.in * * @param spr1 The first sprite to test the collision * @param x1 "x" of top-left corner of sprite 1 * @param y1 "y" of top-left corner of sprite 1 * @param spr2 The second sprite to test the collision * @param x2 "x" of top-left corner of sprite 2 * @param y2 "y" of top-left corner of sprite 2 * @param hot1 The "hot" texture for sprite 1. It will be the default texture of spr1 if it equal to 0 * @param hot2 The "hot" texture for sprite 2. It will be the default texture of spr2 if it equal to 0 * @param airColor The color which considered of "air" * * @return if they are collided, return true */ bool IsCollision(hgeSprite* spr1, float x1, float y1, hgeSprite* spr2, float x2, float y2, HTEXTURE hot1 = 0, HTEXTURE hot2 = 0, DWORD airColor = 0xffff00ff) { hgeRect r1, r2; r1.Set(x1, y1, x1 + spr1->GetWidth(), y1 + spr1->GetHeight()); r2.Set(x2, y2, x2 + spr2->GetWidth(), y2 + spr2->GetHeight());
if(r1.Intersect(&r2)) { int x[] = { x1, x2, x1 + spr1->GetWidth(), x2 + spr2->GetWidth() }; int y[] = { y1, y2, y1 + spr1->GetHeight(), y2 + spr2->GetHeight() }; std::sort(x, x + 4); std::sort(y, y + 4); hgeRect r;
r.Set(x[1], y[1], x[2], y[2]);
int sx1, sy1, sx2, sy2; sx1 = x[1] - x1; sy1 = y[1] - y1; sx2 = x[1] - x2; sy2 = y[1] - y2;
HTEXTURE hTex1 = hot1; HTEXTURE hTex2 = hot2; if(hTex1 == 0) hTex1 = spr1->GetTexture(); if(hTex2 == 0) hTex2 = spr2->GetTexture();
float tx1, ty1, tw1, th1, tx2, ty2, tw2, th2; int w1 = hge->Texture_GetWidth(hTex1), w2 = hge->Texture_GetWidth(hTex2); spr1->GetTextureRect(&tx1, &ty1, &tw1, &th1); spr2->GetTextureRect(&tx2, &ty2, &tw2, &th2);
DWORD* color1 = new DWORD[(x[2] - x[1]) * (y[2] - y[1])]; DWORD* color2 = new DWORD[(x[2] - x[1]) * (y[2] - y[1])]; DWORD* color;
color = hge->Texture_Lock(hTex1, true); for(int i = 0; i < y[2] - y[1]; i++) { for(int j = 0; j < x[2] - x[1]; j++) { color1[i * (x[2] - x[1]) + j] = color[((int)ty1 + sy1) * w1 + (int)tx1 + sx1 + i * w1 + j]; } } hge->Texture_Unlock(hTex1);
color = hge->Texture_Lock(hTex2, true); for(int i = 0; i < y[2] - y[1]; i++) { for(int j = 0; j < x[2] - x[1]; j++) { color2[i * (x[2] - x[1]) + j] = color[((int)ty2 + sy2) * w2 + (int)tx2 + sx2 + i * w1 + j]; } } hge->Texture_Unlock(hTex2);
for(int i = 0; i < y[2] - y[1]; i++) { for(int j = 0; j < x[2] - x[1]; j++) { if(color1[i * (x[2] - x[1]) + j] != airColor && color2[i * (x[2] - x[1]) + j] != airColor) { delete []color1; delete []color2;
return true; } } }
delete []color1; delete []color2; return false; } else return false; }
|