Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Raycast registers one hit per collider

Discussion in 'Physics for ECS' started by Drayanlia, Jul 13, 2023.

  1. Drayanlia

    Drayanlia

    Joined:
    Jan 14, 2021
    Posts:
    10
    Hi there,

    I have a very simple scene with just a box entity with a physics shape and a physics body set to kinematic.
    I am trying to cast a ray through it and get the number of resulting hits. I expect to get two hits, one from "entering" the collider and one from "exiting" but only get one.

    I am under the impression it should be working since this is a very basic setup. Am I missing something ?

    Any help is much appreciated

    Code (CSharp):
    1.             var CollisionWorld = SystemAPI.GetSingleton<PhysicsWorldSingleton>().CollisionWorld;
    2.  
    3.             var worldPosition = new int3(100, 200, 100);
    4.             var rayDirection = new int3(0, -1, 0);
    5.  
    6.             var rayEnd = worldPosition + 1000 * rayDirection;
    7.  
    8.             RaycastInput input = new RaycastInput()
    9.             {
    10.                 Start = worldPosition,
    11.                 End = rayEnd,
    12.                 Filter = new CollisionFilter
    13.                 {
    14.                     BelongsTo = 1u << 0,
    15.                     CollidesWith = 1u << 1,
    16.                     GroupIndex = 0,
    17.                 },
    18.             };
    19.  
    20.             var hits = new NativeList<Unity.Physics.RaycastHit>(Allocator.Temp);
    21.  
    22.             CollisionWorld.CastRay(input, ref hits);
    23.  
    24.             var hitCount = hits.Length;
    25.             Debug.Log($"{hitCount}");
     
  2. Drayanlia

    Drayanlia

    Joined:
    Jan 14, 2021
    Posts:
    10
    Seems like it actually is the intended behaviour. My bad.

    A straightforward solution is to cast a new ray from every new intersection point until no intersection is found but this sounds quite inefficient for my use case (checking if a point is inside a group of meshes). Will explore other solutions.