libgdxraycastingclosestfixture

libgdx box2d raycast closest fixture


i'm using RayCastCallback interface ıf LibGDX. I couldn't find a way to get closest point from start of the ray. It returns random fixtures that hit by the ray. How can i get the closest collision point between ray and the fixture?


Solution

  • Sounds like you've got most of the code there, since you're getting fixtures back from your raycast. You'll just need to loop through all fixtures hit by the raycast and remember the closest one. Something like:

    public class SomeClass {
        
        private World world;
        private Vector2 fromPoint;
        private Vector2 toPoint;
        private Vector2 collisionPoint = new Vector2();
        float closestFraction = 1.0f;
        
        // ... rest of code ...
        
        private void calculateCollisionPoint() {
            RayCastCallback callback = new RayCastCallback() {
                
                @Override
                public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
                    if ( fraction < SomeClass.this.closestFraction ) {
                        SomeClass.this.closestFraction = fraction;
                        SomeClass.this.collisionPoint.set(point);
                    }
                    
                    return 1;
                }
            };
                
            world.rayCast(callback, fromPoint, toPoint);
        }
    }