- Home /
Raycast should ignore everything but player, yet still gets interrupted
I have an enemy that's constantly checking to see if it can see the player through a simple raycast. The raycast is instructed to only observe general obstacles (in the 'default' layer) and the player (in the 'player' layer). It should ignore everything else, except when the player is holding a pickup (in the 'pickup' layer), the enemy says it can't see the player.
Why doesn't the raycast ignore everything but the player? I can't get it to stop observing pick-ups that the player is holding.
lookMask is a public LayerMask that is set to true on "default" and "player", everything else is unchecked. eyes represents the enemy's raycast starting position, and it looks for the graphics of the player (which has the 'player' layer).
private bool CanISeePlayer() {
var hit = new RaycastHit();
var rayDirection = (eyes.position - player.transform.Find("Graphics").position) * -1;
Debug.DrawRay(eyes.position, rayDirection, Color.green);
if (Physics.Raycast(eyes.position, rayDirection, out hit, lookMask)) {
Debug.Log(hit.transform.gameObject.name);
return (hit.transform == player);
}
return false;
}
The code works just fine in finding the player, but can be obstructed by things it's not supposed to be obstructed by.
Answer by Bunny83 · Jul 25, 2020 at 05:08 PM
Just check the documentation of Physics.Raycast. You're using the second overload from the top:
public static bool Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo, float maxDistance, int layerMask, QueryTriggerInteraction queryTriggerInteraction);
The fourth parameter is the max raycast distance. Here you pass in your layermask. The actual layermask parameter is parameter #5 which you omit and therefore it's the default layermask.
So you probably want to use
if (Physics.Raycast(eyes.position, rayDirection, out hit, float.PositiveInfinity, lookMask)) {
Your answer
Follow this Question
Related Questions
SphereCast doesn't work with a layerMask 1 Answer
unity raycast layers in Multiplayer 0 Answers
Raycast Layermask doesn't ignore no layered Parent? 1 Answer
Layermasks 1 Answer
How does Raycast layer mask work? 1 Answer