[quote name='wolfscaptain' timestamp='1326919051' post='4904069']
if (leftA > rightB || rightA < leftB || bottomA > topB || topA < bottomB) {
return false; // no collision
} else {
return true; // collision occured
}
Like I said in my first reply.
This way of doing collision is flawed and does not work.
Due to the fact that even if the rectangles are far from eachother it may return a True.
[/quote]
Those conditions mean the rectangles are not overlapping in any direction, I don't see how it is flawed (apart from the fact I use it since ever).
If you want correct response, using SAT (google separating axis theorm) is the easiest form of collision response, if not very good in the long term (it's not continouous, so if you have a large velocity compared to your objects, they might go through each other in one frame).
Here's a simple Rectangle-Rectangle SAT test (in JavaScript, but you get the point):
function SAT_solveCollision(a, b) {
var vector = [0, 0];
var left = (b.position[0]) - (a.position[0] + a.size[0]);
var right = (b.position[0] + b.size[0]) - (a.position[0]);
var top = (b.position[1]) - (a.position[1] + a.size[0]);
var bottom = (b.position[1] + b.size[1]) - (a.position[1]);
// this is basically the same conditions as my previous comment but it uses vector projection
if (left > 0 || right < 0 || top > 0 || bottom < 0) {
return vector;
}
if (Math.abs(left) < Math.abs(right)) {
vector[0] = left;
} else {
vector[0] = right;
}
if (Math.abs(top) < Math.abs(bottom)) {
vector[1] = top;
} else {
vector[1] = bottom;
}
if (Math.abs(vector[0]) === Math.abs(vector[1])) {
} else if (Math.abs(vector[0]) < Math.abs(vector[1])) {
vector[1] = 0;
} else {
vector[0] = 0;
}
return vector;
}
This code returns the smallest vector that might get object A out of object B.
Also note that my "origin" of each rectangle is the left-top corner, with the "up" axis pointing down (also known as screen space). If your setup is different, the calculation of left/right/top/bottom will be slightly different.