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

2018/5/1

Issue with space invaders enemy movement.

SPCWW SPCWW

2018/5/1

#
For some reason the top row of my enemies always gets offset by 10 pixels when it hits the right edge howerver its fine whilst hitting the left? World code to add enemies:
public void addEnemies()
    {
        int x1 = 170;
        for(int i=0;i<11;i++) {           
            addObject(new Enemy(), x1, 20);
            x1+=60;
        }
        int x2 = 170;
        for(int i=0;i<11;i++) {           
            addObject(new Enemy(), x2, 60);
            x2+=60;
        }
        int x3 = 170;
        for(int i=0;i<11;i++) {           
            addObject(new Enemy(), x3, 100);
            x3+=60;
        }
        int x4 = 170;
        for(int i=0;i<11;i++) {           
            addObject(new Enemy(), x4, 140);
            x4+=60;
        }
        int x5 = 170;
        for(int i=0;i<11;i++) {           
            addObject(new Enemy(), x5, 180);
            x5+=60;
        }
    }
Enemy code for movement:
public void move()
    {
        MyWorld world = (MyWorld)getWorld();
        steps++;
        if(steps==60)
        {
            setLocation(getX()+world.d, getY());
            steps=0;
        }
        if(getX()==960)
        {
            world.d = -10;
            setLocation(940, getY());
        }
        if(getX()==40)
        {
            world.d = 10;
            setLocation(60, getY());
        }
    }
danpost danpost

2018/5/2

#
You issue is probably due to the fact that you are having each Enemy object control its own movement. Therefore each one that hits an edge and causes a direction change does not know that another enemy may have already changed the direction. You really want to control the entire Enemy army as a whole when having them move. I have a Space Invaders Movement Demo which has the world control the movement of the army using invisible Row objects that group the ranks of the enemy army. There is a bit of communication that goes on between each enemy in a rank and the Row object which is passed onto the world object to assist in determining when to change directions. The world tells a Row object when to move its rank of enemies (I do not remember, but it probably passed the direction to move, also). The Row object tells each enemy in its rank to move. The enemies inform the row if it reached an edge (only one would be at an edge on any given move). The Row object tells the world whether any has hit an edge. The world moves on to the next row. After all rows have moved, if any enemy had hit an edge, the direction is changed. I add a timer field in the world to make it move more like the original game.
You need to login to post a reply.