由於某種原因,當我的精靈擊中左邊時,它不會反彈。該程序運行完美,但後來我改變了一些對它完全沒有影響的東西,並停止了工作。這個錯誤出現在我的Java程序中,看起來沒有理由
//Sprite class
public class Sprite {
private String sprite = "sprite-adult.fw.png";
private int speed;
private int dx;
private int dy;
private int x;
private int y;
private Image image;
public Sprite() {
ImageIcon ii = new ImageIcon(getClass().getResource(sprite));
image = ii.getImage();
speed=6;
dx=speed;
dy=speed;
x = 40;
y = 60;
}
public void move() {
toggleRebound();
x += dx;
y += dy;
}
public void toggleRebound() {
if(x == 1366)
dx = negate(dx);
if(y == 768)
dy = negate(dy);
if(x == 0)
dx = negate(dx);
if(y == 0)
dy = negate(dy);
}
public int negate(int x) {
return x*-1;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return image;
}
}
//SType class
public class SType extends JFrame{
public SType() {
add(new Board());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(1366,768);
setLocationRelativeTo(null);
setTitle("S - Type");
setVisible(true);
setResizable(false);
}
public static void main(String[] args) {
new SType();
}
}
//Board class
public class Board extends JPanel implements ActionListener{
private Sprite sprite;
private Timer timer;
public Board() {
setFocusable(true);
setBackground(new Color(39,124,36));
setDoubleBuffered(true);
sprite = new Sprite();
timer = new Timer(5,this);
timer.start();
}
public void paint(Graphics g) {
super.paint(g);
Random rand = new Random(5398);
for(int x=0;x<1000;x++) {
g.setColor(new Color(22,98,19));
g.drawOval(rand.nextInt(1368), rand.nextInt(768), 1, 20);
}
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(sprite.getImage(),sprite.getX(),sprite.getY(),this);
Toolkit.getDefaultToolkit().sync();
}
public void actionPerformed(ActionEvent arg0) {
sprite.move();
repaint();
}
}
爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 –
當你說「它不反彈」,你能更清楚嗎?它只是坐在那裏嗎?代碼是否會拋出異常?它仍然反彈底部?或者是右邊還是頂部?它曾經嗎? – CPerkins
它穿過「牆」,好像什麼都沒有。 – alexdr3437