- Home /
How to tell if 2 blocks are next to each other in a 2d game?
I am trying to figure out if two different 1x1 blocks are right next to each other. I just can't seem to make it work. Here is a script that I tried:
 #pragma strict
 var Extractor : GameObject;
 var Resource : GameObject;
  
 function Update () {
 if(Extractor.transform.position.x == Resource.transform.position.x + 1 || Extractor.transform.position.x == Resource.transform.position.x - 1 ){
     Debug.Log("Extract");
 }
 }
Depends how you want them to behave. Eg, is either moving controlled via a rigidbody's forces / velocity? Is either staying in the same place once spawned? Are their positions always snapped to the nearest whole number to emulate a grid placement system? Depending on your answer to those questions, you'll have different best solutions.
$$anonymous$$aking an assumption and saying you're working with a system that snaps to a grid and that neither block will be moved, your current method is comparing floats directly, which can have issues when it comes to rounding errors. Use $$anonymous$$athf.Approximately(myFloat1,myFloat2) to do more reliable comparisons, perhaps that'll fix your issue.
Answer by Linus · Feb 26, 2014 at 01:14 AM
In this example if from a tile set of 2D sprites. Each tile checks to find its neighbor tiles.
I use 0.32 as offset in each direction since my sprite is 32px.
 var marketArea : Collider2D[] = Physics2D.OverlapAreaAll( Vector2(transform.position.x-0.32, transform.position.y-0.32), Vector2(transform.position.x+0.32, transform.position.y+0.32) );
     
 for (var i = 0; i < marketArea.Length; i++) {
     //Here I test it the collider next to the sprite has a tileBehaviour script
     // you could test for other things like tag or name
     if(marketArea[i].GetComponent(tileBehaviour) ){
         Debug.Log("Current Market "+marketArea[i].transform.name);
         marketPopulation += marketArea[i].GetComponent(tileBehaviour).population;
     }
 }
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                