-1
不知道如何做到這一點是殺了我。我現在有一個框架,它有一個斜向下向右移動的球,當它碰到框架的邊緣時,它需要彈跳。彈跳部分我可以自己制定出來,我需要幫助的是球知道什麼時候碰到框架的邊緣。爪哇:球與球碰撞
主營:
class ControlledBall extends JPanel {
private int x = 70;
private int y = 30;
private boolean yes = true;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLUE);
Ellipse2D.Double ball = new Ellipse2D.Double(x,y,50,50);
g2.draw(ball);
g2.fill(ball);
}
public void moveRight(int d) {x = x + d;}
public void moveDown(int d) {y = y + d;}
public void gogo() {yes = true;}
public void nono() {yes = false;}
public static void main(String[] args) {
JFrame frame = new Viewer();
frame.setSize(500, 500);
frame.setTitle("Bouncing Ball");
frame.setDefaultCloseOperation((JFrame.EXIT_ON_CLOSE));
frame.setVisible(true);
}
}
瀏覽器類:
public class Viewer extends JFrame {
JButton go = new JButton("GO");
JButton stop = new JButton("STOP");
JPanel buttons = new JPanel();
Timer timer;
ControlledBall cbPanel = new ControlledBall();
JPanel left = new JPanel();
JPanel right = new JPanel();
JPanel top = new JPanel();
class gogoListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
cbPanel.gogo();
timer.start();
}
}
class nonoListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
cbPanel.nono();
timer.stop();
}
}
class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
cbPanel.moveRight(5);
cbPanel.moveDown(5);
repaint();
}
}
public Viewer() {
buttons.add(go);
buttons.add(stop);
this.add(buttons, BorderLayout.SOUTH);
this.add(cbPanel, BorderLayout.CENTER);
this.add(right, BorderLayout.EAST);
this.add(top, BorderLayout.NORTH);
this.add(left, BorderLayout.WEST);
timer = new Timer(50, new TimerListener());
go.addActionListener(new gogoListener());
stop.addActionListener(new nonoListener());
timer.start();
cbPanel.setBorder(BorderFactory.createLineBorder(Color.black));
}
}
見[碰撞檢測用複雜的形狀](http://stackoverflow.com/q/14 574045/418556)爲一個工作示例。雖然可以肯定的是一個圓圈(球)和可顯示的區域(一個矩形)會讓它開放得比JRE在我的例子中執行的公式簡單得多。 –