Hello, I am trying to reference the Space world "time" int from the PointOrbs Actor class. I have attempted to use a getTime() function within the PointOrbs constructor, but am getting a null pointer exception once the program attempts to create a PointOrbs object. The objective is to set the speed of the orbs according to a fraction of time.
Here is the Space class:
Here is the PointOrbs class:
Here is the error:
java.lang.NullPointerException
at PointOrbs.<init>(PointOrbs.java:9)
at Space.act(Space.java:20)
at greenfoot.core.Simulation.actWorld(Simulation.java:573)
at greenfoot.core.Simulation.runOneLoop(Simulation.java:506)
at greenfoot.core.Simulation.runContent(Simulation.java:193)
at greenfoot.core.Simulation.run(Simulation.java:183)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | import greenfoot.*; public class Space extends World { private int time; public Space() { GreenfootImage background = getBackground(); background.setColor(Color.BLACK); background.fill(); prepare(); time = 0 ; } public void act() { countTime(); if (Greenfoot.getRandomNumber( 1000 ) < 2 ) { addObject( new PointOrbs(), Greenfoot.getRandomNumber( 460 ), - 60 ); } } public int getTime() { return time; } private void countTime() { if (lives != 0 ) { time++; } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import greenfoot.*; public class PointOrbs extends Actor { private int speed; public PointOrbs() { Space space = (Space)getWorld(); speed = 1 + (space.getTime()/ 100 ); } public void act() { setLocation(getX(), getY()+speed); turn( 1 ); if (getY() == 599 ) { Space space = (Space)getWorld(); space.removeObject( this ); } } } |