2014-06-13 3 views
0

키를 누르고있는 동안 읽히는 키와 읽은 상태 사이에 짧은 지연이 있음을 발견했습니다. 나는 이것이 무엇을 의미 하는가? 어떤 열쇠를 누르고 가까이서 관찰하십시오. 패턴은 다음과 같습니다 : h.....hhhhhhhhhhhhhhhhhhhhhh 여기서 .은 일시 정지를 나타냅니다. 입력 할 때 한 글자를 쓰는 것이 더 힘들어지기 때문에 괜찮습니다. '나는'.키를 누른 상태에서 누른 상태에서 키를 누르는 것 사이의 지연

하지만 게임을 만들고 싶다면 어떻게해야합니까? 내 말은, 우리는 그 연기가 싫어. 이것은 내 문제입니다. 그래서 지금, 내가 당신에게 내 코드를 보여주지 :

import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.event.KeyAdapter; 
import java.awt.event.KeyEvent; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class Tutorial3{ 
    static MyPanel panel; 
    public static void main(String[] agrs){ 
     createAndStartGui(); 
     new gameplay(); 
    } 
    static void createAndStartGui(){ 
     JFrame f = new JFrame("tutorial 3"); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.getContentPane().setPreferredSize(new Dimension(500, 300)); 
     f.addKeyListener(new MyKeyListener()); 

     panel = new MyPanel(); 
     f.add(panel); 

     f.pack(); 
     f.setVisible(true); 
    } 
} 

class gameplay { 
    static String current_key = "stop"; 

    public gameplay(){ 
     begin(); 
    } 

    void begin(){ 
     while (true){ 
      try { 
       Thread.sleep(100); 
      } catch (InterruptedException ex) { 
       Logger.getLogger(Tutorial3.class.getName()).log(Level.SEVERE, null, ex); 
      } 
      Tutorial3.panel.user.move(current_key); 
      Tutorial3.panel.repaint(); 
      System.out.println(current_key); 
      current_key = "stop"; 
     } 
    } 

    static void key_event(){ 

    } 


} 

class MyKeyListener extends KeyAdapter{ 
     public void keyPressed(KeyEvent e){ 
     int keyCode = e.getKeyCode(); 
     switch(keyCode){ 
      case KeyEvent.VK_UP: 
       gameplay.current_key = "up"; 
       break; 
      case KeyEvent.VK_DOWN: 
       gameplay.current_key = "down"; 
       break; 
      case KeyEvent.VK_LEFT: 
       gameplay.current_key = "left"; 
       break; 
      case KeyEvent.VK_RIGHT: 
       gameplay.current_key = "right"; 
       break; 
      default: 
       gameplay.current_key = "stop"; 
     } 
    } 

} 

class MyRectangle{ 
    int x; 
    int y; 
    public MyRectangle(int x, int y){ 
     this.x = x; 
     this.y = y; 
    } 
    void move(String direction){ 
     switch (direction){ 
      case "up": 
       this.y -= 10; 
       break; 
      case "down": 
       this.y += 10; 
       break; 
      case "left": 
       this.x -= 10; 
       break; 
      case "right": 
       this.x += 10; 
       break; 
      default: 
       break; 
     } 
    } 
} 

class MyPanel extends JPanel{ 
    MyRectangle user = new MyRectangle(10, 10); 
    public MyPanel(){ 

    } 
    public void paintComponent(Graphics g){ 
     super.paintComponent(g); 
     Graphics2D g2d = (Graphics2D) g; 
     g.drawRect(user.x, user.y, 10, 10); 
    } 

} 

코드는 기본적으로 JPanel의에 사각형을 만들고 (오른쪽 화살표 사각형을 오른쪽으로 10 픽셀 이동 것) 사용자의 입력에 따라 주위로 이동합니다. 경험을 망칠 지체가 있다는 것을 제외하고는 모든 것이 잘 작동합니다.

나는이 질문을 읽었습니다 : Ignoring delay when a key is held down?하지만 슬프게도 JavaScript에만 적용되는 것으로 보입니다. 어떤 도움이 필요합니까?

이 유형의 기존 질문에 대한 링크도 있습니다 (누락되었을 수 있음).

+0

[KeyEventDispatcher (http://stackoverflow.com/a/7940227/1048330) 사용 방법]이 유용 할 수 있습니다. – tenorsax

답변

1

당신이 지금하고있는 일은 각 100ms 후에 current_key을 "중지"로 설정하고 keyPressed을 수신하여 방향을 다시 지정하는 것입니다. 문제는 keyPressed이 얼마나 자주 해고당하는 지에 따라 제한됩니다.

방향을 누를 때 움직이기 시작하고 키를 놓으면 움직이지 않는 것이 좋습니다.

쉬운 방법은 메인 루프에서 줄을 제거하고 을 "중지"로 설정 한 MyKeyListenerkeyReleased 방법을 사용하는 것입니다.

이렇게하면 키를 누를 때마다 해제 될 때까지 계속 그 방향으로 이동합니다.

class gameplay { 
    static String current_key = "stop"; 

    public gameplay() { 
     begin(); 
    } 

    void begin() { 
     while (true) { 
      try { 
       Thread.sleep(100); 
      } catch (InterruptedException ex) { 
       Logger.getLogger(Tutorial3.class.getName()).log(Level.SEVERE, null, ex); 
      } 
      Tutorial3.panel.user.move(current_key); 
      Tutorial3.panel.repaint(); 
      System.out.println(current_key); 
//   current_key = "stop"; // only "stop" when the key is released 
     } 
    } 

    static void key_event() {} 
} 

class MyKeyListener extends KeyAdapter { 
    // set direction to "stop" when a key is released 
    @Override 
    public void keyReleased(KeyEvent e) { 
     gameplay.current_key = "stop"; 
    } 

    public void keyPressed(KeyEvent e) { 
     int keyCode = e.getKeyCode(); 
     switch (keyCode) { 
      case KeyEvent.VK_UP: 
       gameplay.current_key = "up"; 
       break; 
      case KeyEvent.VK_DOWN: 
       gameplay.current_key = "down"; 
       break; 
      case KeyEvent.VK_LEFT: 
       gameplay.current_key = "left"; 
       break; 
      case KeyEvent.VK_RIGHT: 
       gameplay.current_key = "right"; 
       break; 
      default: 
       gameplay.current_key = "stop"; 
     } 
    } 
} 
+0

완벽한! 이제 작동합니다. 나는 파이썬에 대해 같은 질문을 다시해야 할 수도있다. (언젠가는 미래에) : D –

관련 문제