3
votes

for some reason my raycast hits objects, that are in another layer.

private int obstaclesLayerMask = (1 << 11) | (1 << 12);
private Vector3 GetPointOfContactNormal()
{
    Ray ray = new Ray(transform.position, transform.forward);
    if (Physics.Raycast(ray.origin, ray.direction, out hit, obstaclesLayerMask))
    {
        Debug.Log(hit.collider.gameObject.name);
        return hit.normal;
    }

    return Vector3.zero;
}

I`ve tried changing layerMask to random layers even the ones not specified like 1 << 30 and tried to use LayerMask.GetMask() instead, but raycast still hits objects. Only setting layerMask to default layer like 1 << 0 made raycast ignore collisions.

1

1 Answers

4
votes

Also to add to the above mentioned answer, i found something else that from my knowledge wouldn't work.

It seems like you are placing the obstaclesLayerMask in the distance Parameter of the Physics.Raycast

these are all the Parameters:

  1. origin: The starting point of the ray in world coordinates.

  2. direction: The direction of the ray.

  3. maxDistance: The max distance the ray should check for collisions.

  4. layerMask: A Layer mask that is used to selectively ignore Colliders when casting a ray.

  5. queryTriggerInteraction: Specifies whether this query should hit Triggers.

the argument range would be correct if you change it to this:

//I put it on 300f here but just put there what you prefer.
if (Physics.Raycast(ray.origin, ray.direction, out hit, 300f, obstaclesLayerMask))