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

2016/2/12

NullPointerException Help!

Chandler.S Chandler.S

2016/2/12

#
I keep getting an error when trying to deduct lives from the pirate2 when it is hit with the bullet. Only happens when I have the myWorld.removeObject(this); this is the code in the bullet class to see when the bullet hits the pirate 2 and trys to run the pirate 2 lives function.
Actor Pirate2 = getOneObjectAtOffset(0, 0, Pirate2.class); //checking if the bullet has hit the pirate 2
                
         if (Pirate2 != null)
        {
            MyWorld myWorld = (MyWorld) getWorld();
            getWorld().removeObject(this);
            myWorld.Pirate2Lives(); //Calls in world to remove lives from pirate 2
            myWorld.score2(); //adds 2 points to score board
            return;
        }
This is the code in the world linking the bullet to the pirate function.
public void Pirate2Lives()
    {
        pirate2.Pirate2LivesLost();
    }
And here's the pirate2 code where the function to deduct the lives is.
private int Pirate2Lives;
    
    public Pirate2()
    {
        Pirate2Lives = 2;
    }
    
    public Pirate2(int direction)
    {
        setRotation(direction);
    }
    
    public void Pirate2LivesLost() //here is the code where the nullpointexception error is
    {
        Pirate2Lives--;
        Pirate2Dead();
    }
    
    
    
    public void Pirate2Dead()
    {
        if (Pirate2Lives <= 0) //if the lives equal zero then delete the object and run the score2 function
        {
            MyWorld myWorld = (MyWorld) getWorld();
            myWorld.addObject(new Explosion(), getX(), getY());
            myWorld.removeObject(this);
            myWorld.score2();
            return;
        }
    }
    
    public void act() 
    {
        move(4);
        

        if (atWorldEdge())
        {
            turn(10);
        }

        if (Greenfoot.getRandomNumber(100) <10 )
        {
            turn( Greenfoot.getRandomNumber(40)-20 );
        }

        if (canSee(Ship.class))
        {
            World world = getWorld();
            MyWorld myWorld = (MyWorld) world;
            eat(Ship.class);
            int x = Greenfoot.getRandomNumber(world.getWidth());
            int y = Greenfoot.getRandomNumber(world.getHeight());
            getWorld().addObject(new Ship(), x, y);
            myWorld.lives();
        }
    } 
danpost danpost

2016/2/12

#
It would be easier to have the Pirate2 object check for an intersecting bullet, remove the bullet and adjust its own lives.
You need to login to post a reply.