I have a 8x8 grid sprite (each square is a perfect 100x100 pixel box) that the player uses as a map in-game to move around in relative game coordinates. The player will click on a square in the grid, which is relative to a coordinate in the game world. I need to calculate the position where the player clicked, on this grid, and call a method in C# from this.
How can I do this relative to the grid sprite, once the box collider 2D detects a raycasthit? Is it possible to translate the centre coordinates of the sprite to 0,0, so I can calculate each hit accurately?
RaycastHit2D.point is a world point. You can convert it to a local coordinate using Transform.InverseTransformPoint(). If you select your texture/sprite in the Inspector, you will see a setting for ‘Pixels to Unit.’ The default is 100. So if you have 8 boxes that are each 100 units across, your sprite will be 8 x 8 units in world space.
I’m not sure how you want to map the squares. It might be easiest to use a values system that uses the lower left corner as your starting point (i.e. the lower left corner square would be (0,0) and the upper right corner would be (7,7)). This can be accomplished by either setting the anchor for your sprite as the lower left corner or by adding (4,4) to whatever coordinate you get when you do the Transform.InverseTransformPoint(). Rounding to an int will then give you the i,j indices of your square.