我是学习java的新手,在我的项目中,我创建的程序让球垂直移动。任何人都可以帮助我,我怎么能让球水平移动? 方法actionPerfomed显示我的球垂直移动的方向。
private final int B_WIDTH = 350, B_HEIGHT = 350;
private Image star;
private Timer timer;
private int x, y;
private boolean goingDown = true;
private AudioClip bounce =
Applet.newAudioClip(Board4.class.getResource("bounce.wav"));;
private AudioClip backgroundMusic =
Applet.newAudioClip(Board4.class.getResource("background.wav"));
public Board4() {
setBackground(Color.BLACK);
setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
setDoubleBuffered(true);
ImageIcon icon = new ImageIcon(Board4.class.getResource("ball.png"));
star = icon.getImage();
x = 150;
y = 0;
timer = new Timer(5, this);
timer.start();
backgroundMusic.loop();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(star, x, y, this);
Toolkit.getDefaultToolkit().sync();
}
@Override
public void actionPerformed(ActionEvent e) {
if (y < B_HEIGHT && goingDown == true) {
y += 2;
} else if (y >= B_HEIGHT) {
bounce.play();
goingDown = false;
}
if (!goingDown) {
y -=2;
}
if (y <= 0){
goingDown = true;
}
repaint();
}
}
答案 0 :(得分:1)
水平移动的基本思想与垂直移动相同,只是在不同的轴上。
话虽如此,您可以简化逻辑,但可以使用简单的delta
值,该值描述应用于特定轴的更改量。
例如......
private int xDelta = 2;
@Override
public void actionPerformed(ActionEvent e) {
x += xDelta;
if (x + star.getWidth(this) >= B_WIDTH) {
xDelta *= -1;
x = B_WIDTH - star.getWidth(this);
bounce.play();
} else if (xDelta <= 0) {
xDelta *= -1;
x = 0;
bounce.play();
}
if (y < B_HEIGHT && goingDown == true) {
y += 2;
} else if (y >= B_HEIGHT) {
bounce.play();
goingDown = false;
}
if (!goingDown) {
y -= 2;
}
if (y <= 0) {
goingDown = true;
}
repaint();
}
现在,就个人而言,您不应该依赖private final int B_WIDTH = 350, B_HEIGHT = 350;
,因为组件大小可能因各种原因而有所不同。
相反,您应该使用组件的getWidth
和getHeight
,它将告诉您当前组件的大小。
您还应该覆盖getPreferredSize
并传回B_WIDTH
和B_HEIGHT
(在Dimension
中)。这将为父容器提供布局提示,这更有可能导致您的组件达到实际大小 - 但是没有保证