Raycast2D only hit Trigger Collider


i have a problem with my switch in a simple 2D game.

I use 2 colliders:

  • one for checking if the Player is inRange(isTrigger) to use the switch (Bigger one)
  • and one and one for his Hitbox. (Smaller one)

then i use a Raycast2D whenever i click on my mouse and if the Object this Raycast hits is the switch, then it will call Use()

the problem is that the raycast always hits the trigger that is only used to determine the range. I already tried to ignore the trigger by using !hit.collider.isTrigger in an if statement but then it will do nothing because its the only collider which was hit. I also tried to deactivate the “Queries hit triggers” in the physics settings but that changed nothing.

A boxcast2D method can check for player, and you wouldn’t need two separate colliders for the ray to get confused by, just the one you want the RaycastHit2D to check.

Here is a generic example from Unity API:

RaycastHit2D BoxCast(Vector2 origin, Vector2 size, float angle, Vector2 direction, float distance = Mathf.Infinity, int layerMask = Physics2D.AllLayers

Replace origin with the transform.position of the switch and the size with how big you want the boxcast to check for, and then you can plug a 0 for angle, direction, and distance; but for the layemask, you need to choose the player.

The easiest way to check for player layer is to give this switch a variable of a public layermask, and then you can choose the player in the inspector.