出于某种原因,当我的 Sprite 碰到左侧边缘时,它不会反弹。该程序运行得很好,但后来我更改了一些实际上根本不应该对其产生任何影响的内容,然后它就停止运行了。
//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();
}
}
最佳答案
第一个回答者是正确的,这不应该影响任何事情。尽管在本例中它并不真正相关,但在构造函数中初始化私有(private)实例变量而不是使用它们的声明是一种很好的形式。
private int speed;
private int dx;
private int dy;
public Sprite()
{
speed=6;
dx=speed;
dy=speed;
}
关于java - 这个错误出现在我的java程序中,似乎没有任何原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17602748/