Checking for Collisions in Greenfoot

Download Report

Transcript Checking for Collisions in Greenfoot

Checking for Collisions
in
Greenfoot

Greenfoot provides a two important
methods that allow an object to
detect whether it is intersecting with
another object:
• atWorldEdge( )


This method returns a “true” value if an
object is at the edge of the world
This method is in the “Mover” class
• getOneIntersectingObject(CLASS)

This method returns the object that is being
intersected.


To make an object disappear if it is at the edge of
the world…
Type the following in the class’ act( ) method:
if (atWorldEdge() == true)
{
getWorld().removeObject(this);
}
-removeObject(this) will remove your object.
-atWorldEdge( ) will return a boolean value

To detect if an object is touching
another object you will use the
following method:
This will method will return the object that is being touched.
getOneIntersectingObject(CLASS);
This is class of the objects for which you are looking.

Here is an example of how you would
use that method:
public void act()
{
checkKeys();
checkCollision();
}
public void checkCollision()
{
Actor collided;
}
collided = getOneIntersectingObject(UFO.class);
if (collided != null)
{
//This will remove the object
getWorld().removeObject(collided);
}
“collided” is a variable of the type Actor.
It will store an Actor object.
This method says, “Am I
touching a UFO object?” If it
is, put that UFO object in the
variable “collided.”
public void checkCollision()
{
Actor collided;
}
collided = getOneIntersectingObject(UFO.class);
if (collided != null)
{
//This will remove the object
getWorld().removeObject(collided);
}
If “collided” has an object
in it, then do the following…
This method removes the “collided”
object from the world.