Need help with what pattern to use for collision detection

Started by
2 comments, last by povilaslt2 6 years, 9 months ago

Hello. I'm trying to make dynamic collision detection system. In example: automatically adjust collision detection when new vector of objects added and etc.

Now I have few vectors and I'm trying to do collision by just passing vector/object as parameter in "CheckCollision" function.


player->Update(application, dt);
			if (player->CheckCollision(&enemies))
			{
				InitScene();
				application->SetState(GameState::NOTSTARTEDYET);
				UI["Pause Menu"]->HideAllElements();
				UI["Options"]->HideAllElements();
				UI["Main Menu"]->ShowAllElements();
			}
			for (auto enemy : enemies)
			{
				enemy->Update(dt, t);
				if (enemy->CheckCollision(player))
				{
					InitScene();
					application->SetState(GameState::NOTSTARTEDYET);
					UI["Pause Menu"]->HideAllElements();
					UI["Options"]->HideAllElements();
					UI["Main Menu"]->ShowAllElements();
				}
			}

Can I somehow change this code to make code more dynamic when I add more vectors with enemies.

Advertisement

Well, obviously all the `InitScene(); ... etc` code can be factored out into a separate function and called from both places. There's no need for it to be inline there. But read on...

You also don't need to compare the player against each enemy and then each enemy against the player - you only have to do that once.

Probably better to update everything first, then just perform the single collision check, where you check each enemy in turn against the player.

If you anticipate having more vectors than just 'enemies' in future then you could make all these objects implement a 'Collidable' interface, so you can keep references to all of them in the same vector. You don't even need to treat the player and enemies as different types, in that case. Or, just check each vector in turn - it's unlikely to be a big problem just duplicating a one-liner like `if CheckCollision(etc).`

Ye but what if all enemies and player have use Base class which has bullets vector? Then I need to check player to enemies and enemies to player because of bullets?

This topic is closed to new replies.

Advertisement