2D Collision Detection Problem

while making my game called "Journeys of Nemo the Fish" i stumbled upon a collision detection problem. Please, help me to solve it.

The problem is: the program runs only the first if statement adjusting the coordinates of the player without taking in consideration what type of collision occurred.

Here is my code:

short int py = player.getPosition().y;
short int px = player.getPosition().x;
short int pw = player.getGlobalBounds().width;
short int ph = player.getGlobalBounds().height;

for (int i = 0; i < block.size(); i++) {
short int by = block[i].getPosition().y;
short int bx = block[i].getPosition().x;
short int bw = block[i].getGlobalBounds().width;
short int bh = block[i].getGlobalBounds().height;

if (player.getGlobalBounds().intersects(block[i].getGlobalBounds())) {
// UP and DOWN
if (px+pw > bx && px < bx+bw) {
if (py < by+bh && py > by) {
py = by + bh;
} else if (py+ph > by && py < by) {
py = by - ph;
}
}

break;
}

if (player.getGlobalBounds().intersects(block[i].getGlobalBounds())) {
//LEFT and RIGHT
if (py+ph > by && py < by+bh) {
if (px < bx+bw && px+pw > bx+bh) {
px = bx + bw;
} else if (px+pw > bx && px < bx) {
px = bx - pw;
}
}

break;
}
}

Here is a link to the video: Journeys of Nemo the Fish.

EDITED

When a collision occurs

if (px+pw > bx && px < bx+bw) {

Will be true in the two collision types. There is no way to know wich type of collision is. I would create a new variable called typeOfMovement to know wether fish is moving up/down or left/right

short int py = player.getPosition().y;
short int px = player.getPosition().x;
short int pw = player.getGlobalBounds().width;
short int ph = player.getGlobalBounds().height;

for (int i = 0; i < block.size(); i++) {
short int by = block[i].getPosition().y;
short int bx = block[i].getPosition().x;
short int bw = block[i].getGlobalBounds().width;
short int bh = block[i].getGlobalBounds().height;

if (player.getGlobalBounds().intersects(block[i].getGlobalBounds())) {
// left/right
if (typeOfMovement == 0) {
if (py < by+bh && py > by) {
py = by + bh;
} else if (py+ph > by && py < by) {
py = by - ph;
}
}
// Up/Down
else if (typeOfMovement == 1) {
if (px < bx+bw && px+pw > bx+bh) {
px = bx + bw;
} else if (px+pw > bx && px < bx) {
px = bx - pw;
}
}

}

}
• Thank you for pointing out this out, but it didn't really changed the problem. Somehow, the first IF statement is run in both cases. Jun 21 '17 at 14:26