Search Unity

Getting capsule's position from CapsuleCast

Discussion in 'Physics' started by crysicle, Jun 2, 2019.

  1. crysicle

    crysicle

    Joined:
    Oct 24, 2018
    Posts:
    95
    Hello, i've come into some trouble trying to get the position of the capsule once it hits something via CapsuleCast as it only returns the HitInfo. Anyone know how to calculate such a thing? I've been trying to figure this out for hours, but have hit a brick wall. The only thing i've been able to do is create an extension method to convert Capsule Collider information relative to Transform into CapsuleCast point1, point2 and radius.
     
  2. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    3,296
    What are you trying to achieve?

    https://docs.unity3d.com/ScriptReference/Physics.CapsuleCast.html
    Code (CSharp):
    1. public static bool CapsuleCast(Vector3 point1, Vector3 point2, float radius, Vector3 direction, out RaycastHit hitInfo, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteractionqueryTriggerInteraction = QueryTriggerInteraction.UseGlobal);
    got the collision point that can be retrieved from the RaycastHit as hitInfo.point.

    If you need to compute where you should put your capsule if its colliding with something, this might be more useful:
    https://docs.unity3d.com/ScriptReference/Physics.ComputePenetration.html
     
    crysicle likes this.
  3. crysicle

    crysicle

    Joined:
    Oct 24, 2018
    Posts:
    95
    I'm looking for a below terrain check to teleport my units to be above terrain if they happen to fall through it. Unfortunately the Physics.ComputePenetration() doesn't apply in my case as my terrain will not be convex. I've already tried the easiest route, which is to use Raycasts for this, however, the physics engine then dislodges the capsule collider further leading to stuttery behaviour. The only route i can think of to avoid this 100% is to cast a Capsule Collider itself as CapsuleCast into the terrain from above and get the HitPoint from which i would calculate the capsule's position, which would then be traced to the unit's transform that i could offset by the right amount.
     
  4. crysicle

    crysicle

    Joined:
    Oct 24, 2018
    Posts:
    95
    Finally found an easy solution. RaycastHit.distance provides the exact distance that the Capsule travelled, which then can be easily transformed into a trasform position by adding direction * distance to the emission point.
     
    taoleaf and xVergilx like this.