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
how can I achieve that?
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:
Where
snapTois theVector2of the location you're going to snap to andboxSizeis aVector2equal to the size of one grid position (you might need to play around with this a bit). The last two arguments,0.0frefers to the angle of the box, which we don't need so just set it to zero andVector2.zerois 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[] hitsandPhysics2D.BoxCastAllthen check ifhits.Lengthis greater than 0.