Detecting collision is (genenrally) testing to see if two things are overlapping. However, the response to collision is what you do what that occurs.
One thing to do is, as you've done, stop the thing from moving anymore if they collide. However, this means that they stop where they are overlapping. Generally, and especially for things like walls, you want to move the thing to where it should be - outside of the wall. There are different approaches to this and I don't profess to know lots about this.
One approach is to move is back to where it was before it collided. This is the easiest step and could be the best solution depending on how accurate you want it to look and how fast the thing is moving.
The next approach would be to take the previous position and the colliding position and use geometry to project the first position towards the second to work out where it would have collided between the two.
A more advanced approach could be to take the previous approach and the work how much further it would've travelled to the colliding position and 'bounce' the thing from the wall by that much. You should probably take into account the direction of travel and angle of the wall for this. However, this is less useful for things that should stop when hitting a wall.
Thank you very much for your reply
I think I will go with the first option because its the best for my case: the player is moving in a constent velocity, and I don't need to calculate anything about the direction because there are only 4 of them (up, down, left and right).
unluckily, it does not work.
this is my code:
for (int i = 0; i < lvl.getSizeInTiles().x; i++) {
for (int j = 0; j < lvl.getSizeInTiles().y; j++) {
if (lvl.getTileFromBuffer(i, j).getType() == "wall") {
if (intersects(lvl.getTileFromBuffer(i, j).getPosition().x, lvl.getTileFromBuffer(i, j).getPosition().y, lvl.getTileFromBuffer(i, j).getSize().x, lvl.getTileFromBuffer(i, j).getSize().y)) {
if (faceDirection == "UP" && vel.y < 0) {
collidesUp = true;
pos.y += walkSpeed;
vel.y = 0;
}
else {
collidesUp = false;
}
if (faceDirection == "DOWN" && vel.y > 0) {
collidesDown = true;
pos.y -= walkSpeed;
vel.y = 0;
}
else {
collidesDown = false;
}
if (faceDirection == "LEFT" && vel.x < 0) {
collidesLeft = true;
pos.x += walkSpeed;
vel.x = 0;
}
else {
collidesLeft = false;
}
if (faceDirection == "RIGHT" && vel.x > 0) {
collidesRight = true;
pos.x -= walkSpeed;
vel.x = 0;
}
else {
collidesRight = false;
}
}
}
}
}
}
I hope it will help you, but if you have questions about the code; just ask me.
Thank you very much again,
Arad.