Get null pointer in my Thread

Hey guys! I am currently writing a Combat class to handle well you guessed it Combat in my game.

[java]
public class Combat implements Runnable {

public Combat(Game game) {
this.game = game;

    attackThread = new Thread(this);

    init();

    run = true;
    
}//end of Combat Constructor

/**
 * init method
 */
private void init() {
    random = new Random();
    randomHit = new Random();

    run = false;

    playerDamage = 0;
    enemyDamage = 0;

    attackThread.start();

}//end of init

@SuppressWarnings(“static-access”)
public void run() {
while (run) {

        handleAttack();

        try {
            attackThread.sleep(500);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

/**
 * handleAttack method
 */
private void handleAttack() {

if(game.getPlayerModel().getWorldTranslation().distance(game.getOgre().getWorldTranslation()) < 25) {
game.getPlayer().decrementHealth(random.nextInt(3));
}
}
[/java]

I get a nullpointer in handleAttack on the if statement. If i remove the if statement i take damage every 500 milliseconds which i want but i want in a certain distance to take damage however i get the null pointer.

You shouldn’t spawn a thread to handle a timer to do something every 500ms, especially not when you’re inexperienced in threading. Instead, use the update loop and make a timer:

float timer = 0;

[java]public void update(float tpf){
timer = timer +tpf;
if(timer>500){
//do stuff here
timer = 0;
}
}[/java]

To not handle every event in the simpleUpdate of SimpleApplication you could use Controls or AppStates to handle these things.

An aside: in all of my years of software development, I have not even once found the need to use:
@SuppressWarnings(“static-access”)

…probably better to fix the code instead of hiding the issue.

1 Like
@normen said: You shouldn't spawn a thread to handle a timer to do something every 500ms, especially not when you're inexperienced in threading. Instead, use the update loop and make a timer:

float timer = 0;

[java]public void update(float tpf){
timer = timer +tpf;
if(timer>500){
//do stuff here
timer = 0;
}
}[/java]

To not handle every event in the simpleUpdate of SimpleApplication you could use Controls or AppStates to handle these things.


Yeah i just extended control thanks