- Home /
Does RayCast crosses mesh colliders?
Hello, Im making a raycast with this code, its in the enemy to shoot the player:
void Update() { timer += Time.deltaTime;
shootRay.origin = transform.position;
shootRay.direction = transform.forward;
if (Physics.Raycast(shootRay, out shootHit, range, playerMask))
{
PlayerHealth playerHealthDetected = shootHit.collider.GetComponent<PlayerHealth>();
if (playerHealthDetected && timer >= timeBetweenBullets)
{
Shoot(playerHealthDetected);
}
}
}
My problem is that after, when i run the game, if theres a wall with a mesh collider between the player and the enemy, the enemy keeps shooting me. Why does this happend? The wall mesh collider doesn't have a PlayerHealth component, is the raycast crossing that collider?
Thank you very much.
Answer by goutham12 · Sep 15, 2017 at 12:41 PM
it will shoot. you coded like that.
if (Physics.Raycast(shootRay, out shootHit, range, playerMask)) { }
in the above code you gave layer mask so unity will ray cast to player even other collieders are in middle. remove that layer mask and try. like
if (Physics.Raycast(shootRay, out shootHit, range, out hit)) { if(hit.collieder.gameobject.tag == "Playertag") { Shoot(playerHealthDetected);
}
}
Answer by Viturbiko · Sep 15, 2017 at 01:48 PM
Great, it works. So, the LayerMask is used to IGNORE colliders? This is what I found in documentation:
"A Layer mask that is used to selectively ignore Colliders when casting a ray."
Thanks again.