- Home /
Raycast2D not working with LayerMask
I am attempting to use a Raycast2D to detect if an attack has hit an enemy. I created a LayerMask for the "Enemy" layer and I have an object with a collider on the "Enemy" layer. I have no problem hitting the collider without using a LayerMask, however when I do, I get nothing back. What am I missing here?
LayerMask EnemyLayer;
void Start ()
{
EnemyLayer = LayerMask.NameToLayer ("Enemy");
}
public void BasicAttack()
{
PlayerVitality.Stamina = 0;
Vector2 attackDirection = CalculateAttackDirection ();
float attackDamage = CalculateDamage (BasicAttackDamage);
Debug.Log (EnemyLayer.value);
RaycastHit2D hit = Physics2D.Raycast(new Vector2(transform.position.x + 2, transform.position.y), attackDirection, BasicAttackDistance, EnemyLayer.value);
if (hit.collider != null)
{
Debug.Log("You hit: " + hit.collider.gameObject.name);
}
}
Answer by Brunomir · Apr 27, 2015 at 04:28 AM
RaycastHit2D hit = Physics2D.Raycast(new Vector2(transform.position.x + 2, transform.position.y), attackDirection, BasicAttackDistance,1 << LayerMask.NameToLayer("Enemy");
Thanks, that works! In my case the problem was that I left out the "1 <<" before the layer$$anonymous$$ask. What is this? The documentation doesn't mention this.
Layer$$anonymous$$ask.NameToLayer() returns an index, a value from 0 to 31. The layer$$anonymous$$ask is a bit vector where you can enable/disable each of the 32 layers by setting an individual bit. The (1 << number) starts with a "1" and shifts that bit to the left to the correct position.
There is also Layer$$anonymous$$ask.Get$$anonymous$$ask() which returns the correct value immediately.
Thank you for this. This should really be part of the documentation for Raycast though.