void World::guideMissiles() { // Setup command that stores all enemies in mActiveEnemies Command enemyCollector; enemyCollector.category = Category::EnemyAircraft; enemyCollector.action = derivedAction<Aircraft>([this] (Aircraft& enemy, sf::Time) { if(!enemy.isDestroyed()) { mActiveEnemies.push_back(&enemy); } }); // Setup command that guides all missiles to the enemy which is currently closest to the player Command missileGuider; missileGuider.category = Category::AlliedProjectile; missileGuider.action = derivedAction<Projectile>([this] (Projectile& missile, sf::Time) { // Ignore unguided bullets if(!missile.isGuided()) { return; } float minDistance = std::numeric_limits<float>::max(); Aircraft* closestEnemy = nullptr; // Find closest enemy for(Aircraft* enemy : mActiveEnemies) { float enemyDistance = distance(missile, *enemy); if(enemyDistance < minDistance) { closestEnemy = enemy; minDistance = enemyDistance; } } if(closestEnemy) { missile.guideTowards(closestEnemy->getWorldPosition()); } }); // Push commands, reset active enemies mCommandQueue.push(enemyCollector); mCommandQueue.push(missileGuider); mActiveEnemies.clear(); }
void World::guideMissiles() { Command enemyCollector; enemyCollector.category = Category::EnemyAircraft; enemyCollector.action = derivedAction<Aircraft>( [this](Aircraft& enemy, sf::Time) { if(!enemy.isDestroyed()) mActiveEnemies.push_back(&enemy); }); Command missileGuider; missileGuider.category = Category::AlliedProjectile; missileGuider.action = derivedAction<Projectile>( [this](Projectile& missile, sf::Time) { if(!missile.isGuided()) return; float minDistance = std::numeric_limits<float>::max(); Aircraft* closestEnemy = nullptr; for(auto* enemy : mActiveEnemies) { float enemyDistance = distance(missile, *enemy); if(enemyDistance < minDistance) { closestEnemy = enemy; minDistance = enemyDistance; } } if (closestEnemy) { missile.guideTowards(closestEnemy->getWorldPosition()); } }); mCommandQueue.push(enemyCollector); mCommandQueue.push(missileGuider); mActiveEnemies.clear(); }