0
votes

I am trying to make the sprite stop continuously moving. Right now, the code makes the sprite move in the direction indicated by the user through arrow keys without stopping. I want to press an arrow key and make the sprite move once (ex. 10 steps only) in that direction.

 public class Contents extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(100, this);
private Image man;
int x=0, y=0;

public Contents() {
    super.setDoubleBuffered(true);
    t.start();
    addKeyListener(this);
    setFocusable(true);
    setFocusTraversalKeysEnabled(false);
}

@Override
public void paintComponent (Graphics g) {
    super.paintComponent(g);
    super.setBackground(Color.white);
    ImageIcon ii = new ImageIcon("guy.png");
    man = ii.getImage();

    Graphics2D g2d = (Graphics2D)g;
    g2d.drawImage(man, x, y, this);
}

    double xv = 0;
    double yv = 0;

    public void move() {
        x += xv;
        y += yv;
    }
    public void up() {
        yv = -1;
        xv = 0;
    }
    public void down() {
        yv = 1;
        xv = 0;
    }
    public void left () {
        xv = -1;
        yv = 0;
    }
    public void right () {
    xv = 1;
    yv = 0;
    }
@Override
public void actionPerformed(ActionEvent e) {
    repaint();
    //Collision for left and right walls
    if (x==0) {
        xv = 1; 
    }
    else if (x==900-240) {
        xv = -1;
    }
    // Collision for top and bottom walls
    if (y==0) {
        yv = 1;
    }
    else if (y==600-320) {
        yv = -1;
    }
    move();
}
public void keyPressed(KeyEvent e) {
    int code = e.getKeyCode();
    if (code == KeyEvent.VK_UP) {
        up();
    }
    if (code == KeyEvent.VK_DOWN) {
        down();
    }
    if (code == KeyEvent.VK_LEFT) {
        left();
    }
    if (code == KeyEvent.VK_RIGHT) {
        right();
    }
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}

}

It works when I delete the boundaries under ActionEvent. The boundaries prevent the sprite from going off screen. But I want to keep the boundaries and control the sprite too.

1

1 Answers

0
votes

I figured it out. Under keyReleased, set xv=0. Then when you release the arrow key, the sprite will stop moving.