Whilst trying to make a gamecharacter jump in java, I tried to use Thread.sleep() to make an image move up 5 pixels, then wait for eg 100 miliseconds, then move up 5 pixels again, etc.
Instead, when the image needs to make 5 steps up of 5 pixels each, and wait 100 miliseconds everytime, it waits 500 miliseconds and moves up 25 pixels.
I can't explain this behaviour and there doesn't seem to be an answer online. Note that my program doesn't contain threads. Here is my code:
ImageIcon poppetje1 = new ImageIcon("img/poppetje1.jpg");
JLabel poppetje2 = new JLabel(poppetje1);
...
public void jump() {
try {
poppetje2.setBounds(poppetje2.getX(), (poppetje2.getY()-5), poppetje1.getIconWidth(), poppetje1.getIconHeight());
Thread.sleep(100);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
...
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_W) {
for(int c = 0; c < 10; c++) {
jump();
repaint();
}
}
}
I hope this is enough of my code, if I should upload the complete code, please ask.
Thanks in advance for your time.
Does setBounds
include a redraw/render step? If not, blocking within keyPressed
is probably preventing the redraw from happening until the sleeps are all done and keyPressed
returns.
Maybe you get an exception in this line of code poppetje2.setBounds(poppetje2.getX(), (poppetje2.getY()-5), poppetje1.getIconWidth(), poppetje1.getIconHeight());
and it's jumping directly on the catch statement.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.