Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bullets instantiate inside wall, doesn't trigger OnCollisionEnter2D

void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "Wall")
        {
            Destroy(gameObject);
        }
    }

I use this script. All is ok, but if my bullet spawns in Wall, it doesn't react with wall. It flies inside the wall. So, what should I use for instan destroy bullet if it spawns inside wall?

Bullet spawn method:

Instantiate(bullet1, firepoint1.position, firepoint1.rotation);

enter image description here

like image 455
Eloren Avatar asked Dec 07 '25 10:12

Eloren


1 Answers

Since colliders are giving troubles when the GameObject is instantiated inside the other collider. I recommed you to first check if the bullet would be instantiated inside the Wall, and in that case, directly don´t instantiate it. I believe this will make the code more efficient.

So first you need to add the Wall in a Layer (Here you can see how to create a new layer and assign the wall to that layer). An pass it as parameter to the script you use to instantiate the bullets (the script of the tank for example).

public LayerMask wallLayer;

You save the transform of the tank in a variable

// Variable with position of the Tank
Transform _transform;

void Awake () {

    _transform = GetComponent<Transform> ();

}

Next thing you generate Physics2D.Linecast. Source. Assuming you use a script attached to the tank GameObject to fire the bullets:

// Linecase goes from the tank position to the place where you would be instantiating the bullet
boolean insideWall = Physics2D.Linecast(_transform.position, firepoint1.position, wallLayer);

Then you instantiate the bullet only in case you would not instantiate it inside the wall.

if(!insideWall)
    Instantiate(bullet1, firepoint1.position, firepoint1.rotation);
like image 136
Ignacio Alorre Avatar answered Dec 09 '25 23:12

Ignacio Alorre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!