Let's say we have 2 rectangle shapes: shape1 and shape2, i want to test the collision between them and do different things when each side of shape1 touch the other side of shape2.
i was thinking in an easy way of doing it, and ended with something like this:
sf::RectangleShape shape;
sf::RectangleShape shape2;
shape1.setSize(Vector2f(50,100));
shape2.setSize(Vector2f(500,50));
(. . .)
in the game loop:
//shapes bottom
s1b = shape1.getPosition().y + 100;
s2b = shape2.getPosition().y + 50;
//shapes top
s1t = shape1.getPosition().y;
s2t = shape2.getPosition().y;
//shapes right
s1r = shape1.getPosition().x + 50;
s2r = shape2.getPosition().x + 500;
//shapes left
s1l = shape1.getPosition().x;
s2l = shape2.getPosition().x;
//shapes are coliding?
if(s1l <= s2r && s1r >= s2l && s1t <= s2b && s1b >= s2t){isColiding = true;}else{isColiding = false;}
if(isColiding)
{
if(s1b <= s2t + 10)//is shape1 on top of shape2?
{
spd.y = 0;
shape1.setPosition(shape1.getPosition().x, shape2.getPosition().y - 100);
std::cout<<"is on top" << std::endl;
}
else if(s1t >= s2b - 10)//is shape1 top hitting shape2 bot?
{
spd.y = speed;
shape1.setPosition(shape1.getPosition().x, shape2.getPosition().y + 50);
std::cout<<"is touching bottom" << std::endl;
}
else if(s1l >= s2r - 10)//does shape1 left collide with shape2 right?
{
spd.x = 0;
shape1.setPosition(shape2.getPosition().x + shape2.getSize().x, shape.getPosition().y);
std::cout<<"is touching right" << std::endl;
}
else if(s1r <= s2l + 10)//does shape1 right collide with shape2 left?
{
spd.x = 0;
shape1.setPosition(shape2.getPosition().x - shape1.getSize().x, shape1.getPosition().y);
std::cout<<"is touching left" << std::endl;
}
}
It works, but i think that maybe this is really inefficient, because if shape1 move in a really fast speed for some reason (fps drops,etc), it will most probably miss the collisions. since it depends in a tiny 10 pixels collision check system, won't it?