Search Unity

All Collisions Count

Discussion in 'Physics for ECS' started by kro11, Apr 25, 2021.

  1. kro11

    kro11

    Joined:
    Sep 23, 2019
    Posts:
    105
    Is it possible to get all collisions count in a frame?
     
  2. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    What is the use-case you have in mind?
    Depending on what you mean by collision count (# Collision Pairs, # Contact Points, # Collision Events) there are different answers.
     
  3. kro11

    kro11

    Joined:
    Sep 23, 2019
    Posts:
    105
    This. I want to prevent too many push collisions by changing the speed of the physical objects. Just need to change a coefficient depending on the current number of collisions.
     
  4. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    You can use an ICollisionEventsJob to count the collisions on specific shapes that are flagged to raise them upload_2021-4-29_9-53-13.png

    An IContactsJob can count low level contacts (though this will be for all bodies).
    An IBodyPairsJob could count overlaps (though again this is for all bodies.

    The latter 2 options mean you'd be going over all contact or pairs and you'd need to filter the count if you are only interested in a specific body/bodies. On that note, if you are only interested on details of a single body, then a specific PhysicsWorld.CalculateDistance query might be the more optimal approach.
     
    kro11 likes this.
  5. kro11

    kro11

    Joined:
    Sep 23, 2019
    Posts:
    105
    As I understood it is executed in one thread? I have 10k+ rigidbodies which interact with each other and have tried ICollisionEventsJob and it took a very long time in one thread. I thought there was a simple way like m_query.CalculateEntityCount().
     
  6. steveeHavok

    steveeHavok

    Joined:
    Mar 19, 2019
    Posts:
    481
    The ICollisionEventsJob certainly needs parallelized, but is a common interface between the Unity Physics and the Havok Physics simulation backend. It's also pretty safe in terms of giving valid information at the appropriate time.

    If you are sure about your scheduling, only interested in the Unity Physics simulation, and are happy to make local modifications to the com.unity.physics package you could try adding a
    Count
    property to the
    CollisionEvents
    struct e.g.

    public int Count => m_EventDataStream.IsCreated ? m_EventDataStream.Count() >> 1 : 0; 


    Then you can use the property like

    var numCollisionEvents = (World.GetOrCreateSystem<StepPhysicsWorld>().Simulation as Unity.Physics.Simulation).CollisionEvents.Count;


    You need to be careful when you read it though to ensure that the StepPhysicsWorld jobs are finished adding events to the underlying NativeStream.
     
    kro11 likes this.