Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Physics2D ignore itself?

Discussion in 'Scripting' started by tomang5, Jul 16, 2020.

  1. tomang5

    tomang5

    Joined:
    Feb 18, 2020
    Posts:
    63
    Hi all,

    Is there a way to ignore a collider/colliders of an object that I fire raycast from? The raycast always hits the object itself. I tried turning off the "Queries Start In Colliders" option but that breaks from-screen-to-world raycasts (raycasts from mouse position to the world).
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    Best way is to use Layers and explicitly say what you want to ignore, even to the point of ignoring anything and only picking up a single specific layer. There are other overloads of the Raycast function family that accept a layer mask, which is a 32-bit number of 1 and 0 bits indicating what to mask (1-ignore/mask, 0 - accept) layer-wise.
     
  3. FeVergara

    FeVergara

    Joined:
    Jul 14, 2020
    Posts:
    8
    I don't understand verry well.
    But active "Is Trigger" in collider, the object ignore physics but the Unity register
    when passing through the object (sorry my English, google tradutor :p)


    void OnCollisionEnter2D(Collision2D collision2D) -> private void OnTriggerEnter2D(Collider2D collision2D)

    void OnCollisionExit2D(Collision2D collision2D) -> private void OnTriggerExit2D(Collider2D collision2D)



    Ex:
    private void OnTriggerEnter2D(Collider2D collision2D)
    {
    if (collision2D.gameObject.CompareTag("Checkpoint"))
    {
    lastCheckpoint = collision2D.gameObject;
    }
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    You don't use this for Raycast but similar layer rules apply: you can control what connects with what:

    Edit -> ProjectSettings -> Physics2D -> LayerCollisionMatrix (near bottom)
     
  5. tomang5

    tomang5

    Joined:
    Feb 18, 2020
    Posts:
    63
    In my case, I need to use raycasts for car sensors for AI. Traffic cars should detect each other as well. By using layer masks, I cannot achieve this.

    I don't wan to use the RaycastAll function because those raycasts are fired every frame.