简体   繁体   中英

“JUMP” in a java 2d game

I have this code and I wanted to initiate a jump in a java 2d game,the thing is that my object doesnt goes anywhere,it just stays there...i wanted my object to jump as i press the key and the programme to show me images moving up and down..i am trying to do this by simple repaint() method CODE::::

    public void actionPerformed(ActionEvent e) {
    if(hero.jump()==1){
    int jumpheight=40,j=0;
    while(j<jumpheight){
        hero.y--;             \\changing the y position (up)..
            try {
            Thread.sleep(100);
        } catch (InterruptedException e1) {}
        repaint(); 
        j++;
    }
    j=0;
    hero.jump1=0;
    while(j<jumpheight){
        hero.y++;               \\changing the y position (down)..
            try {
            Thread.sleep(100);
        } catch (InterruptedException e1) {}
        repaint(); 
        j++;
    }
    }
    else {
    hero.move();
    repaint();  
    }

You need to move the position change into another thread. The key processing and the redraw is now handled in the same thread in the code you have now. When you call repaint() a repaint is scheduled, but not performed until the event thread is "free" again, but since you have a loop (with sleep) it is never free and instead your repaint will happen after your loop is done (and your hero is back at the original position).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM