- Home /
Mouse position to Isometric Grid Tile number
I am trying to use a mouse position to find a grid location (column / row). Can anyone help me write a few lines of code to make this happen?
The grid starts at world position (0,0) and stretches downwards and out. The maximum number of rows is 61 and the maximum number of columns is also 61. The entire grid is stored in a single dimension array. Indexes 0 through 60 represent row 0, columns 0 - 60. Index 61 would mean row 1, column 0. See photo here: Image
The tiles are 4 units in height and 8 units in width.
By the way ... there's no resin you can't do this with colliders!
Just shoot a ray downwards, and find out which square it is.
Answer by Bunny83 · Jan 23, 2012 at 05:42 AM
Is there any good reason why you arranged your squares at 45°? You should just arrange them paralell to the world axes and place the camera rotated at the desired position.
The coordinates are just the world position divided by the tile size. One tile is 4x4 so if you use the Plane class for example to get the world position of your click, just divide it by 4 and "round down" / "truncate the number" / "cast to int" to get the index value.
You should really rephrase your question since this is a Q&A site, not a free-script-shop.
Here's a small code snippet how to get the world position of the mouse on a Plane:
//C# // Define your ground plane by create an Plane instance with your plane coordinates / normal Plane myPlane;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); float distance; if (myPlane.Raycast(ray,out distance)) { Vector3 pos = ray.GetPoint(distance); int xIndex = (int)(pos.x / 4); int yIndex = (int)(pos.y / 4); int index = yIndex*61 + xIndex; // Do something }
You had negative numbers in your image so keep in mind that you might need to invert one number first.
If your ground plane goes through (0,0,0) and is facing upwards just create the plane like this:
Plane myPlane = new Plane(Vector.up,Vector.zero);
The first parameter is the normal vector, the second a point on the plane.
Thanks for the reply. The tiles are not squares at all; ins$$anonymous$$d, they are diamonds that sit on a plane.
Do the diamonds have four right-angled corners, with each side being the same length as all the others? Because that sounds awfully similar to a grid of squares rotated to 45 degrees.
Since I'm apparently a complete idiot and have no idea what a square is, I searched google for what I am referring to. http://i.imgur.com/mh$$anonymous$$rX.png
It's a square, transformed into 3-dimensional space, and then rendered onto a 2-dimensional plane at 45 degrees. What's your point?
Right, there's no reason to make things hard on yourself. Just use squares like syclamoth said. It would also be generally simpler not to use negative numbers for coords.