【问题标题】:Java: Ball Collision with FrameJava:与框架的球碰撞
【发布时间】:2014-06-06 06:21:13
【问题描述】:

不知道如何做到这一点让我很生气。我目前有一个带有球的框架,它沿对角线向下和向右移动,当它与框架的边缘碰撞时,它需要反弹。反弹部分我可以自己解决,我需要帮助的是球知道它何时撞击框架边缘。

主要:

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

}

【问题讨论】:

  • 请参阅Collision detection with complex shapes 以获取工作示例。虽然无可否认,一个圆(球)和可显示区域(一个矩形)将使其开放给一个比 JRE 在我的示例中执行的更简单的公式。

标签: java swing jframe awt java-2d


【解决方案1】:

您需要某种 delta 来确定球的移动方向,而不是调用 moveRight/moveDown,您只需要求球根据此 delta 进行自我更新。

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

水平和垂直位置都需要一个 delta ;)

例如:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-29
    相关资源
    最近更新 更多