Search Unity

Unity Tile Position between Tiles ?

Discussion in '2D' started by Slastraf, Aug 19, 2019.

  1. Slastraf

    Slastraf

    Joined:
    Aug 30, 2015
    Posts:
    6
    Code (CSharp):
    1.                    
    2. Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    3.                     Vector3 worldPoint = ray.GetPoint(-ray.origin.z / ray.direction.z);
    4.                     Vector3Int position = m_level.WorldToCell(worldPoint);
    5.  
    6.                     TileBase tile = m_level.GetTile(position);
    7.                     Debug.Log(tile);
    8.                     selectIconBuildMode.gameObject.transform.position = m_level.CellToWorld(position);
    When I place an entity on the cellToWorld position it can also be halfway inbetween the cells. How to get the exact cell ?
     
  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    This line isn't making sense to me:
    Vector3 worldPoint = ray.GetPoint(-ray.origin.z / ray.direction.z);


    The parameter is supposed to be a distance along the ray. The ray origin is a world space position, and the ray direction is a normalized unit vector, so I'm not sure what kind of value you're getting there (especially since it will be negative). The reason it works at all is because the ray points directly forward along the Z axis so any distance along the ray is the same point in 2D.

    Since you're not really using the ray here, you could you change your code to:
    Vector3 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);


    Anyway, for your question:

    You can offset the CellToWorld result by adding/subtracting half the cell size in X and/or Y depending on the results you're looking for.

    m_level.cellSize * 0.5f