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

2016/6/8

Turning Towards Object Help

CuddlySpartan CuddlySpartan

2016/6/8

#
So I have code for a tower to turn towards an octopus when the octopus is in the world, however, when the octopus isn't in the world at all the game crashes. How would I modify this code to make it so that when the octopus isn't in the world it won't crash? I'm sure it's something relatively simple but I can't figure it out. Thanks!
public void turnTowardsOctopus()
    {
        Octopus o = (Octopus)getObjectsInRange(700, Octopus.class).get(0);
        oX = o.getX();
        oY = o.getY();
        turnTowards(oX, oY);
        fire();
    }
SPower SPower

2016/6/8

#
The problem is that you're calling get(0) on a list that might be empty. You first need to check if the list is empty. To make things a little easier, import the List class at the top of your 'file':
import java.util.List;
Then, in turnTowardsOctopus, replace the contents with:
List list = getObjectsInRange(700, Octopus.class);
if (!list.isEmpty()) {
    Octopus o = (Octopus)list.get(0);
    // stuff
}
CuddlySpartan CuddlySpartan

2016/6/8

#
Thanks so much! You aren't danpost but you still helped. Thanks SPower :D :D :D :D
SPower SPower

2016/6/8

#
CuddlySpartan wrote...
You aren't danpost but you still helped.
Probably because of the difference in experience. He's been in computing much longer than I have (I mean, simply have a look at the age difference).
CuddlySpartan CuddlySpartan

2016/6/8

#
It's okay I was just joking with you :D I love you SPower <3
You need to login to post a reply.