From a49753e39af117b7c21d17088e89f8a9936fb36f Mon Sep 17 00:00:00 2001 From: ineslelin Date: Tue, 3 Dec 2024 12:06:09 +0100 Subject: [PATCH] rework calculateSpawnPosition() --- include/AssetManager.h | 2 +- src/AssetManager.cpp | 48 +++++++++++++++++++++++------------------- 2 files changed, 27 insertions(+), 23 deletions(-) diff --git a/include/AssetManager.h b/include/AssetManager.h index 1a92c76..0d7a699 100644 --- a/include/AssetManager.h +++ b/include/AssetManager.h @@ -27,7 +27,7 @@ public: void createProjectile(Vector2D pos, Vector2D velocity, int scale, int range, int speed, const char* texturePath, Entity* owner); void createPowerup(Vector2D pos, std::function pickupFunc, std::string texturePath); - Vector2D calculateSpawnPosition(); + Vector2D calculateSpawnPosition(int width, int height); template T calculateType(int amount); //texture management diff --git a/src/AssetManager.cpp b/src/AssetManager.cpp index 809ccd7..4bf00be 100644 --- a/src/AssetManager.cpp +++ b/src/AssetManager.cpp @@ -14,6 +14,7 @@ #include "Vector2D.h" #include "PowerupComponent.h" #include +#include AssetManager::AssetManager(Manager* manager) : man(manager) {} @@ -73,29 +74,32 @@ void AssetManager::createPowerup(Vector2D pos, std::function pic powerups.addGroup((size_t)Entity::GroupLabel::POWERUPS); } -Vector2D AssetManager::calculateSpawnPosition() +Vector2D AssetManager::calculateSpawnPosition(int width, int height) { - Vector2D spawnPos = Vector2D(-1, -1); - bool conflict = false; - for (int i = 0; i <= SPAWN_ATTEMPTS; i++) - { - SDL_Rect spawnRect; - spawnRect.h = spawnRect.w = 32; - spawnRect.x = rand() % (SCREEN_SIZE_WIDTH - spawnRect.w); - spawnRect.y = rand() % (SCREEN_SIZE_HEIGHT - spawnRect.h); - conflict = false; - for (auto cc : this->man->getGame()->collisionHandler->getColliders({ Entity::GroupLabel::MAPTILES })) - { - if (SDL_HasIntersection(&spawnRect, &cc->collider) && strcmp(cc->tag, "projectile")) - { - conflict = true; - break; - } - } - if (conflict) continue; - spawnPos = Vector2D(spawnRect.x, spawnRect.y); - } - return spawnPos; + Vector2D spawnPos = Vector2D(-1, -1); + + for(int i = 0; i <= SPAWN_ATTEMPTS; i++) + { + SDL_Rect spawnRect = { + rand() % (SCREEN_SIZE_WIDTH - width), + rand() % (SCREEN_SIZE_HEIGHT - height), + width, + height + }; + + std::vector colliders = this->man->getGame()->collisionHandler->getColliders({Entity::GroupLabel::MAPTILES}); + bool conflict = std::any_of(colliders.begin(), colliders.end(), + [&](const auto& cc) { + return SDL_HasIntersection(&spawnRect, &cc->collider);} ); + + if(!conflict) + { + spawnPos = Vector2D(spawnRect.x, spawnRect.y); + break; + } + } + + return spawnPos; } template