Hi guys I have a problem with the following code, and I am not sure how to fix itDoes anyone know how to fix this? The error I get is :
java.lang.NullPointerException
at Key.die(Key.java:55)
at Key.act(Key.java:16)
at greenfoot.core.Simulation.actActor(Simulation.java:565)
at greenfoot.core.Simulation.runOneLoop(Simulation.java:523)
at greenfoot.core.Simulation.runContent(Simulation.java:213)
at greenfoot.core.Simulation.run(Simulation.java:203)
import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot)
public class Key extends Actor
{
private int wait = 0;
private final int waitTime = 35;
private boolean touchingPlayer = false;
/**
* Create a new key.
*/
public void act()
{
movementAi();
die();
hitPlayer();
checkTouchingStatus();
}
private void checkTouchingStatus()
{
if (wait > 0) wait--;
if (wait == 0) touchingPlayer = false;
}
//movement
public void movementAi()
{
move(2);
if(Greenfoot.getRandomNumber(100) < 10)
{
turn(Greenfoot.getRandomNumber(90));
}
if (getX() <= 5 || getX() >= getWorld().getWidth() - 5)
{
turn(180);
}
if (getY() <= 5 || getY() >= getWorld().getHeight() - 5)
{
turn(180);
}
}
//If health is 0
public void die()
{
if (getHealth() == 0)
{
menu menuWorld = (menu) getWorld();
Bar scoreBar = menuWorld.getScoreBarValue();
scoreBar.add(50);
getWorld().removeObject(this);
}
}
//Enemy health
private int health = 3;//or any other starting value;
public void setHealth(int points) {
health += points;
}
public int getHealth() {
return health;
}
public void hitPlayer() {
key2 key2 = (key2) getOneObjectAtOffset(0, 0, key2.class);
if (key2 != null && !touchingPlayer) {
menu menuWorld = (menu) getWorld(); //Do this every time to call method!!!
Bar healthBar = menuWorld.getHealthBarValue();
healthBar.subtract(1);//decrements the health of your player
touchingPlayer = true;
wait += waitTime;
}
}
}
