I’ making a drag and drop sysem, where i need to know if something is already placed there.
private static Transform[,] grid = new Transform[width, height];
here i only create an array with the size of the grid
void AddTorGrid()
{
foreach (Transform children in transform)
{
int roundedX = Mathf.RoundToInt(children.transform.position.x);
int roundedY = Mathf.RoundToInt(children.transform.position.y);
grid[roundedX, roundedY] = children;
Debug.Log(roundedX + "," + roundedY);
}
}
I call this function when something is placed in the grid save it. And let write the position in the Console. To check the postiitons myself
bool ValidMove()
{
foreach (Transform children in transform)
{
int roundedX = Mathf.RoundToInt(children.transform.position.x);
int roundedY = Mathf.RoundToInt(children.transform.position.y);
if (roundedX < 0 || roundedX >= width || roundedY < 0 || roundedY >= height)
{
return false;
}
//das hier um zu gucken ob da bereits was ist
if (grid[roundedX,roundedY] != null)
{
return false;
}
}
return true;
}
here I’m first checking if the dragged object is placed into the grid. And then check the array ist something already is in there.
public void OnEndDrag(PointerEventData eventData)
{
if (!ValidMove())
{
rectTransform.anchoredPosition = defaultPos;
rectTransform.localScale = new Vector3(0.56f, 0.56f, 0.56f);
}
if (ValidMove())
{
if (snapToGrid)
{
transform.position = new Vector2(Mathf.RoundToInt(transform.position.x / gridSize) * gridSize, Mathf.RoundToInt(transform.position.y / gridSize) * gridSize);
AddTorGrid();
}
}
}
finally i call the functions by the end of the drag. But this shit is not workiing i dont know why. i ckecked everything 100times. And logically it must work. Everything works except that i can place antoher object on the already pplaced object.
I would be happy if someone can help me.