- Home /
Placing Objects on a grid,
Hi, I am new to coding and am working on a new game project, I created a grid and have taken all the grid positions in a list, now I need to snap my objects to the grid positions. I did it but there comes a problem I don't want another game object to snap to the position where a previous game object is already snapped, can you help here is my code
public class Newdragdrop : MonoBehaviour { private bool isbeingheld = false; public List GridPositionFinal = Grid.GridPosition; private int index; public List GridFilledPositions; Vector3 closestObject;
private List<Vector3> objectpositions;
private void Update()
{
if(isbeingheld == true)
{
Vector3 mousepos;
mousepos = Input.mousePosition;
mousepos = Camera.main.ScreenToWorldPoint(mousepos);
this.gameObject.transform.localPosition = new Vector3(mousepos.x, mousepos.y, -0.1f);
}
}
private void OnMouseDown()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 mousepos;
mousepos = Input.mousePosition;
mousepos = Camera.main.ScreenToWorldPoint(mousepos);
isbeingheld = true;
}
}
private void OnMouseUp()
{
Vector3 mousepos1;
mousepos1 = Input.mousePosition;
mousepos1 = Camera.main.ScreenToWorldPoint(mousepos1);
var distance = 1.5f;
foreach (var snapgrid in GridPositionFinal)
{
var currentSlotDistance = Mathf.Sqrt(Mathf.Pow((mousepos1.x-snapgrid.x),2.0f)+ Mathf.Pow((mousepos1.y - snapgrid.y), 2.0f));
if (currentSlotDistance < distance)
{
closestObject = new Vector3(snapgrid.x, snapgrid.y, 0);
}
}
if (mousepos1.x > -4.0f && mousepos1.y < 3.2f)
{
this.gameObject.transform.localPosition = new Vector3(closestObject.x,closestObject.y,0);
}
}
}
,
Answer by Klarzahs · Oct 26, 2020 at 08:59 AM
Hi @amithreddy93,
Is your grid, well, grid like, meaning does it have a rigid and evenly spaced offset between each possible position? If so, you can find your actual grid position like so (untested):
mousepos1 = Input.mousePosition;
mousepos1 = Camera.main.ScreenToWorldPoint(mousepos1);
gridPos = new Vector2(mousePos1.x - mousePos1.x%OFFSETX, mousePos1.y - mousePos1.y % OFFSETY);
You basically take the overshoot over the possible positions and subtract it. That way you don't actually need to save all the possible positions beforehand, and you especially don't have to loop all over them each time
To actually save/check for duplicates, it depends on whether you expect to have a filled grid, or a rather empty one. If you want to have a filled grid in the end, you can use a 2D array as a lookup. If you want to have a rather empty grid, you can still use an array, but it will be mostly empty too. Which is wasted memory :) So you can use a Dictionary<Vector2, GameObject>
as a lookup