Timer doesn't execute functions within a method consecutively Java

DanB3195 :

I'm trying to implement a functionality within a game that I've made where if you press a button, the car will auto complete a lap of the track without any user input.

To do this, I've created functions for each direction of movement.

I needed to create a delay between each function call, otherwise it'll complete the lap the instant I press the button to initialise it. I've added the following:

    public void driveCar()
{
    Timer t = new Timer(1000 * 1, new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            move(MOVE_RIGHT);
            move(MOVE_DOWN);

        }
    });
    t.start();
}

If I only have the MOVE_RIGHT, it'll act as a loop and continuously run this method and move one space to the right every second however, I'm trying to make it so that it'll move one step to the right once, and then one step downwards. Currently, it's just moving diagonally every tick.

How can I implement a solution that carries out each call as if it's a list of instructions?

Andreas :

If you want the action of the timer to alternately move right or move down on each tick, you need a field tracking the progress:

Timer t = new Timer(1000 * 1, new ActionListener() {
    private boolean moveRight = true;
    public void actionPerformed(ActionEvent e) {
        if (moveRight)
            move(MOVE_RIGHT);
        else
            move(MOVE_DOWN);
        moveRight = ! moveRight;
    }
});

If you have more than two different actions, you can use a step counter:

Timer t = new Timer(1000 * 1, new ActionListener() {
    private int step = 0;
    public void actionPerformed(ActionEvent e) {
        switch (step) {
            case 0:
                move(MOVE_RIGHT);
                break;
            case 1:
                move(MOVE_DOWN);
                break;
            case 2:
                move(MOVE_UP);
                break;
        }
        step = (step + 1) % 3;
    }
});

UPDATE: If you want to walk a specific path, use an array:

final int[] path = { MOVE_RIGHT, MOVE_DOWN, MOVE_UP, MOVE_UP, MOVE_LEFT, MOVE_DOWN };
Timer t = new Timer(1000 * 1, new ActionListener() {
    private int step = 0;
    public void actionPerformed(ActionEvent e) {
        move(path[step]);
        step = (step + 1) % path.length;
    }
});

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=144602&siteId=1