Reputation: 15
I'm new to learning java and in my project, the program that I have created makes the ball move vertically. Can anyone please help me as to how can I make the ball move horizontally? The method actionPerfomed shows the directions in which my ball moves vertically.
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();
}
}
Upvotes: 1
Views: 1092
Reputation: 347194
The basic idea for moving horizontally is the same as moving vertically, just in a different axis.
Having said that, you could simplify the logic but making use of a simple delta
value, which describes the amount of change to applied to the specific axis.
For example...
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();
}
Now, personally, you shouldn't be relying on private final int B_WIDTH = 350, B_HEIGHT = 350;
as a components size may be different for any number of reasons.
Instead, you should be using getWidth
and getHeight
of the component, which will tell you the current size of the component.
You should also be overriding getPreferredSize
and passing back B_WIDTH
and B_HEIGHT
(in a Dimension
). This will provide a layout hint to the parent container which is more likely to result in your component been that actual size - but there's no guarantees
Upvotes: 1