Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question How to detect Tilemap Collider on mouse click

Discussion in '2D' started by Matteo0o, Apr 22, 2023.

  1. Matteo0o

    Matteo0o

    Joined:
    Sep 14, 2022
    Posts:
    2
    I'm working on a top-down 2d game, I want the player to move only when I click over a certain tilemap, the ground that is. This tilemap has a tilemap collider 2d attached.
    I've used Input.GetMouseButtonDown with Raycast2d to do this. It works, but the player also moves in some areas where the ground tiles are not present and where there is no collider and I dont understand why. I've attached the script, I know the code is ugly but I focused on this problem in particular.

    Still quite new to Unity, so help would be appreciated, thanks!
     

    Attached Files:

  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,519
    Raycast in 2D is unlikely to be the correct solution here.

    Instead use the Overlap family of methods, either those in the Physics2D class or those in the Collider2D class if you know the collider(s) and want to iterate them yourself.

    Other than that, if you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/
     
  3. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,321
  4. BoredVoid

    BoredVoid

    Joined:
    Feb 29, 2020
    Posts:
    12
    You could use GridLayout.WorldToCell to get a VectorInt3 of the cell positions and then test if it exists in the ground tilemap.
    And for the Worldcoordinates you can use Camera.ScreenToWorldPoint.
     
  5. Matteo0o

    Matteo0o

    Joined:
    Sep 14, 2022
    Posts:
    2
    The overlap function worked perfectly, thanks all for the help and the heads up about code tags!
     
    MelvMay likes this.