Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Why does Ground Stick code make Capsule fall slower?

Discussion in 'Scripting' started by ynm11, Feb 3, 2022.

  1. ynm11

    ynm11

    Joined:
    Jul 6, 2021
    Posts:
    57
    I am using a function from one of Unity's provided standard controllers. The function is meant to help the Player stick to the terrain that they walk on regardless of how uneven it is.

    While it achieves that result, an unexpected side effect is that the player Capsule now falls toward the ground very slowly. What might be causing that?

    Video demonstration:
    With GroundStick code: https://i.imgur.com/MTcMdIN.gif
    Without GroundStick code: https://imgur.com/a/57kYru1

    Code (CSharp):
    1. private void GroundStick()
    2.     {
    3.         RaycastHit hitInfo;
    4.         if (Physics.SphereCast(transform.position, capsule.radius, Vector3.down, out hitInfo, ((capsule.height / 2f) - capsule.radius) + stickToGroundHelperDistance))
    5.         {
    6.             if (Mathf.Abs(Vector3.Angle(hitInfo.normal, Vector3.up)) < 85f)
    7.             {
    8.                 r.velocity = Vector3.ProjectOnPlane(r.velocity, hitInfo.normal);
    9.             }              
    10.         }
    11.     }
    I tried remedying the problem by making the code only run if player Capsule is not grounded, but that approach introduces many new gameplay problems.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,517
    Your problem is that line 8 assigns a "flat" on plane vector, wiping out whatever was in the Y component.

    To solve:

    - copy the velocity out of the RB to a temp var
    - in the temp set the X and Z from that project on plane result
    - do not adjust the Y
    - copy the velocity back into the RB

    ALTERNATELY: extract the Y, save it, copy it all over, then reset the Y... potatoe, potatoh
     
    ynm11 likes this.
  3. ynm11

    ynm11

    Joined:
    Jul 6, 2021
    Posts:
    57
    Thank you, that works!! And explanation makes sense.
     
    Kurt-Dekker likes this.