Physics2D. Raycast() - How to use the ContactFilter2D Overload?

Concept: I’m using this to create a 2D “laser” hazard of sorts for a 2D puzzle game. Laser can be blocked by certain objects to allow passage and it will cause damage to the player if they touch the laser.

I am basically trying to use Raycast to shoot a ray and detect collisions in the game space, however I only want the ray to detect collisions with particular layers in my scene and not others (i.e. the tilemap, the player, a platform, etc.)

I declare a public variable for ContactFilter2D and call if “cf”. I configure the layers I want to be detected in the unity inspector and check the “use Layer Mask” checkbox.

However, when I try to use “cf” as an ContactFilter2D overload in Physics2D.Raycast, it is expecting the ContactFilter2D to return an int value.

Might I need to convert the layers I specified in my contact filter into an array of some sort that will give them an int value?

Hey,

I’ve never actually used this before, but it looks like you need to access the .layerMask property of the contact filter.

    ContactFilter2D filter;

    void Update()
    {
        Physics2D.Raycast(transform.position, Vector2.up, 1f, filter.layerMask);
    }

Hopefully that works, I haven’t tested it.

Physics2D.Raycast has a bunch of overloads, so you might be getting the wrong one by accident. I do it like this:

int hitCount = Physics2D.Raycast(origin, dir, filter, output, length);

In this case, output is a RaycastHit2D[ ], and filter is the ContactFilter2D. If you don’t include the RaycastHit2D array output, I think you’ll get a different overload.

That seems to have done the trick. Thanks!

this is exactly what I was looking for. I appreciate the help

1 Like