Hello Guest

Author Topic: Can't get world ray to identify tile  (Read 4510 times)

limegreen

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 6
    • View Profile
Can't get world ray to identify tile
« on: September 16, 2017, 10:28:36 pm »
I am using a Tilemap and right now I have no real use for colliders so I want to avoid them.  However, I do need to respond to mouse clicks on the map.  I came across this post: http://2dtoolkit.com/forum/index.php/topic,2304.msg11501.html

In there is this advice:

Quote
Don't use colliders. Get the intersection of the cursor / touch ray and tilemap plane
      Plane p = new Plane(tileMap.transform.forward, tileMap.transform.position);
      Ray r = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
float hitD = 0;
if (p.Raycast(r, out hidD)) {
  Vector3 hitPoint = r.GetPoint(hitD);
}

When I try to do this, I get this error:

Unable to convert GUI point to world ray if a camera has not been set up!

I have tried this with a tk2dCamera in the scene, a regular Unity Camera in the scene, and with both, and I always get this error.  Any suggestions?

Thanks,
Wayne

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: Can't get world ray to identify tile
« Reply #1 on: September 17, 2017, 09:29:36 am »
Hi,

The GUI functions require a GUI Layer component I think.
You don't need GUIPointToWorldRay.

Assuming the tilemap is perpendicular to the camera (i.e. no rotation on camera or tilemap) you don't need the plane intersection either. If your camera is perspective you'll need the line that does mousePos.z, otherwise you can remove that too. This gives you the X, Y tilemap coordinate where the mouse is on.

Code: [Select]
Vector3 mousePos = Input.mousePosition;
mousePos.z = tileMap.transform.position.z - cam.transform.position.z;

Vector3 worldPos = cam.ScreenToWorldPoint(mousePos);

int tileX = 0, tileY = 0;
tileMap.GetTileAtPosition(worldPos, out tileX, out tileY);


limegreen

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 6
    • View Profile
Re: Can't get world ray to identify tile
« Reply #2 on: September 21, 2017, 04:08:43 pm »
Thanks for the advice - works great