1
General / Re: Strange problem with sprite collision
« on: June 04, 2021, 08:56:04 pm »
Thanks you very much. Now I understand my mistakes.
I know also how to resolve the color's problem, I have to put a break instruction after changing the color.
So the correct code is:
After testing some code I've found another solution to solve my problem, it's an easier way to write the first solution:
I hope this will be useful for everyone else that encounter this kind of problem.
I know also how to resolve the color's problem, I have to put a break instruction after changing the color.
So the correct code is:
void checkCollision()
{
int i = 0;
while(i < vectorHeroes.size())
{
int j = 0;
while(j < vectorHeroes.size())
{
if(i != j) // makes sure the two tested sprites are different
{
if( isCollision( vectorHeroes[i]->s, vectorHeroes[j]->s ) ) // if there's a collision between one of the sprites with another
{
vectorHeroes[i]->s.setColor(sf::Color::Red); // set the sprite's color to red
break; // break because otherwise the sprite's color does not change correctly
}
else
{
vectorHeroes[i]->s.setColor(sf::Color(-1,-1,-1)); // set the sprite's color to the original one
}
}
++j;
}
++i;
}
}
{
int i = 0;
while(i < vectorHeroes.size())
{
int j = 0;
while(j < vectorHeroes.size())
{
if(i != j) // makes sure the two tested sprites are different
{
if( isCollision( vectorHeroes[i]->s, vectorHeroes[j]->s ) ) // if there's a collision between one of the sprites with another
{
vectorHeroes[i]->s.setColor(sf::Color::Red); // set the sprite's color to red
break; // break because otherwise the sprite's color does not change correctly
}
else
{
vectorHeroes[i]->s.setColor(sf::Color(-1,-1,-1)); // set the sprite's color to the original one
}
}
++j;
}
++i;
}
}
After testing some code I've found another solution to solve my problem, it's an easier way to write the first solution:
void checkCollision()
{
// Use a "for each" loop
for(auto &i : vectorHeroes)
{
for(auto &j : vectorHeroes)
{
if( isCollision(i->s, j->s) && i != j ) // i != j is important to make sure it's two different sprites
{
std::cout << "COLLISION!!\n==========" << std::endl;
i->s.setColor(sf::Color::Red);
break;
}
else
{
i->s.setColor(sf::Color(-1,-1,-1));
}
}
}
}
{
// Use a "for each" loop
for(auto &i : vectorHeroes)
{
for(auto &j : vectorHeroes)
{
if( isCollision(i->s, j->s) && i != j ) // i != j is important to make sure it's two different sprites
{
std::cout << "COLLISION!!\n==========" << std::endl;
i->s.setColor(sf::Color::Red);
break;
}
else
{
i->s.setColor(sf::Color(-1,-1,-1));
}
}
}
}
I hope this will be useful for everyone else that encounter this kind of problem.