Today I was having an interesting issue myself. For my 2D spaceship-crew-management game, I had recently added some components that allow military characters to seek out enemy targets.
Every military character essentially has a circular collider trigger with a certain range. Whenever an enemy enters the trigger, it is stored as a potential enemy threat. If the military character has no enemy in sight, it will go over the list of potential targets and perform raycasts until it finds a valid target. This all seemed to work well, I had tested it in a small-scale setup with two characters fighting each other.
However today I was playing around with a larger scene, and suddenly one of the characters was no longer acquiring the obvious target. Instead the character just stood there and let himself get shot. What was going on?
It took me a few hours to finally figure this one out, probably because I hadn't touched this code in a few days as well. Because the cause of the problem wasn't trivial I decided to implement a bunch of visual debugging aids, of which you can see the results below. A bunch of gizmos are being drawn representing the various ongoing raycasts, projectile targets, etc...
|Results of visual debugging.|
Note that it did take a bit of time to set up these visual aids, you have to make sure that the various targets for the DrawLine function are in fact correct. In doing so, you'll naturally come across other potential bugs that would have otherwise escaped your attention.
So back to our problem: the military character on the right of the image isn't targeting the military character in the middle of the image. Having the new visual aids, the cause of the problem quickly became clear. The blue lines represent blocked raycasts towards characters within range. Obviously the white civilian character is behind a wall, so having that raycast blocked is expected behavior. However, the blue line heading towards the central military character is being blocked by a large green circle!
This circle was actually the "sight radius" trigger from another military character (the one all the way on the left of the screen). So the solution was to simply set layer of the sight radius gameobject to "Ignore Raycast". Having implemented that, the two military rivals are now happily targeting each other once again.
Hurray for visual debugging!
|Combat wages once more as the problem is solved!|