# Change of direction after Collision

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.

## 1 Answer

What you need to do is reflect the velocity vector in the normal of the collision. If it's a wall, then the normal is the normal of the wall (which direction it is facing). So if you know which side of the tile was hit, then you can work out the normal for that side.

To reflect the vector you need to use the dot product to calculate the resultant vector to use as the new velocity. Vector Reflection.

If you don't know the normal of the surface there are also ways to calculate it from the two points which define the tile edge. Calculating Normals.