Exclude colliders from raycast
What do I need is to ignore some colliders during raycast (objects which I want to ignore is on the same layer with objects which I want to hit. For example, I have AI which uses colliders to detect enemies, but I don't want its own collider to block the view.)
So, in general I need to use Physics.RaycastAll, exclude collider which I want to ignore and be happy, but it seems to work very slowly. So, what I have tested that is other ways to ignore colliders with using simple Physics.Raycast:
1. Just disable colliders, then enable.
2. Disable game objects, then enable.
3. Change game object layer, then revert.
And here results for 1000k raycasts:
Code which I used - https://pastebin.com/2TwNt0u8
So, changing layers and then rolling back seems to be the most optimal solution. So, the question - is there any better solution?
Answer by Desoro · Oct 31, 2017 at 03:34 PM
Put the enemies on their own layer and Raycast to only that layer. It is also worth noting that Raycasts that start inside a collider, will ignore said collider.
Enemies are already on their own layer. Raycast is not going from inside.
So if the collider on the AI that detects enemies isn't on the same layer as the enemies, you have no issue. Just Raycast to only the enemy layer using a mask.
But this contradicts your statement "objects which I want to ignore is on the same layer with objects which I want to hit".
All objects are on the same layer. If object will raycast it will detect itself.
#1 Layering
LayerA = AI's layer
LayerB = enemy layer
------OR--------
#2 Ignore Self
LayerA = all entities (AI is also an enemy)
Start Raycast at the center point of the collider on AI. This will ignore the collider on the AI.
AI and enemy is the same, there is no difference between them. As I said, there are just colliders which are used to detect entities, the problem is that owned collider can obstruct raycast, rude layering will not help here. 2. There is no way to throw ray from the center (there are more than one collider per object).
Your answer
Follow this Question
Related Questions
How to ensure raycasts hit colliders inside of trigger colliders on objects that have a rigidbody? 0 Answers
Not able to raycast on image 1 Answer
How to get the Normal of a collider for orienting an explosion. 1 Answer
Shooting through walls 0 Answers
Raycast collisions being detected along a non-existent curve(?) 1 Answer