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

2014/1/15

Moving from the left to right and then back?

GreenAnthony GreenAnthony

2014/1/15

#
Hi I am making this really classic space invasion game but I have problems with making the boss enemy move correctly. I want it to move from the left to the right and then back and so on, however the more I think about it the less possible it seems to me... So do you guys know how I could do this?
Gevater_Tod4711 Gevater_Tod4711

2014/1/15

#
I think the easiest way would be to use a counter that counts up every act and changes the direction of your boss enemy when it reaches a threshold value. You can try like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class BossEnemy extends Actor {
     
    private int movingCounter = 0;
     
    public void act() {
        if (movingCounter < 100) {
            setLocation(getX() + 5, getY());//move right;
        }
        else if (movingCounter < 200) {
            setLocation(getX() - 5, getY());//move left;
        }
        else {
            movingCounter = 0;
        }
        movingCounter++;
    }
}
danpost danpost

2014/1/15

#
I would use a direction field set to 1 for right, and whose alternate value is -1 for left:
1
2
3
4
5
6
7
8
9
10
11
public class BossEnemy extends Actor {
    private int direction = 1;
 
    public void act() {
        if ((direction < 0 && getX() < 20) || (direction > 0 && getX() > getWorld().getWidth()-20))
        {
            direction = -direction; // change direction
        }
        setLocation(getX()+5*direction, getY());
    }
}
In pseudo-code, this becomes 'if (edge moving toward is close) then changeDirection; move;' or 'if ((moving left and left edge is close) or (moving right and right edge is close)) then changeDirection; move;'
You need to login to post a reply.