Java:与框架的球碰撞

时间:2014-04-22 03:50:25

标签: java swing jframe awt java-2d

不知道怎么做就是杀了我。我目前有一个带有球的框架,它向下和向右倾斜移动,当它与框架的边缘碰撞时,它需要反弹。弹跳部分我可以自己解决,我需要帮助的是球知道它何时撞到框架的边缘。

主:

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));
}

}

1 个答案:

答案 0 :(得分:2)

你需要一种决定球进入方向的delta,而不是叫moveRight / moveDown,你只需要让球根据这个delta来更新自己。< / p>

当调用(更新方法)时,它会将当前增量应用于x / y位置,并评估球是否超出可用范围,如果球有重新定位在边缘并且三角形翻转(乘以-1),这将改变增量的方向。

水平和垂直位置都需要增量;)

例如: