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

How to transform something in grid instead of world

Discussion in '2D' started by aybarsmete1, Nov 20, 2019.

  1. aybarsmete1

    aybarsmete1

    Joined:
    Oct 26, 2019
    Posts:
    43
    Code (CSharp):
    1. player.transform.position = new Vector3Int (spawnPoint, 0, 0);
    I kinda struggled in here, anyway I could make these integers into grid?(Or tilemap, if it works.)
     
  2. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    @aybarsmete1

    You mean you want to get some arbitrary position as tile position? Easiest way is to round the coordinates. You actually want to "floor" the values, that way, when you move your cursor (not that you need the cursor, it can be anything), you tile is the one defined by tile size, and current arbitrary position gets rounded so that it only changes when you go to values less than tile left border, or higher than its right edge... i.e. you cross the current tile boundary:

    Code (CSharp):
    1. void Update()
    2. {
    3.     // Note: this camera to world only works with ortho camera.
    4.     wPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    5.  
    6.     var tx = Mathf.FloorToInt(wPos.x / tileSize) * tileSize;
    7.     var ty = Mathf.FloorToInt(wPos.y / tileSize) * tileSize;
    8.  
    9.     // Maybe do some custom debug drawing to show current tile
    10.     DrawRect(new Vector3(tx, ty, 0));
    11. }
    This should work with tile sizes like 1.5 and 3 too.
     
    DarthIF and MisterSkitz like this.
  3. aybarsmete1

    aybarsmete1

    Joined:
    Oct 26, 2019
    Posts:
    43
    I didn't understand whats with the mousePos. I think it's my mistake to not tell you I am not doing anything about placing/destroying tiles. I am trying to make a respawn system and I need the player to respawn on grid with grid positions.
     
  4. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    @aybarsmete1

    And that is what I tried to explain pretty much... I think?

    Consider mouse position as any arbitrary position, like (4.7, 3.3) and then you can round that to your tile coordinate system positions. So if your tile is size 3x3, then this coordinate would be in tile (1,1).

    So the exact spawn position in world space is now in "tile" positions, that don't necessarily match 3d space coordinates.
     
    MisterSkitz likes this.