Search code examples
libgdxbox2draycasting

How to raycast with a given angle?


enter image description here

The green point is the Vector p1 while red point is the Vector p2. I could access the ray angle by using p2.sub(p1).angle() method.

Given:

float oberserverAngle = p2.cpy().sub(p1).angle();

RayCastCallback callback = new RayCastCallback() {

    @Override 
    public float reportRayFixture(Fixture fixture, Vector2 point, Vector2 normal, float fraction) {
    }        

}

world.rayCast(callback, p1, p2);

Now when I do this, the fov is not right, what am I missing?

shape.line(p1, p2)
Vector p3 = p2.cpy().setAngle(oberserverAngle * 0.5f);
Vector p4 = p2.cpy().setAngle(-oberserverAngle * 0.5f);
shape.line(p1, p3);
shape.line(p1, p4);

Solution

  • You are rotating a wrong vector. This should do it:

    Vector2 angleVec = p2.cpy().sub(p1);
    
    shape.line(p1, p2)
    Vector p3 = p1.add(angleVec.cpy().setAngle(oberserverAngle * 0.5f));
    Vector p4 = p1.add(angleVec.setAngle(-oberserverAngle * 0.5f));
    shape.line(p1, p3);
    shape.line(p1, p4);
    

    To achieve the result as shown in your Image you'd have to Stretch the rotated angleVec's