开发者

Unity3D Which way of doing 2D collision is faster?

开发者 https://www.devze.com 2023-04-01 02:42 出处:网络
I am doing a 2D game where enemies will shoot at my player. There are two ways to do collision of bullets:

I am doing a 2D game where enemies will shoot at my player. There are two ways to do collision of bullets:

  1. Add colliders to bullets. Add rigidbody to player. Use OnCollision() way to do collision detection.
  2. Use Vector3.Distance() to check every bullet's distance between player and bullets, if it is smaller than the preset value开发者_StackOverflow社区, 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.


To answer your question, the colliders I would say are the better way to go, physics detection are a little more optimized than checking EVERY frame for a distance collision.

But this also depends on the number of objects that are gonna be handled, you can use the profiler to see where it's slowing down and switch your code if necessary.

Also this article might help: http://technology.blurst.com/unity-physics-trigger-collider-examples/


In my experience I would say detect collider is faster and better, in any case you are using unity physics and add on collider method to your scrip doesn't decrease performance

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号