I am doing a 2D game where enemies will shoot at my player. There are two ways to do collision of bullets:
- Add colliders to bullets. Add rigidbody to player. Use OnCollision() way to do collision detection.
- Use Vector3.Distance() to check every bullet’s distance between player and bullets, if it is smaller than the preset value, then my player is hit.
The question is, which method will have better performance(less calculation)?
Shortly, method 1, no dobut about that.
I’ll assume that you want to have many players (let’s say N), and many bullets (let’s say M). Method 2 needs to test all the bullets vs all the players, that’s executing your distance test N*M times. On the other hand, you can relay that the physics engine will optimize the testing by using spatial subdivision techniques (Testing only against ‘near’ objects).
But have in mind that the correct method to use also depends on the velocity of your bullet, while using a collider or checking the distance is ok with fairly slow bullet (ie. Metal Slug bullets), you’ll have problems with a fast bullet (ie. fast like a real bullet), two psossible solutions are to play a bit with Project Settings->Physics or, just do a Physcis.Raycast() to get the object with which te bullet impacts instantly.