Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only.

    Please, do not make any changes to your username or email addresses at id.unity.com during this transition time.

    It's still possible to reply to existing private message conversations during the migration, but any new replies you post will be missing after the main migration is complete. We'll do our best to migrate these messages in a follow-up step.

    On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live.


    Read our full announcement for more information and let us know if you have any questions.

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:
    11
    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:
    11
    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.