amerkoleci / JoltPhysicsSharp

JoltPhysics C# bindings
MIT License
238 stars 34 forks source link

Access to Body.GetWorldSpaceSurfaceNormal #98

Closed captainkidd5 closed 3 weeks ago

captainkidd5 commented 3 weeks ago

I'm trying to get the normal of the hit of a raycast using NarrowPhaseQuery.CastRay. This spits out a RayCastResult which hands back a BodyID. In order to use the method referenced here I need to have the actual Body struct instead.

Would it be possible to gain access to GetWorldSpaceSurfaceNormal somehow? I'm also not sure how to get a Body reference from just any BodyID uint

amerkoleci commented 3 weeks ago

Version 2.9.11, here is how you can do the stuff you need:

` Vector3 start = Vector3.Zero; Vector3 direction = Vector3.Zero; Ray ray = new(start, direction);

    bool had_hit = System.NarrowPhaseQuery.CastRay(ray, out RayCastResult hit);

    // Fill in results
    var outPosition = ray.GetPointOnRay(hit.Fraction);
    //outFraction = hit.mFraction;
    //outID = hit.mBodyID;

    // Draw results
    if (had_hit)
    {
        System.BodyLockInterface.LockRead(hit.BodyID, out BodyLockRead bodyLock);
        if (bodyLock.Succeeded)
        {
            Body hit_body = bodyLock.Body;

            PhysicsMaterial? material2 = hit_body.GetShape().GetMaterial(hit.subShapeID2);

            // Draw normal
            var normal = hit_body.GetWorldSpaceSurfaceNormal(hit.subShapeID2, outPosition);
            //mDebugRenderer->DrawArrow(outPosition, outPosition + normal, color, 0.01f);
        }

        System.BodyLockInterface.UnlockRead(in bodyLock);
    }

`

captainkidd5 commented 3 weeks ago

Works like a charm, thank you!