I’m making a game that’s (theoretically) tile-based. Each floor tile occupies 1 unit of space, while a wall tile is .1 unit thick and sits on top of and between two floor tiles.
I need to be able to find all adjacent floor and wall tiles (ignoring diagonals). To do this I find all tiles within 1 unit using Physics.OverlapSphere. I then cull invalid tiles by making sure they’re all within 1 unit (unnecessary, but just to be safe).
The problem I have is when I run a Raycast to check if there’s a wall between tiles, to cull out invalid tiles that shouldn’t be added due to being on the other side of a wall. For some reason I’m not getting the proper number of tiles added that actually exist. I’ve setup debug colouring to turn a tile red when it has less than 8 adjacent tiles. The tiles in the picture all have between 1 and 6 tiles (except one tile which mysteriously has 7). This is obviously incorrect.
Any idea what I’m doing wrong?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class FloorTile : MonoBehaviour {
Collider[] adjacentObjects;
List<GameObject> adjacentTiles;
Vector3 raycastPos;
int layerMask = 1 << 8;
void Start(){
raycastPos = new Vector3(transform.position.x, transform.position.y + 3.5f, transform.position.z);
adjacentTiles = new List<GameObject>();
adjacentObjects = Physics.OverlapSphere(transform.position, 1f);
foreach(Collider col in adjacentObjects){
GameObject colGO = col.gameObject;
if(col.tag == "Wall"){
if(Vector3.Distance(transform.position, new Vector3(colGO.transform.position.x, 0f, colGO.transform.position.z)) <= 1)
adjacentTiles.Add (col.gameObject);
} else if(col.tag == "Floor"){
if(Vector3.Distance(transform.position, col.transform.position) <= 1){
if(Physics.Raycast(raycastPos, new Vector3(colGO.transform.position.x, 3.5f, colGO.transform.position.z), 1f)){
} else {
adjacentTiles.Add (col.gameObject);
}
}
}
}
InvokeRepeating("CheckForLeaks", 5f, 5f);
Debug.Log (adjacentTiles.Count);
}
void Update(){
}
void CheckForLeaks(){
if(adjacentTiles.Count < 8){
renderer.material.color = Color.red;
}
}
}