Alex W
Alex W

Reputation: 330

Java Slick2D Line Constructor throws NullPointerException

In Java Slick2D, I am attempting to make a line using a constructor that takes two float arrays, as detailed here: http://slick.ninjacave.com/javadoc/org/newdawn/slick/geom/Line.html

My code is the following:

float[] floatArray1 = { 10.0f, 155.0f };
float[] floatArray2 = { 20.0f, 165.0f };
Line line1 = new Line ( floatArray1, floatArray2 );

However, this third line (line 263 in my code) throws a NullPointerException:

java.lang.NullPointerException
    at org.newdawn.slick.geom.Line.set(Line.java:217)
    at org.newdawn.slick.geom.Line.set(Line.java:138)
    at org.newdawn.slick.geom.Line.<init>(Line.java:112)
    at view.play.Character.checkIntersectionMovementVector(Character.java:263) (my method)

Why is this happening?

Edit: It is worth noting that using its constructor that takes four float values instead of two float arrays of length two works, and throws no exception:

        Line line = new Line ( 10.0f, 155.0f, 20.0f, 165.0f );

Upvotes: 2

Views: 69

Answers (1)

elhefe
elhefe

Reputation: 3504

Looks like a bug in the Line class. The Line.set() method that is eventually called is this:

public void set(float sx, float sy, float ex, float ey) {
    super.pointsDirty = true;
    start.set(sx, sy);     // this is line 217
    end.set(ex, ey);
    float dx = (ex - sx);
    float dy = (ey - sy);
    vec.set(dx,dy);

    lenSquared = (dx * dx) + (dy * dy);
}

However, the start instance variable of the Line class isn't initialized in the constructor you call:

public Line(float[] start, float[] end) {
    super();

    set(start, end);  // line 112
}

You should report the bug to the Slick2d maintainers. As a workaround, you should be able to use the Vector2f input constructor:

public Line(Vector2f start, Vector2f end)

As the set() method used here does initialize start:

public void set(Vector2f start, Vector2f end) {
    super.pointsDirty = true;
    if (this.start == null) {
        this.start = new Vector2f();
    }
    this.start.set(start);

    if (this.end == null) {
        this.end = new Vector2f();
    }
    this.end.set(end);

    vec = new Vector2f(end);
    vec.sub(start);

    lenSquared = vec.lengthSquared();
}

The four float input constructor also works because it calls the Vector2f constructor above:

public Line(float x1, float y1, float x2, float y2) {
    this(new Vector2f(x1, y1), new Vector2f(x2, y2));
}

Upvotes: 2

Related Questions