Hey all, I'm making a very simple game library, designed to make games like the ZX Spectrum ones Jet Set Willy, Manic Miner, Jetpac, etc. The way it works is similar to the D3DX Framework. The user links with my .lib and derives from CApplication. For sprites, they derive from CSprite and set the sprites size, position and velocity. The base application processes all sprites every frame, updates their position, and checks for collisions.
I've never needed to do collision detection before, and I'm a bit stuck for ideas how to go about it. A sprite could be stationary (for triggers and things), it could move at a reasonable speed (the player), or it could move across the entire screen in one frame (bullets, etc).
There could be any number of sprites on screen at once, but anything over 500 or so will be way too many. I'd expect an average of 50 sprites on screen at once.
Here's what I have at the moment (just for testing really). It only matches collisions if they happen during that frame (not between frames), and it doesn't adjust the sprites position so it doesn't intersect the object:
for(DWORD i=0; i<m_vSprites.size(); ++i)
{
// Update position //
m_vSprites->m_vPos += (m_vSprites->m_vVelocity*(float)(dTime/1000.0));
// Call update tick //
m_vSprites->Tick(dTime);
// Render textured sprites //
if(m_vSprites->m_pTexture)
{
D3DXVECTOR3 vPos(m_vSprites->m_vPos.x,m_vSprites->m_vPos.y,0.0f);
D3D_CHECK(m_pSprite->Draw(m_vSprites->m_pTexture->GetTexture(),
&m_vSprites->m_rcTexture,NULL,&vPos,0xffffffff));
}
// Check for collisions //
for(DWORD j=0; j<i; ++j)
{
SpectrumRect rcFirst(m_vSprites->m_vPos.x,m_vSprites->m_vPos.y,m_vSprites->m_vSize.x,m_vSprites->m_vSize.y);
SpectrumRect rcSecond(m_vSprites[j]->m_vPos.x,m_vSprites[j]->m_vPos.y,m_vSprites[j]->m_vSize.x,m_vSprites[j]->m_vSize.y);
if(CheckCollision(rcFirst,rcSecond))
{
m_vSprites->OnCollision(m_vSprites[j]);
m_vSprites[j]->OnCollision(m_vSprites);
}
}
}
CheckCollision() is very hacky and converts the 2 parameters to RECT structures, and then checks for collisions with IntersectRect().
So, does anyone have any suggestions how I should do collision detection? I need to loop through all the sprites, and check for collisions with other sprites. But I need to see if the sprite collided with several other sprites in the frame (a bullet may pass through several sprites), and process the collisions in order.
I don't really know how to go about checking for collisions between frames. I supppose I could form a rectangle of possible collisions like this, where p1 is the initial position, p2 is the end position, and a, b and c are objects in the colision rectangle:
+--+--------------+
|p1| a |
+--+ |
| b |
| +--+
| c |p2|
+--------------+--+
But then, I'm a stuck on how to check for collisions in that ractangle.
Thanks in advance,
Steve