Search code examples
c#unity-game-enginecollision-detectioncollision

Ignore collision between parent objects in order to detect collision between its child game objects


Player is my game object which moves around 2d map and tries to hit goblin with his weapon, but if weapons of goblin and player collide i dont want damage to be delt

  • If weapon collided with the body deal damage, if weapon collided with other weapon do not deal damage.

  • Problem is that when two weapons collide it detects it as if Player object and Goblin object collide and not that actual weapons collide.

  • I have tried:

    • to add and remove rigid bodies.
    • to extract children from Player game object because somehow weapon collision box becomes part of a player and i cannot get weapon to weapon collision.

visualization of collisions2D

 public class ObjectDamage : MonoBehaviour
{
    public int damage;
    public int team;
    public float bounceForce = 5f;

    void Start()
    {
        
    }

    void Update()
    {
        
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {   
        Debug.Log($"Collided with object with tag: {collision.gameObject.tag}"); 
        if (collision.gameObject.layer == 3)
        {
            ClashWithOtherWeapon();
            Debug.Log("Reached!");
            return;
        }

        ObjectHealth objectHealth = collision.gameObject.GetComponent<ObjectHealth>();
        if (objectHealth != null && objectHealth.team != team)
        {
            objectHealth.TakeDamage(damage);
            BounceEnemyBack(collision);
        }
    }

    private void ClashWithOtherWeapon()
    {
        return;
    }

    private void BounceEnemyBack(Collision2D collision)
    {
        Rigidbody2D rb = collision.gameObject.GetComponent<Rigidbody2D>();
        if (rb != null)
        {
            Vector2 bounceDirection = collision.transform.position - transform.position;
            bounceDirection.Normalize();
            rb.AddForce(bounceDirection * bounceForce, ForceMode2D.Impulse);
        }
    }
}

Solution

  • You should check collision.collider, which represents the Collider2D component that collides with the current object. And collision.gameObject refers to the game object where the Rigidbody2D associated with the collider is attached.