- Home /
IsTouchingLayers() is not working
I have a 2D game with a handful kinematic objects.
I am checking in OnTriggerEnter2D for IsTouchingLayers but it is acting very odd
This is the Code
private void OnTriggerEnter2D(Collider2D collision)
{
int p=collision.gameObject.layer;
int r = LayerMask.NameToLayer("Ships");
if (collision.IsTouchingLayers(LayerMask.GetMask(new string[] { "Ships" })))
//if(p==r)
{
Destroy(this.gameObject);
}
}
So this code does not work as it is, the Orb (which this script is attached to) is on layer "Items" and the ship (which is what it has collided with is on layer "Ships".
However if I change the ship to layer "Items" (and obviously change the code to match) then IsTouchingLayers does indeed then work. But it does not work if the ship is on any other layer. So IsTouchingLayers only appears to be working for objects on the same layer...
If I comment out the IsTouchingLayers If statement and uncomment the p==r If statement then the code works fine.
The Collision Matrix has all boxes ticked.
I am using version 5.5
Answer by Commoble · Mar 04, 2017 at 11:58 PM
The collision/collider parameter in all collision/trigger events always refers to the other object involved in the collision/trigger. Since your script above is on the Orb, let's look at what your variables in the script are referencing when something collides with an Orb:
int p=collision.gameObject.layer;
This is the layer index of the other object, potentially a Ship.
int r = LayerMask.NameToLayer("Ships");
This is the layer index of the Ship layer.
if (collision.IsTouchingLayers(LayerMask.GetMask(new string[] { "Ships" })))
Now, in this one up there, you're checking if the other object (potentially a Ship) is touching an object whose layer is the Ship layer,
if(p==r)
whereas in that one, you're checking if the other object's layer is the Ship layer.
So you see why the one doesn't work and the other does?
Wow! How on earth did I not spot that obvious logic...
Thank you for spotting that glaring error for me.