2013-07-19 4 views
0

자바 이미지의 유체 움직임을 얻기 위해서는 booleans을 설정하고 그 상태에서 액션을 트리거해야한다는 것을 이해했습니다.
실행 루프에서 설정하려고했지만 스프라이트가 움직이지 않습니다. 나는 그것을 시험해 보았고 모든 방법 안에 들어가서 내가 뭘 잘못하고 있는지 모른다.자바 게임 부드러운 움직임

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 일반적으로 설정되지 않은 것입니다.

관련 문제