Raycasts not working on triggers
Asked Answered
H

3

0

My Raycasts don’t work on triggers, however I have Queries hit triggers turned on in physics settings, I have also tried QueryTriggerInteraction.Collide, but that does’t work.
However if I set my triggers to colliders it works, but I need them as a trigger, If I put them as a collider it breaks my game…(edited)
this is an example of my code:

if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.right), out hit, 2f, laneTrigger, QueryTriggerInteraction.Collide) && isMoving && laneNum == 2 || Physics.Raycast(transform.position, transform.TransformDirection(Vector3.right), out hit, 2f, laneTrigger, QueryTriggerInteraction.Collide) && isMoving && laneNum == 0)
{
    Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.right) * hit.distance, Color.yellow);
    Debug.Log("Right Hit" + hit.collider);
    moveX = 0f;
    isMoving = false;
}
else
{
    Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.right) * 2f, Color.white);
    Debug.Log("Target not hit");
}
Hygrothermograph answered 14/10, 2023 at 15:13 Comment(0)
D
0

Are you sure you are only changing the isTrigger property on the collider? It sounds like there is something else that is causing the problems. The QueryTriggerInteraction.Collide, which you have already tried, should make the ray hit whether it is a collider or a trigger (regardless of the physics settings).

When the ray misses - is the white debug line going through the object with the trigger?

  1. A common error I have seen is that the collider is disabled (I have never done so myself, of course). An easy mistake in the editor, but it can also be disabled by code. Check it while the game is running.

  2. Make sure your ray isn’t hitting the collider/trigger on the object you are pointing from.

  3. I guess you have already checked this - but is the Layer Collision Matrix in Project Settings correct?

  4. Double check the layer mask laneTrigger so it is set as you expect.

  5. If the Raycast still does not hit - try and make a simple Raycast call (without unnecessary game logic) and the layer mask set to Physics.AllLayers.

if (Physics.Raycast(transform.position, target.position - transform.position, out RaycastHit raycastHit, float.MaxValue, layerMask, QueryTriggerInteraction.Collide))
    Debug.Log("HIT!");
else
    Debug.Log("MISS... very strange!");
Deliadelian answered 14/10, 2023 at 15:29 Comment(0)
S
0

I also found that starting your raycast within a collider will not detect that collider. Make sure your raycast starts well outside of the collider

Sleuthhound answered 19/7, 2021 at 20:45 Comment(0)
I
0

Same on 2023.x . It is a bug!!!'nn

Innermost answered 14/10, 2023 at 14:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.