How to avoid Unity physical collision two object (C# example code)

2017. 4. 3. 15:08Korean/개발백과사전

How to avoid physical collision between two object?


Here is an example.


Th first object is the tank and the second object is a bullet. Think about a tank shot cannon. but this tank and bullet have a collision object.

As soon as your tank fire the cannon, two objects are a collision and explode. This is not what you wanted to.


To Solve this problem, You have two options.


First code is like this. check object tag, and if cannon detects collision with the Tank, let's ignore it.


public class Cannon: MonoBehaviour {

    private void OnCollisionEnter2D(Collision2D collision)   {

        if(collision.gameObject.tag == "Tank")

return;

    }

}


The second way is to use physical ignore function.


Just one line of code to avoid collision between the tank and the cannon

public class Cannon: MonoBehaviour {

    private void FixedUpdate()    {

        Physics2D.IgnoreLayerCollision(9, 10);

    }

}


What is the number 9 and 10?

This is a layer number where you defined in the object.

For me, number 9 is tank named "Player", number 10 is cannon named "Weapon"



As everybody knew, There is no standard way to coding.
Find the best way in your situation and adopt it as you thinking.
CHEERS.