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. Dismiss Notice

Tile Collider 2D and Physics2D Raycast

Discussion in '2D' started by boiseunity, Mar 17, 2022.

  1. boiseunity

    boiseunity

    Joined:
    Dec 19, 2020
    Posts:
    14
    I have a 2D rectangular tilemap that is partially filled. It has a Tilemap Collider 2D component.

    Meanwhile, in my script...

    Code (CSharp):
    1. void Update()
    2.     {
    3.         if (Input.GetMouseButtonDown(0))
    4.         {
    5.             RaycastHit2D raycastHit2D = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.down);
    6.             Debug.Log(raycastHit2D.collider);
    7.         }
    8.     }
    And yet, nothing. There is no collision recorded, only null in the debugger.
     
  2. boiseunity

    boiseunity

    Joined:
    Dec 19, 2020
    Posts:
    14
    An answer for someone in the future:

    I had to edit the tile in the Inspector and change its collision type to "Grid," rather than "None."
     
  3. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,529
    Yes, you're not going to detect collision shapes on a Tilemap without adding any!

    More important is that you don't use a raycast to detect an intersection with the mouse in 2D physics like you would in 3D physics. You use the much faster/efficient Physics2D.OverlapPoint simply because this is 2D!
     
    bowserscastle likes this.
  4. DrVanillaCookie

    DrVanillaCookie

    Joined:
    Aug 23, 2021
    Posts:
    39
    What if colliders are 2D but the camera is 3D (perspective)? In that case you have to use ScreenPointToRay and GetRaytIntersection. Do I understand this correctly?
     
  5. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,529
    Yes. As long as you remember that it's 2D physics and it exists on the XY plane only. That query will sort by the Transform Z for you but the physics knows nothing about it. If all the colliders are on the same Z (which doesn't affect physics) then the order is "undefined".

    I only mention this because I've encountered many devs who just grab 3D physics code and straight-up use it with 2D and don't think about the fact that it's not 3D. :)
     
    DrVanillaCookie likes this.