- Home /
Raycasts not working on triggers.
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");
}
Answer by AndBje · Apr 10, 2021 at 07:44 PM
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?
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.
Make sure your ray isn't hitting the collider/trigger on the object you are pointing from.
I guess you have already checked this - but is the "Layer Collision Matrix" in Project Settings correct?
Double check the layer mask "laneTrigger" so it is set as you expect.
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!");
Answer by XSpitFire · Jul 19, 2021 at 08:45 PM
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
Your answer
Follow this Question
Related Questions
RayCast2d Not colliding with objects in other layers 1 Answer
Is there a way to detect if an object is being hit by a raycast? 2 Answers
Raycast returns null for no apparent reason 0 Answers
Trying to play other objects' sound and animations from Raycast hit 1 Answer
[help]RayCast check [SOLVED] 2 Answers