- Home /
Question by
BZS · Feb 25, 2014 at 01:54 AM ·
javascriptgameobjectposition
How to tell if two blocks are right next to each other?(2D)
I am making a 2d game and want to tell if two 1x1 blocks are right next to each other. How would I do this? Here is the script I made:
#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");
}
}
Any advice? Thanks in advanced.
Comment
Answer by Kiloblargh · Feb 25, 2014 at 02:10 AM
The code above should work. But if your game is a grid of 2d blocks you should be storing references to them in a 2d array.
var blockArray : GameObject[,];
If the array coords correspond to 1 unit blocks in world space, you can do this :
var extIntX : int = Mathf.FloorToInt (Extractor.transform.position.x);
var extIntZ : int = Mathf.FloorToInt (Extractor.transform.position.z);
var canExtract : boolean = false;
if (blockArray [extIntX-1, extIntZ].tag = "Resource") { canExtract = true;}
if (blockArray [extIntX+1, extIntZ].tag = "Resource") { canExtract = true;}
if (blockArray [extIntX, extIntZ-1].tag = "Resource") { canExtract = true;}
if (blockArray [extIntX, extIntZ+1].tag = "Resource") { canExtract = true;}
if (canExtract) {
Debug.Log ("Extract");
}
Not fully working as is, you have to set it up in functions and initialize stuff, as well as check to avoid ArrayIndexOutOfRangeException
s when you're at the edges- but that should give you the general idea.