Search Unity

2D Isometric Tilemap Player movement by clicking mouse

Discussion in '2D' started by DGaliyev1, Aug 5, 2019.

  1. DGaliyev1

    DGaliyev1

    Joined:
    Jul 5, 2019
    Posts:
    1
    Hello,
    I just recently started to learn unity and C# (so i am very nooby at this subject xP ). I am making 2D isometric tilebased dungeon game and what my players to move by selecting the Player with a mouse and clicking on the tile and player has to change his position to position of that tile. I got to the point where I click on the tile and get the grid coordinates of that tile (e.g., Tile #20 (5,6,0)) and of a Player in grid coordinates. But then if I use transform.Translate() to my coordinate of a tile, player simply wonders off hell knows where =).

    I know there are scripts on how to make player to move by grid using keyboard. And do I have to attach Rigidbody2D, Script to a sprite or a parent Player object?))
    So guys can you help me with at least basic movement from current position to tile coordinate?
    Thank you in advance.
    Update: I use Vector3.MoveTowards() and its better but still player goes in wrong directions.

    void Update()
    {
    Vector2 currentPos = theRB.position;
    Vector3Int playerPos = tilemap.WorldToCell(currentPos);

    if (Input.GetMouseButtonDown(0))
    {
    Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Vector3Int coordinate = tilemap.WorldToCell(mousePos);

    var tilePos = tilemap.GetTile(coordinate);

    Debug.Log(tilePos);
    Debug.Log(coordinate);
    Debug.Log(playerPos);

    theRB.position = Vector3.MoveTowards(currentPos, coordinate, moveSpeed * Time.deltaTime);
    }


    Btw, for some reason I cannot add my code in here, it says that my content seems like spam.
     
    Last edited: Aug 5, 2019