Code Clip - Remove an object on collision:

Actor gold = getOneIntersectingObject(Gold.class);
if(gold!=null)
{      World myWorld = getWorld();
     myWorld.removeObject(gold);
}

Demo Lesson - Remove object on collision:

First, download the demo lesson here:
Remove Object on Collision demo lesson

Instructions:

First, open the GoldBuggy code window by double-clicking on the GoldBuggy class on the right.

At the bottom of the act() method, remove the comment //Code clip: Remove Object on Collision goes here and paste or type in the code clip above.

Press the 'Close' button at the top of the code window.

Press the 'Compile' button at the lower right hand corner of the Greenfoot window.

Press the 'Run' button, and grab some gold!

How it works:

This demo contains two actors, the GoldBuggy and the Gold . The GoldBuggy moves with the arrow keys (see Code Clip 1: Move With Arrow Keys).

The first line in the code clip is:

Actor gold = getOneIntersectingObject(Gold.class);

The getOneIntersectingObject method tries to find one other object that intersects the object whose code includes it. If it finds one, it will be assigned to a variable called gold of the type Actor . If there is no intersecting Gold object, the gold variable will be null, or no value.

The next line is:

if(gold!=null)

This is a conditional that only runs when an intersecting gold object has in fact been detected -- that is, is not null . If the buggy is touching gold, the code inside the curly brackets ({}) below will run.

The code in the curly brackets is:

{
     World myWorld = getWorld();
     myWorld.removeObject(gold);
}

The first line runs the getWorld() method which gets the world the buggy is in. It assigns the world to the variable myWorld of the type World . This allows the buggy to run the methods available to the world.

The second line calls the removeObject() method, which removes an object from the world. The argument is the variable gold , which was assigned to the intersecting Gold actor by the getOneIntersectingObject() method.