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

2012/5/25

Trying to move a whole class up and down but only one image moves

fergo2012 fergo2012

2012/5/25

#
I'm creating a Space Invaders game for a school project and I'm having the issue that when the Aliens reach the worlds edge, only the Alien on the furthest side of the screen will automatically move down closer to the bottom of the world. Obviously, in true Space Invaders fashion, I want the entire class of Aliens to move down. Here's the code I'm currently using:
public void reachWorldEdge()
    {
        if (getX() >= 970)
        {            
            MOVEMENT_SPEED2 = -1;
            setLocation(getX(), getY() + 30);
        }

        if (getX() <= 50)
        {
            MOVEMENT_SPEED2 = 1;
            setLocation(getX(), getY() + 30);
        }
    }
Any help is much appreciated!
erdelf erdelf

2012/5/25

#
I know its a lot of work depending on how much aliens you have, but make for every alien an own variable in the world and make a method to move them all. In the alien method should be something like
    public void reachWorldEdge()  
        {  
            if (getX() >= 970)  
            {              
                MOVEMENT_SPEED2 = -1;  
                getWorld().moveDown();
            }  
      
            if (getX() <= 50)  
            {  
                MOVEMENT_SPEED2 = 1;  
                getWorld().moveDown();
            }  
        }  
danpost danpost

2012/5/25

#
Make 'MOVEMENT_SPEED2' a class variable by adding declaring the variable as 'static' (this way, instead of each Alien having a speed variable, the whole class will be using the same speed variable). Next, use this as your 'reachWorldEdge()' method:
public void reachWorldEdge()
{
    if ((getX() <= 50 && MOVEMENT_SPEED2 == -1) || (getX() >= 970 && MOVEMENT_SPEED2 == 1))
    {
        MOVEMENT_SPEED2 = -MOVEMENT_SPEED2;
        for (Object obj : getWorld().getObjects(Alien.class))
        {
            Actor alien = (Actor) obj;
            alien.setLocation(alien.getX(), alien.getY() + 30);
        }
    }
}
fergo2012 fergo2012

2012/5/26

#
Thank you very much, I used you code danpost and it's perfect!
You need to login to post a reply.