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

2015/7/16

java.util.List

tom.2013 tom.2013

2015/7/16

#
I want a spaceship to fly (player is only able to press up or down) until it hits a ball (which means game over) which is randomly spawned on the right side and you shortly have to dodge it afterwards. Because isTouching wasn't exact enough, I wanted to use java.util.List and found this style on the internet, which I tried to adjust to my programme: public void Find() { List <ball> actors = getObjectsInRange(80, ball.class); if(actors != null) { if(getImage() == current){image = getImage();}; setImage ("gameover.png");setLocation(400,200); if (Greenfoot.isKeyDown("up")) {setLocation (getX()+0,getY()+0);};if (Greenfoot.isKeyDown("up")) {setLocation(getX()+0,getY()+0);}; Greenfoot.stop(); } Now I have several questions: What does the null stand for? Why doesn't the Spaceship get destroyed? How can I do it, that if the centre of the Spaceship and the centre of a ball come together within the range of 80, that the spaceship gets destroyed? Pls help me, I don't know how to do it. P.S. I don't know much about programming, as you can probably see.
davmac davmac

2015/7/16

#
What does the null stand for?
null means "no object"
Why doesn't the Spaceship get destroyed?
Because you check if the return from getObjectsInRange() is null, but it will never be null - getObjectsInRange() does not return null, it always returns a list object. (The list object may represent an empty list).
How can I do it, that if the centre of the Spaceship and the centre of a ball come together within the range of 80, that the spaceship gets destroyed?
Using getObjectsInRange() is a good start, but you should not compare its return to null. You can use the List method "isEmpty" to check if the list is empty. You can invert that condition (check if it's not empty) using "!". Eg:
List <ball> actors = getObjectsInRange(80, ball.class);
if(! actors.isEmpty()) {
    // ...
}
Just a couple of other things: 1. Your 'ball' class should be called 'Ball'. It is convention in Java to begin class names with a capital letter. 2. When posting code please use 'code' tags:
You need to login to post a reply.