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

[Solved]Trying to snap a "target" to a tilemap tile

Discussion in '2D Experimental Preview' started by Divinitize1, Mar 17, 2020.

  1. Divinitize1


    May 27, 2019
    As the title says, I'm trying to snap a target to the closest center of a tile of where my mouse position is.

    The code below is close to working, but I think something is wrong because the target sprite this script is attached to only shows up when I've hovered over other game objects in my scene that are not tilemaps...
    And disappears again when moving over the tilemap.
    Any help to my problem is greatly appreciated.

    Code (CSharp):
    1. public Tilemap topTile;
    3.     void Update()
    4.     {
    5.         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    6.         RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity);
    8.         Vector3Int cellPosition = topTile.LocalToCell(hit.point);
    9.         transform.localPosition = topTile.GetCellCenterLocal(cellPosition);
    10.     }

    (It works below the log because the logs trigger box goes below slightly)
    I also do have a tilemap collider on the tilemap
    Last edited: Mar 17, 2020
  2. Divinitize1


    May 27, 2019
    Appears to be being caused by the composite collider, changing from Outline to Polygon on Geometry Type solved the issue.

    I do however still need help.
    Using my new target to remove a tile no longer allows me to hover over that tile because theres no longer collision there.
    How can i still raycast the Tilemap even without collision?

    ^^Solved! (Added a large box collider2d over the entire tilemap and changed the collision matrix to ignore everything.)
    Last edited: Mar 17, 2020