Hello Guest

Author Topic: having problem in finding tile coordinates through mouse cursor  (Read 4146 times)

richardo

  • Newbie
  • *
  • Posts: 2
    • View Profile
having problem in finding tile coordinates through mouse cursor
« on: January 02, 2014, 05:50:51 am »
I want to make my mouse cursor shows the current tile's coordinates (the tile x and y) and display it on debug log, here is my current code

getCursorCoordinate.cs
Code: [Select]
using UnityEngine;
using System.Collections;

public class getCursorCoordinate : MonoBehaviour {

int xx = 0; int yy = 0;
public tk2dTileMap tilemap;
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

}

void OnGUI(){
Event e = Event.current;
       
        if (e.type == EventType.MouseDrag && e.button == 0 && e.isMouse)
        {     
                tilemap.GetTileAtPosition(tk2dCamera.Instance.camera.ScreenToWorldPoint(e.mousePosition), out xx, out yy);
Debug.Log("x:" + xx + "|y:" + yy);
        }
}
}


I tried to check the most bottom left tile (where it should be 0, 0) but it shows the wrong tile coordinate (0, 28). Can anyone help me, thanks!

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: having problem in finding tile coordinates through mouse cursor
« Reply #1 on: January 02, 2014, 05:45:43 pm »
Are you using a perspective / ortho camera? Do you have more than one camera in the scene?

richardo

  • Newbie
  • *
  • Posts: 2
    • View Profile
Re: having problem in finding tile coordinates through mouse cursor
« Reply #2 on: January 03, 2014, 05:42:17 am »
it's ortho and 1 cam
Are you using a perspective / ortho camera? Do you have more than one camera in the scene?

Thank you I finally got it working but I'm completely didnt know what I did, and for some reason this line :
   tilemap.GetTileAtPosition(tk2dCamera.Instance.camera.ScreenToWorldPoint(e.mousePosition), out xx, out yy);

The yy var gives the inverted position of Y axis, so I have to add * -1 on that part and it's works good now. So im sure it has to do with the camera?

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: having problem in finding tile coordinates through mouse cursor
« Reply #3 on: January 03, 2014, 12:37:13 pm »
That is really bizarre. ScreenToWorld point should give you a world point, and GetTileAtPosition uses worldToLocalPosition so it should work when flipped, rotated, etc.

Only just occurred to me you're using e.mousePosition. Unity GUI event?
Unity screen space y=0 is bottom of screen.
Unity GUI space y=0 is top of screen.

Use GUIUtility.GUIToScreenPoint to convert from guy -> screen space point, and feed that in to screenToWorldPoint.