- Home /
How to tell if two objects are right next to each other in a 2d game?
I have two different blocks, one called Resource and one called Extractor. How do I tell if they are right next to each other on the x axis? Here is the code 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");
}
}
Answer by Ashutosh8126 · Feb 26, 2014 at 12:57 PM
Simply check the distance between them using..
if(Mathf.Abs(Extractor.transform.position.x - Resource.transform.position.x)< distanceYouExpect ){ Debug.Log("Next to each other.."); }
or you can try this also.. to make sure in all axes
if(Vector3.distance(Extractor.transform.position,Resource.transform.position).magnitude < distanceyouExpect)) { Debug.Log("Next to each other.."); }
For some reason this doesn't work. It debugs no matter where the Extractor block is.
What do you have 'distanceYouExpect' set to? Can we see your code with this fragment integrated?
Whenever i just start the game it logs the message. All of the blocks are 1x1. Here is the script:
#pragma strict
var Extractor : GameObject;
var Resource : GameObject;
function Update () {
if($$anonymous$$athf.Abs(Extractor.transform.position.x - Resource.transform.position.x)< 1 ){
Debug.Log("Next to each other..");
}
}
Just to cover all the bases... Have you made sure the Extractor and Resource variables point to different gameobjects?
Answer by Oniony · Feb 26, 2014 at 11:51 PM
Your original code should work if you just change the "==" to the appropriate "<=" or ">="
Like this:
if(Extractor.transform.position.x <= Resource.transform.position.x + 1 || Extractor.transform.position.x >= Resource.transform.position.x - 1 ){