- Home /
Mixing OverlapSphere and raycast physics to filter list
So I'm making a tower defense game, and the tower uses an OverlapSphere at several stages to essentially bounce from one enemy to the other, always choosing the closest. an example of this is in the code below:
visibleRange = Physics.OverlapSphere(currentEnemy, towerRange, enemyMask).
Where(n => !usedEnemies.Contains(n)).ToList();
visibleRange = visibleRange.OrderBy(enemy => Vector3.Distance(startPosition, enemy.Position)).ToList();
The enemyMask is the layer that all my enemies are on, and usedEnemies exists so that I don't double up on everything.
Everything works, beautifully. I couldn't be happier for what I have written. I then noticed a problem, that it was shooting through walls. Makes sense, OverlapSphere discriminates against none. So I made a change, adding a raycast:
visibleRange = Physics.OverlapSphere(currentEnemy, towerRange, enemyMask).
Where(n => !usedEnemies.Contains(n) &&
Physics.Raycast(this.stickEnd.transform.position, n.GetComponent<Collider>().bounds.center - this.stickEnd.transform.position, towerRange).Equals(n)).ToList();
visibleRange = visibleRange.OrderBy(enemy => Vector3.Distance(startPosition, enemy.Position)).ToList();
Perhaps I don't know enough about Linq, which is entirely possible. I am rather new to the concept of lambdas. It still shoots through walls, and I can't think a reason why it should be able to, nor have I found anything online to suggest a solution.