【问题标题】:How do I get this square to bounce off of the walls?我如何让这个正方形从墙上反弹?
【发布时间】:2014-02-19 06:29:46
【问题描述】:

所以我试图让这个方块从墙上反弹。我对编码很陌生,但我不明白为什么会这样。它的弹跳似乎很糟糕,因为它完全颠倒了它击中的方向,所以它的弹跳不符合逻辑。

不过,最令人沮丧的问题是它只反弹一次。它从侧面反弹一次,然后当它遇到第二面墙时,它就会飞入深渊。

这是一个用来编写它的sn-p代码:

void moveTheBox() {

    while (inside == true) {

        if ((bigBoxX <= 0) || (bigBoxY <= 0) || 
                (bigBoxX >= 600 - bigBoxSize) || 
                (bigBoxY >= 600 - bigBoxSize)) {

            bigBoxDeltaX = bigBoxDeltaX * -1;
            bigBoxDeltaY = bigBoxDeltaY * -1;

            while ((bigBoxX >= 0) || (bigBoxY >= 0) || 
                    (bigBoxX <= 600 - bigBoxSize) || 
                    (bigBoxY <= 600 - bigBoxSize)) {

                bigBoxX = bigBoxX + bigBoxDeltaX;
                bigBoxY = bigBoxY + bigBoxDeltaY;

                repaint();
                pause();
            }

        } else {

            bigBoxX = bigBoxX + bigBoxDeltaX;
            bigBoxY = bigBoxY + bigBoxDeltaY;

            repaint();
            pause();
        }
    }
}

编辑:我在您发布后 4 分钟才知道。我修复了尴尬的弹跳和 1 弹跳问题。

这是最终产品:

void moveTheBox() {

    int i = 0;
    while(i == 0){
    if ((bigBoxX <= 0) || (bigBoxX >= 600-bigBoxSize)){
        bigBoxDeltaX = bigBoxDeltaX * -1;



        while((bigBoxX >= 0) || (bigBoxY >=0) || (bigBoxX <= 600-bigBoxSize) || (bigBoxY <= 600 - bigBoxSize)){
            bigBoxX = bigBoxX + bigBoxDeltaX;
            bigBoxY = bigBoxY + bigBoxDeltaY;
            repaint();
            pause();
            break;
        }

        }else if ((bigBoxY <= 0) || (bigBoxY >= 600-bigBoxSize)){

            bigBoxDeltaY = bigBoxDeltaY * -1;
            while((bigBoxX >= 0) || (bigBoxY >=0) || (bigBoxX <= 600-bigBoxSize) || (bigBoxY <= 600 - bigBoxSize)){
                bigBoxX = bigBoxX + bigBoxDeltaX;
                bigBoxY = bigBoxY + bigBoxDeltaY;
                repaint();
                pause();
                break;
            }           
        }else{
            bigBoxX = bigBoxX + bigBoxDeltaX;
            bigBoxY = bigBoxY + bigBoxDeltaY;
            repaint();
            pause();


        }

    }
}

【问题讨论】:

    标签: java loops bounce


    【解决方案1】:
    import java.awt.*;
    import java.util.Formatter;
    import javax.swing.*;
    /**
     * One ball bouncing inside a rectangular box. 
     * All codes in one file. Poor design!
     */
    // Extends JPanel, so as to override the paintComponent() for custom rendering codes. 
    public class BouncingBallSimple extends JPanel {
       // Container box's width and height
       private static final int BOX_WIDTH = 640;
       private static final int BOX_HEIGHT = 480;
    
       // Ball's properties
       private float ballRadius = 200; // Ball's radius
       private float ballX = ballRadius + 50; // Ball's center (x, y)
       private float ballY = ballRadius + 20; 
       private float ballSpeedX = 3;   // Ball's speed for x and y
       private float ballSpeedY = 2;
    
       private static final int UPDATE_RATE = 30; // Number of refresh per second
    
       /** Constructor to create the UI components and init game objects. */
       public BouncingBallSimple() {
          this.setPreferredSize(new Dimension(BOX_WIDTH, BOX_HEIGHT));
    
          // Start the ball bouncing (in its own thread)
          Thread gameThread = new Thread() {
             public void run() {
                while (true) { // Execute one update step
                   // Calculate the ball's new position
                   ballX += ballSpeedX;
                   ballY += ballSpeedY;
                   // Check if the ball moves over the bounds
                   // If so, adjust the position and speed.
                   if (ballX - ballRadius < 0) {
                      ballSpeedX = -ballSpeedX; // Reflect along normal
                      ballX = ballRadius; // Re-position the ball at the edge
                   } else if (ballX + ballRadius > BOX_WIDTH) {
                      ballSpeedX = -ballSpeedX;
                      ballX = BOX_WIDTH - ballRadius;
                   }
                   // May cross both x and y bounds
                   if (ballY - ballRadius < 0) {
                      ballSpeedY = -ballSpeedY;
                      ballY = ballRadius;
                   } else if (ballY + ballRadius > BOX_HEIGHT) {
                      ballSpeedY = -ballSpeedY;
                      ballY = BOX_HEIGHT - ballRadius;
                   }
                   // Refresh the display
                   repaint(); // Callback paintComponent()
                   // Delay for timing control and give other threads a chance
                   try {
                      Thread.sleep(1000 / UPDATE_RATE);  // milliseconds
                   } catch (InterruptedException ex) { }
                }
             }
          };
          gameThread.start();  // Callback run()
       }
    
       /** Custom rendering codes for drawing the JPanel */
       @Override
       public void paintComponent(Graphics g) {
          super.paintComponent(g);    // Paint background
    
          // Draw the box
          g.setColor(Color.BLACK);
          g.fillRect(0, 0, BOX_WIDTH, BOX_HEIGHT);
    
          // Draw the ball
          g.setColor(Color.BLUE);
          g.fillOval((int) (ballX - ballRadius), (int) (ballY - ballRadius),
                (int)(2 * ballRadius), (int)(2 * ballRadius));
    
          // Display the ball's information
          g.setColor(Color.WHITE);
          g.setFont(new Font("Courier New", Font.PLAIN, 12));
          StringBuilder sb = new StringBuilder();
          Formatter formatter = new Formatter(sb);
          formatter.format("Ball @(%3.0f,%3.0f) Speed=(%2.0f,%2.0f)", ballX, ballY,
                ballSpeedX, ballSpeedY);
          g.drawString(sb.toString(), 20, 30);
       }
    
       /** main program (entry point) */
       public static void main(String[] args) {
          // Run GUI in the Event Dispatcher Thread (EDT) instead of main thread.
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                // Set up main window (using Swing's Jframe)
                JFrame frame = new JFrame("A Bouncing Ball");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setContentPane(new BouncingBallSimple());
                frame.pack();
                frame.setVisible(true);
             }
          });
       }
    }
    

    请参考tutorial

    【讨论】:

    • 我刚刚发现了如何解决尴尬的弹跳和只有 1 次弹跳的问题。
    • @user3326720 如果他的回答令人满意,请选择它作为您问题的答案
    • 所以你找到了答案..? @user3326720
    • 如果我的回答有帮助,您可以随时投票并标记为答案,以便其他有同样疑问的人可以看到答案是相关的。 stackoverflow.com/help/privileges/vote-upmeta.stackoverflow.com/help/someone-answers
    • 我愿意,但它说我需要 15 声望?
    猜你喜欢
    • 2019-07-01
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多