I’m trying to programming in Unity an 2d grid, where i can press the right button the mouse and the position of the mouse is used as the position to instantiate a game object. The game object will be instantiated in the cell of the grid.
So i create a matrix of Rect and I use the function of the Rect to intersect the position of the mouse and the Rect that included it.
What i have done until now seems to work, but there is a bug that i could’nt fix.
It seems that only a portion of the screen where the script work.
Can anyone help me to figure out where i’m wrong?
I pass the script:
public class GridManager : MonoBehaviour {
public GameObject gameobject;
public int max_row = 9;
public int max_coll = 18;
public int cell_width = 120;
public int cell_height = 120;
private GameObject[,] gameBoard;
private Rect[,] grid;
void Awake(){
gameBoard = new GameObject[max_row, max_coll];
grid = new Rect[max_row, max_coll];
for( int y = 0; y < max_coll; y++)
{
for ( int x = 0; x < max_row; x++)
{
grid[x, y] = new Rect(x * cell_width, y * cell_height, cell_width, cell_height );
}
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if(Input.GetMouseButtonDown(0)){
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
for( int y = 0; y < max_coll; y++)
{
for ( int x = 0; x < max_row; x++)
{
if ( grid[x, y].Contains( ray.origin) )
{
Instantiate(gameobject, new Vector3( grid[x, y].center.x, grid[x,y].center.y, 0 ), transform.rotation);
Debug.Log("x" + grid[x, y].center.x );
Debug.Log("y" + grid[x, y].center.y );
Debug.Log("mouse x " + ray.origin.x);
Debug.Log("mouse y " + ray.origin.y);
}
}
}
}
}
}