让球从墙上弹回来

时间:2017-03-21 23:33:26

标签: java swing collision-detection

对于一个学校项目,我需要从我创建的窗口的墙壁上弹出一个球,但无论我尝试什么,我似乎无法实现它并让它工作。代码如下,并提前感谢您。

import java.awt.Color;
import java.awt.Graphics;
import static java.nio.file.Files.move;


public class MainClass extends javax.swing.JFrame implements Runnable {
      Thread move = new Thread (this);
      int width;
      int height;
      int posX;
      int posY;

public void run(){
    try {
       while (true){
        posX = posX+1;
        posY = posY+1;
        repaint();
        move.sleep(100);
     }
    }
    catch(Exception ex){
      ex.printStackTrace();
    }
  }

    public void paint(Graphics g) {

        g.setColor(Color.BLACK);
        g.fillRect(0, 0, width, height);
        g.setColor(Color.WHITE);
        g.fillOval(posX, posY/ 2, 20, 20);
    }

    public MainClass() {
        initComponents();
        this.setResizable(false);
        width = getWidth();
        height = getHeight();
        posX = width - 150;
        posY = height - 150;
        move.start(); 
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        


    public static void main(String args[]) {

        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainClass().setVisible(true);
            }
        });
    }

2 个答案:

答案 0 :(得分:1)

您必须检测碰撞并将速度更改为其他方向。为了给你指示我改变了代码并继续朝同一方向发展。

int ballSpeedX = 1;
int ballSpeedY = 1;
int ballRadius = 20;

public void run() {
    try {
        while (true) {
            // Calculate the ball's new position
            posX += ballSpeedX;
            posY += ballSpeedY;
            if (posX < 0) {
                ballSpeedX = -ballSpeedX; // Reflect along normal
                posX = 0; // Re-position the ball at the edge
            } else if (posX + ballRadius > width) {
                ballSpeedX = -ballSpeedX;
                posX = width - ballRadius;
            }
            // May cross both x and y bounds
            if (posY < 0) {
                ballSpeedY = -ballSpeedY;
                posY = 0;
            } else if (posY + ballRadius > height) {
                ballSpeedY = -ballSpeedY;
                posY = height - ballRadius;
            }
            repaint();
            move.sleep(10);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

答案 1 :(得分:0)

我认为关键是要替换

posX = posX+1;

posX = posX + velocityX;

如果将velocityX设置为-1,则球向左移动。 如果将velocityX设置为1,则球向右移动。

当它撞到墙壁时,用

反转方向
velocityX *= -1;

...当然也为Y做同样的事。