I am having a pickup image which is moving at random direction and have to change the direction after collision with some tiles, which are a rectangle. I've my own algorithm for detecting the collision, but I couldn't accurately calculate new direction. Please have a look at my code for collision detection.
void PickUpManager::CheckPickUpToTileCollision(){
CIwArray<_TILE*> tiles=m_GAME.m_Datamine->m_Tile;
uint16 tileTop,tileLeft, tileBottom, tileRight, pickTop,pickLeft, pickBottom, pickRight;
for(uint32 i=0;i<tiles.size();i++){
tileTop=tiles[i]->m_TilePos.y;
tileLeft=tiles[i]->m_TilePos.x;
tileBottom=tiles[i]->m_TilePos.y+tiles[i]->m_TileSize;
tileRight=tiles[i]->m_TilePos.x+tiles[i]->m_TileSize;
pickTop=m_Pos.y;
pickLeft=m_Pos.x;
pickBottom=m_Pos.y+pickHeight;
pickRight=m_Pos.x+pickWidth;
//Collision from Top of Tile
if(pickBottom>=tileTop && pickBottom<=tileBottom && pickRight>=tileLeft && pickLeft<=tileRight &&!yFlag){
yDir=-PICK_SPEED;
yFlag=true;
}
//Collision from Bottom of Tile
if(pickTop<=tileBottom && pickTop>=tileTop && pickRight>=tileLeft && pickLeft<=tileRight &&!yFlag){
yDir=PICK_SPEED;
yFlag=true;
}
//Collision from Left of Tile
if(pickBottom>=tileTop && pickTop<=tileBottom && pickRight>=tileLeft && pickRight<=tileRight &&!xFlag){
xDir=-PICK_SPEED;
xFlag=true;
}
//Collision from Right of Tile
if(pickBottom>=tileTop && pickTop<=tileBottom && pickLeft<=tileRight && pickLeft>=tileLeft &&!xFlag){
xDir=PICK_SPEED;
xFlag=true;
}
if(xFlag && yFlag)
return;
}
}
void PickUpManager::Move(){
xFlag=false;
yFlag=false;
CheckPickUpToTileCollision();
m_Pos.x+=xDir;
m_Pos.y+=yDir;
}
The problem is the tiles are like bricks making a wall. So if the pickup hit the tile from top left, it changes it's x and y both direction, while the change of direction should be only in the x direction, as there's another tile which ended before this tile. I know it's some stupid problem, but still couldn't make it out.