- Home /
Question by
BZS · Mar 18, 2014 at 09:43 PM ·
javascriptposition
How to tell if an object is right next to another?
They are 2 1x1 blocks. I tried:
function Update(){
if(object1.transform.position.x==object2.transform.position.x+1){
Debug.Log("Next To Eachother");
}
}
but it didn't work. How would I do this?
Comment
Best Answer
Answer by koray1396 · Mar 18, 2014 at 09:48 PM
maybe this?
if(Mathf.Abs(object1.transform.position.x - object2.transform.position.x) == 1){
Debug.Log("Next To Eachother");
}
Or you can try raycasting in a specific direction =]
if(Physics.Raycast(this.transform.position, Vector3.right, out hit, 1f))
Answer by le_duke · Mar 18, 2014 at 09:57 PM
I think that your code should work but I'dont think that it will give you the result you want.
First the pivot of your a cube is by default centered so your code should be more like :
if(object1.transform.position.x==object2.transform.position.x+0.5){
Debug.Log("Next To Eachother");
}
But this code mean that your object 2 must be exactly right to the next one and on the right side. so it should be interesting to use a range between wich one you consider that your cube is right next to another.
for exemple :
//if object 2 is on the right side of your cube in a range of 0.5
if(object2.transform.position.x>object1.transform.position.x+0.5 && object2.transform.position.x<object1.transform.position.x+1){
Debug.Log("Next To Eachother");
}
you can adapt this code to take in account all the axis etc ...