I'm currently writing a game which is like Battle City game. But right now I'm facing a trouble involved to checking collision between two objects. This is the code that I wrote:
//-------------------------------------------------------------------------------------------
// check collision between a tank and another object
//
bool GameController::checkTankMeetsObject(Tank tank, GameObject ob)
{
int obX = ob.getCoord().getX();
int obY = ob.getCoord().getY();
// calculate area of obstacle: bottom left (X1, Y1), top right (X2, Y2)
int obX1 = obX - SQUARESIZE / 2;
int obX2 = obX + SQUARESIZE / 2;
int obY1 = obY - SQUARESIZE / 2;
int obY2 = obY + SQUARESIZE / 2;
int tankX = tank.getCoord().getX();
int tankY = tank.getCoord().getY();
switch (tank.getDir())
{
case UP:
if ((tankX < obX2 + SQUARESIZE / 2 && tankX > obX1 - SQUARESIZE / 2) &&
(tankY + SQUARESIZE / 2 > obY1 && tankY + SQUARESIZE / 2 < obY2))
return true;
break;
case DOWN:
if ((tankX < obX2 + SQUARESIZE / 2 && tankX > obX1 - SQUARESIZE / 2) &&
(tankY - SQUARESIZE / 2 > obY1 && tankY - SQUARESIZE / 2 < obY2))
return true;
break;
case LEFT:
if ((tankX - SQUARESIZE / 2 < obX2 && tankX - SQUARESIZE / 2 > obX1) &&
(tankY > obY1 - SQUARESIZE / 2 && tankY < obY2 + SQUARESIZE / 2))
return true;
break;
case RIGHT:
if ((tankX + SQUARESIZE / 2 < obX2 && tankX + SQUARESIZE / 2 > obX1) &&
(tankY > obY1 - SQUARESIZE / 2 && tankY < obY2 + SQUARESIZE / 2))
return true;
break;
}
return false;
}
This code does well with normal circumstance, but in special ones like which I describe below, it doesn't work.
The white squares are obstacles and the grey square is the tank. Current direction of the tank is RIGHT. In this situation, I can not move the tank RIGHT or LEFT, only direction I can go is DOWN. Is there any solution to optimize my code?
No comments:
Post a Comment