I've tried giving Health to the alien in my game, but it constantly comes up with a java.lang.NullPointerException error.
If possible could you help me understand it to a level of understanding so I could avoid these types of problems later/be able to handle them myself.
Thanks.
Curtis E.
java.lang.NullPointerException
at Alien.HealthSystem(Alien.java:51)
at Alien.act(Alien.java:18)
at greenfoot.core.Simulation.actActor(Simulation.java:604)
at greenfoot.core.Simulation.runOneLoop(Simulation.java:562)
at greenfoot.core.Simulation.runContent(Simulation.java:221)
at greenfoot.core.Simulation.run(Simulation.java:211)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | public void act() //Alien.class { movement(); HealthSystem(); //First error happens here } private int health = 2 ; public void movement() { if (! getWorld().getObjects(Planet. class ).isEmpty()) { Actor planet = (Actor)getWorld().getObjects(Planet. class ).get( 0 ); int planetX = planet.getX(); int planetY = planet.getY(); turnTowards(planetX, planetY); move( 2 ); } if (isTouching(Alien. class )) { Teleport(); } } public void Teleport() { int cordsX = getX(); int cordsY = getY(); setLocation(cordsX, (cordsY - Greenfoot.getRandomNumber( 200 ))); } public void HealthSystem() { if (health == 0 ) { getWorld().removeObject( this ); MyWorld world = (MyWorld)getWorld(); world.getScore(); System.out.println( "This ran successfully" ); //Doesn't run as of yet world.increaseScore(); //Next happens here } if (getOneIntersectingObject(Bullet. class ) != null ) { int score; MyWorld world = (MyWorld)getWorld(); getWorld().removeObject(getOneIntersectingObject(Bullet. class )); health = health - 1 ; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public MyWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super ( 1500 , 1000 , 1 ); setUpWorld(); } public void setUpWorld() { addObject( new BackGround(), 750 , 500 ); addObject( new Planet(), 0 , 500 ); addObject( new Player(), 238 , 493 ); addObject( new Alien(), 1200 ,Greenfoot.getRandomNumber( 1000 )); addObject( new Alien(), 1200 ,Greenfoot.getRandomNumber( 1000 )); addObject( new Alien(), 1200 ,Greenfoot.getRandomNumber( 1000 )); } public int getScore() { return score; } public int level = 1 ; public void increaseScore() //Problem is supposedly here? { score++; showText( "Score" + score, 300 , 30 ); } |