Dale Sparrow
Dale Sparrow

Reputation: 121

Libgdx Box2d Raycast cannot cast multiple rays

I've tried to find an answer regarding this problem but it doesn't look like many people are using raycasting like I want to. I have multiple actors in my game that I want to cast a short ray from like a sonar sensor on a small robot purely for collision avoidance.

I run a loop through each of these actors and they each call their own raycaster from the World using private Vector2 variables to hold the interception points and normals. It works fine if there is just one actor, but it seems as if the raycaster function only has one instance and any previous calls on it gets overridden by the new call even if it was called by a different object using a new Raycaster() call. Therefore only the last actor in my list actually receives info from the ray it cast.

Previous problems people reported was only on a single ray, but trying to sort the order.

Here is the raycasting callback inside one of the actors:

 RayCastCallback callback = new RayCastCallback() {
        @Override
        public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction)
        {
            ColP = point;
            System.out.println("\nColpoint: "+ ColP.x+","+ColP.y+"with "+Type);
            SurfNormal = normal;
            dist = 1*fraction;
            return 1;
        }
    }; Parent.world.rayCast(callback,p1,p2);

If you guys have any advice on how to achieve this, or insight into how the raycaster works so I could figure out a way around it rewriting previous calls I'd greatly appreciate it.

Upvotes: 1

Views: 401

Answers (1)

Dale Sparrow
Dale Sparrow

Reputation: 121

Okay I figured it out. I'm new to stack exchange so if the convention is to edit my question to contain the answer just let me know. The problem was that even though each object had its own vectors, I made a noob error and forgot that only java primitives aren't given by reference. The solution was to call new Vector2(point) and new Vector2(normal) so that all the vectors aren't merged into one inside the raycallback function.

RayCastCallback callback = new RayCastCallback() {
    @Override
    public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction)
    {
        ColP = new Vector2(point);
        System.out.println("\nColpoint: "+ ColP.x+","+ColP.y+"with "+Type);
        SurfNormal = new Vector2(normal);
        dist = 1*fraction;
        return 1;
    }
}; Parent.world.rayCast(callback,p1,p2);

Upvotes: 1

Related Questions