0
Exception in thread "Thread-1" java.lang.NullPointerException
    at java.awt.Rectangle.intersects(Rectangle.java:786)
    at Robotron.intersecting(Robotron.java:182)
    at Robotron.run(Robotron.java:349)
    at java.lang.Thread.run(Thread.java:745)

The trouble is Here:

public void intersecting(Sprite r1, Sprite r2)
{
    System.out.println("The grunts isAlive is: "+r1.isAlive+" his xpos is: "+r1.rec.x+" his ypos is: "+r1.rec.y);
    if(r1.rec.intersects(r2.rec) && r1.isAlive==true && r2.isAlive==true)
    {
        r1.isAlive=false;
        r2.isAlive=false;
    }
}

The output of my System.out is: The grunts isAlive is: true his xpos is: 936 his ypos is: 478. But for some reason its giving me a null pointer

This is how I initialize my Grunts, Maybe the issue lies there?

for(int i=0; i<grunt.length;i++)
{
    int randX = (int)(Math.random()*worldx);
    int randY = (int)(Math.random()*worldy);
    if(hero.outerCircle.inCircle(randX,randY)!=true)
    {
        grunt[i] = new EnemyD4(randX,randY, worldx, worldy, 50,70);
    }
    if(hero.outerCircle.inCircle(randX,randY)==true)
    {
        randX+=100;
        grunt[i] = new EnemyD4(randX,randY, worldx, worldy, 50,70);
    }
}
Krypton
  • 3,337
  • 5
  • 32
  • 52
jaronoff97
  • 366
  • 3
  • 15

2 Answers2

3

In cases like this just follow the stacktrace! I am guessing from it that the null pointer is thrown here:

if(r1.rec.intersects(r2.rec) && r1.isAlive==true && r2.isAlive==true)

To be exact it's thrown here r1.rec.intersects(r2.rec) (which assumes that r1.rec and r2.rec aren't null).

If you check the code for Rectangle#intersects(Rectangle r) in the awt package you will see that on line 786 you have:

int rw = r.width;

And that's where the NPE occurs. r here is your r2.rec which means that it's null. You either need to check for this case before calling intersects() or you need to fix how you are calling intersecting(Sprite r1, Sprite r2).

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
Mateusz Dymczyk
  • 14,969
  • 10
  • 59
  • 94
0

I think your input to intersects is null. When you check your if condition, check r1 and r2 first:

if(r1.isAlive==true && r2.isAlive==true && r1.rec.intersects(r2.rec)) {
  ...
}
nmore
  • 2,474
  • 1
  • 14
  • 21