This only happens sometimes, but after a bullet hits an asteroid it creates Debris. That Debris later has a randomly generated decay and is destroyed after the decay timer is up as seen on line 27
My question to you is why does it only randomly choose to give a NullPointerException and how do I fix it?
Another question I have about the code is the turn / setRotation functions.
Whenever the debris is generated, it is given a random rotation and then turned towards it. For some reason it only ends up having 8 or so different rotations visible as shown here
And I am wondering if there is anyway I can make it have more possible outcomes. Or is this due to the object being so small? (2x2 pixels)
Edit: took out the code for generating sound as that was copied by mistake
import greenfoot.*;
import java.util.Random;
public class Debris extends Actor
{
World MyWorld = getWorld();
Random randomR = new Random();
private int speed = 0;
int decay;
public Debris()
{
int rotation = randomR.nextInt(360)+1;
decay = (int) ((Math.random() * 50));
speed = (int) (1+ Math.random() * 2);
setRotation(rotation);
}
public void act()
{
move(speed);
destroyAtEdge();
if (decay != 0)
{
decay--;
}
else
{
getWorld().removeObject(this);
}
}
public void destroyAtEdge()
{
int y = getY();
int x = getX();
World myWorld = getWorld();
if (y == 0 )
{
getWorld().removeObject(this);
}
else if ( x==0 )
{
getWorld().removeObject(this);
}
else if (y == myWorld.getHeight() - 1) // -1 because it would not find it otherwise
{
getWorld().removeObject(this);
}
else if ( x == myWorld.getWidth() - 1) // -1 because it would not find it otherwise
{
getWorld().removeObject(this);
}
}
}