我的重力類有一個問題,它應該改變y座標,直到它到達基地,無論何時用戶跳轉,但是當我反覆按下跳轉按鈕(W)時,它會出現錯誤,並且立方體繼續下降基礎。爪哇重力bug
主類:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
@SuppressWarnings("serial")
public class Frame extends JFrame implements Runnable{ //main class
static Panel panel;
static Frame frame;
//CONSTRUCTOR
Frame(){ //constructor
super("Game Frame");
setLayout(new GridLayout(1,1));
panel = new Panel();
add(panel);
} //constructor
public static void main (String args[]){ //main method
frame = new Frame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(true);
frame.setSize(500,300);
frame.setLocationRelativeTo(null);
Thread T1 = new Thread(frame);
T1.start();
} //main method
public void run(){ //run method
frame.addKeyListener(new KeyListener(){ //key listener method
@Override
public void keyPressed(KeyEvent arg0) { //key pressed
switch(arg0.getKeyChar()){
//A (LEFT)
case 'a':
panel.x -= 10;
panel.repaint();break;
//D (RIGHT)
case 'd':
panel.x += 10;
panel.repaint();break;
//W (UP)
case 'w':
panel.y -= 40;
panel.repaint();
Thread T1 = new Thread(new Gravity());
T1.start();
} //switch
} //key pressed method
@Override
public void keyReleased(KeyEvent arg0) {}
@Override
public void keyTyped(KeyEvent arg0) {}
}); //key listener method
} //run method
} //main class
面板類:
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
@SuppressWarnings("serial")
public class Panel extends JPanel{ //class
static BufferedImage bg;
static int x = 20;
static int y = 195;
//PAINT METHOD
public void paint(Graphics g){ //method
super.paint(g);
g.setColor(Color.ORANGE);
this.setBackground(Color.BLACK);
//IMPORTING IMAGES
try {
bg = ImageIO.read(getClass().getResourceAsStream("Background.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//DRAWING GAME
g.drawImage(bg, 0, 0,500,275,null);
g.fillRect(x, y, 50, 50);
} //method
} //class
重力類:
public class Gravity implements Runnable{ //class
@Override
public void run() { //run method
while(Frame.panel.y != 195){ //while loop
try {
Thread.sleep(100);
} catch (InterruptedException e) { //catch exception
// TODO Auto-generated catch block
e.printStackTrace();
} //catch exception
Frame.panel.y += 5;
Frame.panel.repaint();
} //while loop
} //run method
} //class
把它放在一個調試器中,或者寫出println語句來確定這是怎麼回事。這裏的人很樂意回答具體的問題,但不太樂意僅僅採取一組代碼併爲您進行調試。 – arcy
好的,謝謝阿西。我試着解決它很長時間,這就是爲什麼我試着在這裏發佈這個。有什麼辦法可以在java中使用跟蹤表格嗎?由於語法正常,它只是某種邏輯錯誤 –
您似乎也不顯示有趣的部分。 「重力」在哪裏使用?如果你真的不知道它們是如何工作的,我的建議是一起跳過'Thread's。創建模擬的最簡單方法就是對'paint','doPhysics','paint','doPhysics'等交錯。 – pingul