In this exercise, we explore the new concepts in our scenario. As we do, you will need to record all the stated questions and their answers in a text file using a text editor.

Specifications

Using a text editor, like TextPad, create a text file named questions.txt and copy the questions listed below into the file as you come to them. Also, record answers to all the questions in the file under the question.

Download the Newtons-Lab-2 scenario file, save it to a convenient location like the Desktop and unzip the file.

Method getOneIntersectingObject()

By saving the Target object in a reference variable, we have access to its methods

For example, we can call the actor's getX() and getY() methods

If we wrote a custom method, such as hit(), we can call the custom method as well

Thus, getOneIntersectingObject() provides more options than the easier isTouching() and removeTouching() methods

Note that getOneIntersectingObject() returns null if it is not touching another object

This means we need to check that the target is not null before calling methods of the target object

if (target != null)
{
// do something with target
}

When to Call checkHitTarget()

We want to call checkHitTarget() when the projectile is flying

However, if a cannonball is already removed from the world, then we cannot call checkHitTarget()

If we call checkHitTarget() when the cannonball is not in the world, we get a runtime error

java.lang.IllegalStateException: Actor not in world. An attempt was made to use the actor's location while it is not in the world. Either it has not yet been inserted, or it has been removed.

We want to call checkHitTarget() only if the cannonball was not removed from the world

We can ensure this condition by using an if-else statement as shown below

Method act() Calling checkHitTarget()

public void act()
{
addToVelocity(CannonWorld.GRAVITY);
move();
if (isTouching(Ground.class))
{
CannonWorld world = (CannonWorld) getWorld();
world.removeObject(this);
}
else // only if the cannonball is still in the world
{
checkHitTarget();
}
}