Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Question Capsule rigidbody very noticeably penetrates ground even with continuous detection

Discussion in 'Physics' started by ThaBullfrog, Mar 7, 2024.

  1. ThaBullfrog


    Mar 14, 2013
    When my capsule collider rigidbody (height 2, radius 0.5) vertically collides with a static box collider at a speed of 41, it penetrates it by 0.35, over 1/6th of the collider's height! Due to the shape of my character mesh, this is very noticeable to the player as a big portion clips below the ground for a couple frames.

    I've tried changing the fixed timestep, max depenetration velocity, default contact offset, solver iterations, etc. Nothing changes it. I even tried scaling up the entire game by 10x, but I guess since the speed was 10x faster, the penetration distance also scaled up to match.

    Is this in line with what can be expected of Unity physics, or is there something weird going on in my project?

    Why would there be any penetration with continuous collision detection? And why doesn't the engine attempt to depenetrate in a single physics step? I could understand how that might not be possible if there's many colliders competing for the same space, but in the case of one rigidbody colliding with one static collider, I expected better. It's taking it 2-4 steps to fully depenetrate the colliders.

    Has anyone else needed a much smaller margin of error for penetrations? How did you deal with it?

    The only thing I can think of at this point is using either the contact point data in the collision events or Physics.ComputePenetration to modify the transform myself. But I thought I'd check here to see if there's a less hacky way and ask what the unintended consequences might be if I modify the position myself. I could potentially just adjust the visible mesh and not the rigidbody game object if changing the position would mess up the physics too much.
    mischa2k likes this.
  2. zulo3d


    Feb 18, 2023
    With continuous collision detection there shouldn't be an issue.

    Try creating an empty scene and place a rigidbody capsule with continuous collision detection enabled above a cube. The falling capsule shouldn't penetrate the cube at all regardless of how high it falls from.

    Only when switching the collision detection mode to discrete is when you'll start to see penetration.
  3. karliss_coldwild


    Oct 1, 2020
    Is there any script moving capsule collider? Since you mentioned player character I assume there is.

    Are you using position extrapolation ?
  4. ThaBullfrog


    Mar 14, 2013
    There was a script moving it, but I've reproduced the issue without it.

    I attached the repro project. I'm using version 2021.3.15f1.

    Hit play and the capsule should fall onto the cube printing some of the contact info to the console. For me it prints

    Code (csharp):
    2. impulse: (0.00, 29.04, 0.00)
    3. contacts[0].separation: -0.3852639
    Just realized physics settings won't carry over in the unity package. The issue still reproduces fine with default settings, but my game was using
    Gravity: (0, -23, 0)
    Default Max Depenetration Velocity: 500
    Fixed timestep: 0.01

    Attached Files:

  5. zulo3d


    Feb 18, 2023
    I didn't test your project but I did take another look at the issue and you're correct the penetration is much further than I had first thought. You can also test visually by freezing time with Time.timeScale=0 from within OnCollisionEnter.

    But good news! - I was able to prevent penetration by using Continuous Speculative for the collision detection mode.
  6. ThaBullfrog


    Mar 14, 2013
    Thanks, speculative does not suffer from this problem! Though it comes with some drawbacks. After some testing, I noticed the issue mentioned in the docs does show up in egregious ways in some scenarios in my game. The game is kind of about physics, so it's important for the physics to not behave in surprising ways.

    Based on the documentation, sweep-based detection should be better than speculative in my situation because my rigidbody never rotates. But I found the reason Continuous and Continuous Dynamic are not behaving the way I had expected. To improve performance, PhysX only uses sweeps in situations where it might be necessary to prevent tunneling. There's a parameter to change that behavior, but I don't think there's any way to set that parameter from Unity.

    It's kind of wild that there's not a good way to solve this problem in Unity given how bad the "allow penetrations but depenetrate over several steps" strategy looks at times. Would really appreciate if any staff seeing this would forward the feature request from @Luwyliscious in this thread to the proper channels. Or if there's a way for me to file the feature request myself let me know.

    But anyway, thanks @zulo3d for looking into this!
  7. halley


    Aug 26, 2013
    It's easy to get lost in the weeds with this kind of detail, but ask yourself if players will really notice it, given they see a character with legs and feet, and not a capsule?
  8. ThaBullfrog


    Mar 14, 2013
    I solved my problem, although it's not pretty. Would be much better for Unity to expose the PxSceneDesc::ccdThreshold parameter. But for posterity, I'll record my solution here.

    The short version is: after each physics step, I use OverlapCapsule to get the colliders the player is in contact with and Physics.ComputePenetration to push them out.

    Here's the code:

    Code (CSharp):
    1. public class Player : MonoBehaviour
    2. {
    3.     private const int MAX_COLLIDERS = 8;
    4.     private Collider[] collidersBuffer = new Collider[MAX_COLLIDERS];
    5.     private readonly WaitForFixedUpdate waitForFixedUpdate = new WaitForFixedUpdate();
    6.     private CapsuleCollider capsule;
    7.     private LayerMask ignorePlayerLayerMask;
    9.     public void Awake()
    10.     {
    11.         capsule = GetComponent<CapsuleCollider>();
    12.         ignorePlayerLayerMask = ~LayerMask.GetMask("Player");
    13.     }
    15.     public void OnEnable()
    16.     {
    17.         StartCoroutine(AfterPhysicsStep());
    18.     }
    20.     public IEnumerator AfterPhysicsStep()
    21.     {
    22.         while (enabled)
    23.         {
    24.             yield return waitForFixedUpdate;
    26.             Vector3 pointOffset = new Vector3(0f, capsule.height / 2f - capsule.radius, 0f);
    27.             int colliderCount = Physics.OverlapCapsuleNonAlloc(
    28.                 transform.TransformPoint( + pointOffset),
    29.                 transform.TransformPoint( - pointOffset),
    30.                 capsule.radius,
    31.                 collidersBuffer,
    32.                 ignorePlayerLayerMask
    33.             );
    34.             for (int i = 0; i < colliderCount; i++)
    35.             {
    36.                 if (Physics.ComputePenetration(
    37.                     capsule,
    38.                     transform.position,
    39.                     transform.rotation,
    40.                     collidersBuffer[i],
    41.                     collidersBuffer[i].transform.position,
    42.                     collidersBuffer[i].transform.rotation,
    43.                     out Vector3 direction,
    44.                     out float distance
    45.                 ))
    46.                 {
    47.                     transform.position += direction * distance;
    48.                 }
    49.             }
    50.         }
    51.     }
    52. }
  9. mischa2k


    Sep 4, 2015
    For the record, I am seeing this too.
    Capsule collider penetrates the ground by up to 70% of it's size, super strange.