2013-07-19 107 views
0

我已經理解爲了實現java圖像的流體運動,我必須設置booleans,然後從該狀態觸發動作。
我試圖在運行循環中設置它,但精靈不移動。我已經嘗試過把它翻譯過來,它會在每一種方法裏面進行,所以我不知道我做錯了什麼。java遊戲平滑運動

public void run(){ 
    while (running){ 
    go(); 
    repaint(); 
    System.out.println("The game runs"); 
    try { 
     Thread.sleep(1000/60); 
    } catch (InterruptedException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    } 
} 


//PAINT GRAPHICS 
public void paintComponent (Graphics g){ 
    super.paintComponent(g); 
    g.drawImage(bg, 0, 0, this); 
    g.drawImage(sprite, cordX, cordY, this); 


} 

//LOAD IMAGES 
public void load(){ 
      try { 
     String bgpath = "res/bg.png"; 
     bg = ImageIO.read(new File (sfondopath)); 
     String spritepath = "res/sprite.png"; 
     sprite = ImageIO.read(new File (spritespath)); 
    } catch (IOException e) { 

     e.printStackTrace(); 
    } 

} 


//MOVEMENT 
public void go(){ 
    cordX += vX; 
    cordX += vY; 

} 

public void gameupdate(){ 
    vX=0; 
    vY=0; 
    if (down) vY = speed; 
    if (up) vY = -speed; 
    if (left) vX = -speed; 
    if (right) vX = speed; 
} 



public void keyPressed(KeyEvent ke) { 
    switch (ke.getKeyCode()) { 
    //if the right arrow in keyboard is pressed... 
    case KeyEvent.VK_RIGHT: { 
     down = true; 
    } 
    break; 
    //if the left arrow in keyboard is pressed... 
    case KeyEvent.VK_LEFT: { 
     up = true; 
    } 
    break; 
    //if the down arrow in keyboard is pressed... 
    case KeyEvent.VK_DOWN: { 
     right = true; 
    } 
    break; 
    //if the up arrow in keyboard is pressed... 
    case KeyEvent.VK_UP: { 
     left = true; 
    } 
    break; 
} 
gameupdate(); 
} 




public void keyReleased(KeyEvent ke) { 

    switch (ke.getKeyCode()) { 
    //if the right arrow in keyboard is pressed... 
    case KeyEvent.VK_RIGHT: { 
     down = false; 
    } 
    break; 
    //if the left arrow in keyboard is pressed... 
    case KeyEvent.VK_LEFT: { 
     up = false; 
    } 
    break; 
    //if the down arrow in keyboard is pressed... 
    case KeyEvent.VK_DOWN: { 
     right = false; 
    } 
    break; 
    //if the up arrow in keyboard is pressed... 
    case KeyEvent.VK_UP: { 
     left = false; 
    } 
    break; 
} 
gameupdate(); 

} 
+2

看起來好像突破情況塊 – Reddy

回答

0

您正在用while循環阻塞事件調度線程。這讓搖擺沒有機會真正畫任何東西。改用Timer

對你來說會是大致爲:

ActionListener gameLoop = new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent evt) { 
     go(); 
     repaint(); 
     System.out.println("The game runs"); 
    } 
}; 

Timer timer = new Timer(1000/60, gameLoop); 

public void run() { 
    timer.start(); 
} 

您可以撥打timer.stop()這裏你通常未設置running