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

2012/10/4

Help

Stephon231 Stephon231

2012/10/4

#
i have a code that when the bomb comes in contact with another actor it blows up but the bomb doesn't go away the actor that it came in contact with did. the code i use to add the explosion is private void checkCollision() { Bomb a = (Bomb) getOneIntersectingObject(Bomb.class); if(a != null) { getWorld().addObject(new Explosion(), getX(), getY()); getWorld().removeObject(this); } }
Morran Morran

2012/10/4

#
Stephon231, your problem is you're removing "this" instead of "a". You should add this:
 getWorld().removeObject(a) 
Where "a" is the Bomb you already defined. Hope this helps!
Stephon231 Stephon231

2012/10/4

#
i have tried this but it keeps giving me an error message
davmac davmac

2012/10/4

#
Then you probably entered it incorrectly. If you posted your updated code, and said what error message you were getting and on what line, someone might help you.
Stephon231 Stephon231

2012/10/6

#
this is the modified code it is in the rock class,
public void act() 
    {
       checkCollision();
    }    
    
      /**
     * Check whether we are colliding with an asteroid.
     */
    private void checkCollision() 
    {
        Bomb a = (Bomb) getOneIntersectingObject(Bomb.class);
        if(a != null) {
            getWorld().addObject(new Explosion(), getX(), getY());
            getWorld().removeObject(this);
            getWorld().removeObject(a);
            
        }
    }
the error message is the terminal window it says: java.lang.NullPointerException at Rock.checkCollision(Rock.java:29) at Rock.act(Rock.java:17)
danpost danpost

2012/10/6

#
That is a common mistake for students. Line 14 removes 'this' from the world and line 15 tries to use getWorld() on (the understood) 'this'; but since it is no longer in the world, getWorld() return 'null' and you need a World object (not 'null') to remove an object from. Easy fix: switch lines 14 and 15. It is always best to have the line 'getWorld().removeObject(this);' the last line in the method, if possible. If it is inside a conditional block, you can use 'return;' immediately after it. If returning back to a method, and there is more code to execute there, you can use 'if (getWorld() == null) return;'. You have to decide what code should or should not execute after the object is removed from the world and place these program flow commands appropriately, if needed.
Stephon231 Stephon231

2012/10/6

#
thank you it works now
You need to login to post a reply.