• Advertisement
Sign in to follow this  

Need help with what pattern to use for collision detection

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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).`

Share this post


Link to post
Share on other sites

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?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Advertisement