- Home /
Best way to manage a collision between a few different objects?
Let's take the example of the classic asteroids game: Asteroids kill player. Player shoots. Shots divide and destroy asteroids.
Now, I can get all of this working somehow, but I've always wondered how to properly sort the collision events in order to get the best logic or the easiest to read code.
For instance, I could implement the asteroids-kill-player logic both in player and asteroid script. Same with the shots destroying asteroids.
Where do you think implementing each behaviour is best? What would you use to determine this for other problems?
Answer by sacredgeometry · Jan 17, 2020 at 07:47 AM
C# has a bunch of different ways to deal with event driven development. One of the more fundamental is literally events/ delegates.
So the basic premise is something like this: For every situation i.e. OnPlayerCollided or OnShotCollided you have a variable.
This variable stores a reference to all the methods you want to call in the event that those things happen.
Then from anywhere in your code you can write code to invoke those variables on behalf of the methods stored (instead of trying to call them all directly).
Have a read about events and delegates and that should give you a good understanding about how to write code like this more cleanly
https://jonskeet.uk/csharp/events.html https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/events/ https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/events/
Alternatively there are different patterns that you could use and frameworks that support those patterns like observers and reactive programming but those may be a little more heavy weight (especially the latter)