Hey, I’ve got an annoying issue I can’t seem to solve.
I’m working on a script to raycast outwards and determine if an area is suitable to place a Node, to later be used as available Enemy Spawn locations.
Code below:
void Awake()
{
spawnCreate = this;
newX = xPos_List[0]; // this is a list of the X positions for our "direction"
newY = yPos_List[0]; // this is a list of the Y positions for our "direction"
newNode_pos.Add(this.transform.position);
start_distance = distance;
direction = new Vector2(this.transform.position.x + newX, this.transform.position.y + newY);
RaycastFind();
}
public void RaycastFind()
{
RaycastHit2D hit = Physics2D.Raycast(this.transform.position, direction, distance, layers);
if (hit.collider==null)
{
Vector2 place = new Vector2(direction.x, direction.y);
if (!newNode_pos.Contains(place))
{
newNode_pos.Add(place);
distance += distance_add;
direction = new Vector2(this.transform.position.x + newX * distance, this.transform.position.y + newY * distance);
RaycastFind();
}
}
else if (hit.collider != null) // && hit.collider.CompareTag("Walls"))
{
if (i < (numberOfRays - 1)) // number of rays minus 1 to not exceed our List.Count for the X and Y direction variables, newX and newY respectively
{
i++;
newX = xPos_List[i];
newY = yPos_List[i];
distance = start_distance;
direction = new Vector2(this.transform.position.x + newX * distance, this.transform.position.y + newY * distance);
RaycastFind();
print("Scanning");
}
else if (i == (numberOfRays - 1))
{
i = 0;
newX = xPos_List[i];
newY = yPos_List[i];
distance = start_distance;
direction = new Vector2(this.transform.position.x + newX * distance, this.transform.position.y + newY * distance);
print("Reset");
//Finished Placing Nodes
}
}
}
What I was hoping / expecting: We raycast out in a direction and if there is no collision, raycast once more but with additional distance. Repeat until we hit a Wall at which point the ray changes its direction and resets distance to check. Rinse and repeat until all 16 rays have been used.
Instead I’m getting:
The nodes are being place as desired in a gradual outward fashion but the rays are stopping at seemingly random places. I’ve tried this on an empty scene and gotten the same results (switched to a live scene because my Test Scene has a lot of annoying / tedious to remove Errors - completely unrelated to this script, I promise!).
I’m not getting any errors with this, and I’ve tried debugging everywhere I can think of. Layer mask is set to the appropriate fields as well. One other odd thing is that int i is never reaching 16 (or returning to zero as in the last part of the else if).
Any help greatly appreciated!