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

2016/11/27

How do I get Alien to re spawn at the top of the screen?

dlamc dlamc

2016/11/27

#
public class Alien extends Actor
{
    /**
     * Act - do whatever the Alien wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    
    public void act() 
    {
      setLocation(getX(),getY()+(Greenfoot.getRandomNumber(10)-Greenfoot.getRandomNumber(8))); //This line of code is what controls the speed of the Alien as it moves down
      //It is also responsible for the random motion that occurrs as it moves down.
      onTheEdge();
    } 
    /**
     * This part is a test to see whether the alien is on the edge. 
     * If the Alien is on the edge, it is removed from the world. 
     * 
     */
    public void onTheEdge()
    {
        if (isAtEdge())
        {
            getWorld().removeObject(this);
            getWorld().addObject(new Alien(),(Greenfoot.getRandomNumber(791)+5),70);
        }
    }
}
Currently when I run the scenario, the alien reach the bottom of the screen disappear and the game stops. How can I get them to appear back at the top of the screen?
danpost danpost

2016/11/27

#
The reason the game stops is because line 24 calls a method on the world returned by 'getWorld', whose value is 'null'. It returns 'null' because the previous line removes the actor from the world. You could just switch the two lines (line 23 an 24), but better might be to just re-locate this Alien object at the top of the screen:
if (isAtEdge())
{
    setLocation(Greenfoot.getRandomNumber(791)+5, 70);
}
dlamc dlamc

2016/11/27

#
danpost wrote...
The reason the game stops is because line 24 calls a method on the world returned by 'getWorld', whose value is 'null'. It returns 'null' because the previous line removes the actor from the world. You could just switch the two lines (line 23 an 24), but better might be to just re-locate this Alien object at the top of the screen:
if (isAtEdge())
{
    setLocation(Greenfoot.getRandomNumber(791)+5, 70);
}
Something I should have mentioned before hand, is that when an alien touches the bottom of the screen two more have to spawn at the top of the screen then move down. How would I do something like that ?
danpost danpost

2016/11/27

#
dlamc wrote...
Something I should have mentioned before hand, is that when an alien touches the bottom of the screen two more have to spawn at the top of the screen then move down. How would I do something like that ?
I said you could just switch the two lines. That would be so you can add the new Alien object into the world before loosing the reference to the world, which happens when you remove the current Alien object from the world. Just add two new Alien objects into the world before removing 'this'.
You need to login to post a reply.