unity-game-enginegriddragsnapping

How to check for gameObject while Grid Snaping in Unity2D


I am trying to make a game which allows moving objects by snapping them on the grid, I already figured out to snape them to grid but there is one thing little problem, I want to check if there is already a game object placed on that same grid so that I won't let the dragging game object snap to that same spot but the thing is that I have a different game object shapes.

see for yourself

Click to see the image

how can I achieve that?


Solution

  • Since you're on a square grid I think the best way to do this is with Physics2D.Boxcast(). Basically what you're doing is casting a box at the snap vector before moving the game object.

    So in your code before you move the game object to the snap location:

    RaycastHit2D hit = Physics2D.BoxCast(snapTo, boxSize, 0.0f, Vector2.zero);
    if (hit == null)
    {
        // We're clear to move
    }
    else
    {
        // Something is in the way
    }
    

    Where snapTo is the Vector2 of the location you're going to snap to and boxSize is a Vector2 equal to the size of one grid position (you might need to play around with this a bit). The last two arguments, 0.0f refers to the angle of the box, which we don't need so just set it to zero and Vector2.zero is the direction of the cast, but we're casting in one spot so this also doesn't matter.

    I'm assuming that only one game object can occupy the space at once, so there will only ever be one hit. If there's a chance for more than one you can change it to RaycastHit2D[] hits and Physics2D.BoxCastAll then check if hits.Length is greater than 0.