Hello,
I am having issues with collision detection of player bullets against enemies.
I have three "types" of enemies and plan on having many more with distinct characteristics.
enemyOne(sf::Color::Yellow, 20.f, 20.f)
enemyTwo(sf::Color::Red, 40.f, 40.f)
enemyThree(sf::Color::Cyan, 80.f, 80.f)
that feed into
std::vector<Enemy> enemiesOne;
std::vector<Enemy> enemiesTwo;
std::vector<Enemy> enemiesThree;
I currently have a not so elegant function that won't scale very well with my goal...however it does work.
void Bullet::BulletEnemyCollision(sf::RectangleShape playerBulletShape, std::vector<Enemy>& enemyVectorsOne, std::vector<Enemy>& enemyVectorsTwo, std::vector<Enemy>& enemyVectorsThree)
{
for (unsigned int i = 0; i < enemyVectorsOne.size(); i++)
{
if (playerBulletShape.getGlobalBounds().intersects(enemyVectorsOne[i].enemyShape.getGlobalBounds()))
{
enemyVectorsOne.erase(enemyVectorsOne.begin() + i);
}
}
for (unsigned int i = 0; i < enemyVectorsTwo.size(); i++)
{
if (playerBulletShape.getGlobalBounds().intersects(enemyVectorsTwo[i].enemyShape.getGlobalBounds()))
{
enemyVectorsTwo.erase(enemyVectorsTwo.begin() + i);
}
}
for (unsigned int i = 0; i < enemyVectorsThree.size(); i++)
{
if (playerBulletShape.getGlobalBounds().intersects(enemyVectorsThree[i].enemyShape.getGlobalBounds()))
{
enemyVectorsThree.erase(enemyVectorsThree.begin() + i);
}
}
}
An idea I have is to feed each enemy vector into a vector and simply have the function iterate through that vector of vectors. This currently does not work.
std::vector<std::vector<Enemy> >& enemyVectors
void Bullet::BulletEnemyCollision(sf::RectangleShape playerBulletShape, std::vector<std::vector<Enemy> >& enemyVectors)
{
for (unsigned int i = 0; i < enemyVectors.size(); i++)
{
for (unsigned int j = 0; j < enemyVectors[i].size(); j++)
{
if (playerBulletShape.getGlobalBounds().intersects(enemyVectors[i][j].enemyShape.getGlobalBounds()))
{
enemyVectors[i].erase(enemyVectors[i].begin() + j);
}
}
}
}
Below is a brief recording of the game with the not so elegant code in place.
https://gfycat.com/gifs/detail/LivelySpottedChevrotainYou may notice the lack of pointers and keywords like auto...etc. This game for me is an exercise in learning classes & functions at a basic level. The next game I plan on taking a stab at utilizing pointers and super useful keywords. The last game I made I was using header files for implementation...baby steps.
Thanks for reading and I appreciate the help.