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

2014/7/4

please help spwaning obstacle

kinobi kinobi

2014/7/4

#
basicly i want to spawn obstacles always when there are less than 5 in the world. there are two ways of disappearing shoot them or when they fly to the end of the map but i cant figure out how i need to set the code that i dont get this error: java.lang.NullPointerException at hinderniss.move(hinderniss.java:31) at hinderniss.act(hinderniss.java:15) this is the class: import greenfoot.*; public class hinderniss extends Actor { double hinderniss_SPEED = -3.0; public void act() { move(); turnrandom(); spawnhinderniss(); } public void move() { setLocation ( (int) (getX() + hinderniss_SPEED), getY() ); if (getX() <= 30) { getWorld().removeObject(this); hinderniss newHinderniss; newHinderniss = new hinderniss(); int x = Greenfoot.getRandomNumber(1250) +1325; int y = Greenfoot.getRandomNumber(600); getWorld().addObject(newHinderniss, x, y); } } public void turnrandom() { if (Greenfoot.getRandomNumber(100) < 10) { turn(Greenfoot.getRandomNumber(90) - 45); } } public void spawnhinderniss() { if(getWorld().getObjects(hinderniss.class).size()<5) { hinderniss newHinderniss; newHinderniss = new hinderniss(); int x = Greenfoot.getRandomNumber(1250) +1325; int y = Greenfoot.getRandomNumber(600); getWorld().addObject(newHinderniss, x, y); } } }
danpost danpost

2014/7/4

#
Spawning hinderniss objects has nothing to do with specific hinderniss objects already in the world. Therefore, the code to spawn hinderniss objects should go in your world class. In your move method, there is a chance that the hinderniss object is removed from the world. Once this line is executed, you cannot attempt to execute any methods on the object that required it being in the world ('getX', 'getY,' 'get...Intersecting...', 'isTouching', 'intersects', 'get...Objects...'); and because 'getWorld' will now return a 'null' value, you cannot attempt to run any methods on it.
kinobi kinobi

2014/7/4

#
so how would you solve this problem? because where else should be the removeobject be placed?
kinobi kinobi

2014/7/4

#
ok never mind i got it like this public class hinderniss extends Actor { double hinderniss_SPEED = -3.0; public void act() { move(); turnrandom(); spawnhinderniss(); despawnhinderniss(); } public void move() { setLocation ( (int) (getX() + hinderniss_SPEED), getY() ); } public void turnrandom() { if (Greenfoot.getRandomNumber(100) < 10) { turn(Greenfoot.getRandomNumber(90) - 45); } } public void spawnhinderniss() { if(getWorld().getObjects(hinderniss.class).size()<5) { hinderniss newHinderniss; newHinderniss = new hinderniss(); int x = Greenfoot.getRandomNumber(1250) +1325; int y = Greenfoot.getRandomNumber(600); getWorld().addObject(newHinderniss, x, y); } } public void despawnhinderniss() { if (getX() <= 30) { getWorld().removeObject(this); } } }
You need to login to post a reply.