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

Question get world position of tilemap

Discussion in '2D' started by BulbasaurLvl5, Mar 27, 2021.

  1. BulbasaurLvl5

    BulbasaurLvl5

    Joined:
    May 10, 2020
    Posts:
    42
    Hi,

    what i want to do: I want to make my enemies know the tilemap parts near them (i want to do a spring system to make them keep a distance)

    i would prefer to do this by using a collider attached to them (representing perception), which works totally fine for other gameobjects. But tilemaps only store the position of the tilemap gameobject (which then holds the array i used to create the tilemap). Maps might become big and may hold multiple enemies, thus i wanted the enemies only to check for elements close to them, instead of calculating springs for the whole map

    solutions i can imagine:
    • create gameobjects on the tilemap to register to the enemy perception -- this would somewhat make the usage of the tilemap redundant, because, as far as i understand, their purpose is to save gameobjects
    • make the enemies access the tilemap array, transform it to world coordinates and manually check for close tiles -- this seems hacky
    • make the enemies raycast in some angles around them and store the collision coordinate -- this might inaccurate, depending on the number of raycasts
    • somehow get used to A* and hope that it can handle this
    As you can see, the solutions i can come up with, do not seem that good to me and i would like to hear if anybody knows how to do this properly. thanks
     
  2. BulbasaurLvl5

    BulbasaurLvl5

    Joined:
    May 10, 2020
    Posts:
    42
    sight, the method was looking for was WorldToCell(), thanks for reading anyway
     
  3. invasionofsmallcubes

    invasionofsmallcubes

    Joined:
    Mar 7, 2021
    Posts:
    5
    I didn't know it, so good to know :)
     
  4. BulbasaurLvl5

    BulbasaurLvl5

    Joined:
    May 10, 2020
    Posts:
    42
    glad i could help :)

    full "solution" is

    Code (CSharp):
    1.  
    2. public void OnCollisionEnter2D(Collision2D other)
    3.  {
    4.    Tilemap tilemap = other.gameObject.GetComponentInParent<Tilemap>();
    5.  
    6.    Vector3Int cellPosition = tilemap.WorldToCell(transform.position);
    7.    Vector3 tilepos = tilemap.GetCellCenterWorld(cellPosition);
    8. }
    cellpos is the array element and tilepos the position of the tile in the world