Search Unity

Question Calculating The Center Of A Capsule Collider's End Sphere

Discussion in 'Scripting' started by Payaso_Prince, Jan 16, 2022.

  1. Payaso_Prince

    Payaso_Prince

    Joined:
    Jul 17, 2017
    Posts:
    92
    Hello All!

    I'm trying to to get the center position of a Capsule Collider's(Player Controller) end sphere.

    I am able to calculate the bottom of the Capsule Collider fine. But when I add the radius to it, so that I can get the center of the End sphere, it is too low and incorrect.

    Code (CSharp):
    1. float capsuleBottom = (player.myController.center.y - (player.myController.height / 2));
    2.        
    3.        
    4.             Debug.DrawRay(new Vector3(player.transform.position.x + player.myController.center.x,(player.myController.transform.position.y + capsuleBottom) + player.myController.radius, player.transform.position.z + player.myController.center.z),Vector3.right, Color.blue);
    Anyone familiar with where I am going wrong? Any help would be greatly appreciated!
     
    Last edited: Jan 17, 2022
  2. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,999
    The CapsuleColliders center and height are defined in local space of the collider object. They are not worldspace positions. You manually add them together in the most convoluted and inefficient way possible. Apart from that the height of the capsule is the total height of the capsule. You don't need the radius at all. See the graphic in the documentation for reference.

    So to get the bottom point of your capsule you just have to do

    Code (CSharp):
    1. float halfHeight = player.myController.height*0.5f;
    2. var bottomPoint = player.transform.TransformPoint(player.myController.center - Vector3.up*halfHeight);
    3. Debug.DrawRay(bottomPoint, Vector3.right, Color.blue);
    4.  
    The only thing you should keep in mind, the actual height is at least twice the radius, even when you set the height to a smaller value. Because in that case you would get a sphere. So you may want to do

    Code (CSharp):
    1. float halfHeight = player.myController.height*0.5f;
    2. halfHeight = Mathf.Max(halfHeight, player.myController.radius);
    This ensures that halfHeight is at least as big as the radius.
     
  3. Payaso_Prince

    Payaso_Prince

    Joined:
    Jul 17, 2017
    Posts:
    92
    Hey, thanks for the response! I'm actually trying to get the center of the end sphere though. Not the bottom point of the capsule. I probably could have been a little more clear on that.
     
  4. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,999
    Well, in that case you just need to subtract the radius from halfHeight before you multiply it by Vector3.up.
     
    Payaso_Prince likes this.
  5. Payaso_Prince

    Payaso_Prince

    Joined:
    Jul 17, 2017
    Posts:
    92
    That worked! Thank you SO much Bunny83! :)