Search code examples
javalibgdxbox2draycasting

Multiple Raycasting for line of sight


I'm trying to find my way around box2d and I am unsure about my approach to do line of sight detection using raycast callbacks.

 private RayCastCallback callback = new RayCastCallback() {
        @Override
        public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 Normal, float fraction) {
            collision.set(point);

            lineOfSight.addLast(fixture);

            if (fixture.getFilterData().categoryBits != BIT_PLAYER) {
                System.out.println("ray hit wall");
                return fraction;}
            else if (fixture.getFilterData().categoryBits == BIT_PLAYER) {
                System.out.println("player found");

                return fraction;
            }

            return 0;
        }

Above is my callback method which is called through :

       world.rayCast(callback, startp, endp);

The above line is in the update method and called continuously.

Now the problem is that I have multiple objects doing this raycast, so what happens is that fixtures are added into a queue on contact and there is some code in update method that checks if the first item in the queue is player. If it is a player, projectile is fired.

  if (lineOfSight.first().getFilterData().categoryBits == BIT_PLAYER) {
                   lineOfSight = new Queue<Fixture>();
                   createBullet();
               } else {
                   lineOfSight.clear();
               }

All of these seem a bit messy and is not fully working either because I have multiple bodies ray casting and using the callback method.

Is there a more efficient way of doing this or maybe somehow edit the reportRayFixtue method? I can't think of a way to edit the parameters:( Thank you for your time.


Solution

  • One thing you might want to consider (you might already know this) is that the reportRayFixture is not called in any order. So, even if the player was the first in the line of sight, it may not be the first fixture called to the method.

    To get the correct ordering, you can use fraction parameter to measure which one is the first occurring. The smaller the fraction the closer it is to the start point and vice versa. To get the first fixture you would keep track of the smallest fraction called to the callback. Hopefully this will solve your issues.