I’m working on a game whose entire play space is divided into an imaginary 2d grid, and figuring out which grid square the player is clicking on by taking the mouse coordinates and dividing them by the size of each square:
public struct Grid2D
{
public float height;
public float width;
public Vector2 WorldToGrid(Vector3 worldCoords)
{
float xCoord = (int)worldCoords.x / width;
float yCoord = (int)worldCoords.y / height;
Vector2 gridCoords = new Vector2(xCoord, yCoord);
return gridCoords;
}
public Vector3 GridToWorld(Vector2 gridCoords) //Doesn't work yet
{
float xCoord = gridCoords.x * width;
float yCoord = gridCoords.y * height;
Vector3 worldCoords = new Vector3(xCoord, yCoord, 0);
return worldCoords;
}
}
This kinda-sorta works, in the sense that it does correctly divide the world into an arbitrary number of squares of dimensions height/width, but I’m having a lot of trouble getting sprites to snap inside these squares- whenever I set a sprite’s transform.position equal to GridToWorld(vector2Coords), it centers itself on the edge of the square instead of the center. I made a little illustration, the black square indicates the space that Grid2D identifies as (0,0), and the red square indicates where a 1x1 sprite appears if I spawn it at GridToWorld(new Vector2(0,0)).

Is there (hopefully) something wrong with my logic, or is this a case where I need to be hardcoding a spawn offset for every single sprite based on its dimensions?