This site requires JavaScript, please enable it in your browser!
Greenfoot back
coder04
coder04 wrote ...

2014/10/31

Please help me with this error

coder04 coder04

2014/10/31

#
This is the error java.lang.NullPointerException at Miniship.fire(Miniship.java:23) at Miniship.act(Miniship.java:10) at greenfoot.core.Simulation.actActor(Simulation.java:568) at greenfoot.core.Simulation.runOneLoop(Simulation.java:526) at greenfoot.core.Simulation.runContent(Simulation.java:215) at greenfoot.core.Simulation.run(Simulation.java:205) This is the class that needs to be fixed
import greenfoot.*; 
import greenfoot.Actor;

public class Miniship extends Actor
{
    private int timer = 0;
    public void act()
    {
        move(4);
        fire();
        reduceTime();
        randomTurn();
        turnAtEdge();
    }
  
  
       public void fire()
   {
        if (timer == 0)
        {
           Actor laser = getOneObjectAtOffset(0,0,Redlaser.class);
           int rot = getRotation();
            if (rot!=0) laser.setRotation(rot);
            timer = 60;
            Greenfoot.playSound("laser.wav");
       }
    }
    
       public void reduceTime()
    {
        if (timer > 0)
            timer--;
    }
    
    /**
     * With a 10% probability, turn a bit right or left.
     */
    public void randomTurn()
    {
        if ( Greenfoot.getRandomNumber(100) < 10 )
        {
            turn( Greenfoot.getRandomNumber(40)-20 );
        }        
    }
    
    /**
     * If we reach the edge of the world, turn a little bit.
     */
    public void turnAtEdge()
    {
        if (atWorldEdge())
        {
           turn(7);
        }
    }
    public boolean atWorldEdge()  
    {  
       if(getX() < 10 || getX() > getWorld().getWidth() - 10)  
            return true;  
        if(getY() < 10 || getY() > getWorld().getHeight() - 10)  
            return true;  
        else  
            return false;  
    }  
   
    
} 
Alwin_Gerrits Alwin_Gerrits

2014/10/31

#
Instead of using multiple return statements, make a variable which you set to either true or false. Then return that. That might just be the problem.
danpost danpost

2014/10/31

#
If you miniship is supposed to create a laser shot about once per second, then you need to create one; you will probably not 'find' one at the location of the miniship (see line 21).
coder04 coder04

2014/10/31

#
do u know how to add health to when a laser kills me it takes three hits
danpost danpost

2014/10/31

#
Give yourself a health value of 3 to start:
private int health = 3;
Create a method, called from the act method, called checkLaser to detect and remove Laser objects and, when detected, decrease health and check for death (health == 0).
You need to login to post a reply.