|
我读一个超级玛丽游戏的源码,好家伙,基本上注释不如不注释,我一句一句地啃,现在差碰撞检测没弄明白,希望高手指点一二,
BOOL CPlane::Collide( int width,
int height,
float startx,
float starty,
float endx,
float endy,
COLLISION *col )
{
int x1, x2, y1, y2;
if( endx > startx )
{
x1 = (int)startx / TILE_W;
x2 = (int)(endx + width) / TILE_W;
}
else
{
x1 = (int)endx / TILE_W;
x2 = (int)(startx + width) / TILE_W;
}
if( endy > starty )
{
y1 = (int)starty / TILE_H;
y2 = (int)(endy + height) / TILE_H;
}
else
{
y1 = (int)endy / TILE_H;
y2 = (int)(starty + height) / TILE_H;
}
col->frac = 2;
for( int x = x1; x <= x2; x ++ )
{
for( int y = y1; y <= y2; y ++ )
{
if( x < 0 || x >= m_width ||
y < 0 || y >= m_height )
continue;
char surf = m_surface[y*m_width+x];
if( surf == SURF_NONE )
continue;
BOX box;
box.minx = (float)(x * TILE_W);
box.miny = (float)(y * TILE_H);
box.maxx = box.minx + TILE_W;
box.maxy = box.miny + TILE_H;
box.minx -= width;
box.miny -= height;
if( Intersect( startx, starty, endx, endy, box, col ) )
{
col->contents = surf;
col->tilex = x;
col->tiley = y;
}
}
}
return (col->frac <= 1 ? TRUE : FALSE);
}
BOOL CSprite::Collide( float startx,
float starty,
CSprite *sprite,
COLLISION *col )
{
BOX box;
sprite->GetBox( box );
box.minx -= m_width;
box.miny -= m_height;
return Intersect( startx, starty, m_x, m_y, box, col );
}
BOOL Intersect( float startx,
float starty,
float endx,
float endy,
BOX &box,
COLLISION *col )
{
float minx = box.minx + 10;
float miny = box.miny + 6;
float maxx = box.maxx;
float maxy = box.maxy;
float frac, sectx, secty;
BOOL ret = FALSE;
startx += 5;
endx += 5;
starty += 3;
endy += 3;
if( startx != endx )
{
if( endx > startx)
sectx = minx;
else
sectx = maxx;
frac = (sectx - startx) / (endx - startx);
if( frac >= 0 && frac <= 1 )
{
secty = starty + (endy - starty) * frac;
if( secty >= miny && secty <= maxy &&
frac < col->frac )
{
ret = TRUE;
col->type = COL_VERT;
col->frac = frac;
if( endx > startx )
sectx --;
else
sectx ++;
col->sectx = sectx;
col->secty = secty;
}
}
}
if( starty != endy )
{
if( endy > starty )
secty = miny;
else
secty = maxy;
frac = (secty - starty) / (endy - starty);
if( frac >= 0 && frac <= 1 )
{
sectx = startx + (endx - startx) * frac;
if( sectx >= minx && sectx <= maxx &&
frac < col->frac )
{
ret = TRUE;
col->type = COL_HORZ;
col->frac = frac;
if( endy > starty )
secty --;
else
secty ++;
col->sectx = sectx;
col->secty = secty;
}
}
}
if( ret )
{
col->sectx -= 5;
col->secty -= 3;
}
return ret;
}
涉及到这3个函数,调用的函数:
COLLISION col;
g_plane.Collide(m_width, m_height, startx, starty, m_x, m_y, &col);
col.sprite = NULL;
for( CSprite *sprite=g_sprites.m_head; sprite; sprite = sprite->m_next )
{
if( sprite->m_action == UPSIDEDOWN )
continue;
if( sprite->m_type == GHOST && sprite->m_action != DEAD ||
sprite->m_type == WALKTURTLE ||
sprite->m_type == FLYTURTLE )
{
if( Collide(startx, starty, sprite, &col) )
col.sprite = sprite;//如果指定精灵和子弹相撞,则精灵被col对象所捕获
}
}
我把源代码放到chongtianerqu@126.com,密码bladeyaone,希望热心人帮助!谢谢! |
|