2014-04-22 53 views
0

我是斯坦福cs106a公共資源的新學習者。 當我閱讀講義BouncingBall時,我受到了困擾,下面是完整代碼 我從cs106a講義中獲得。斯坦福cs106a彈跳球代碼問題

的問題是,因爲這是這個頁面, 的底部​​3210方法的代碼爲什麼要球做的代碼ball.move(0, -2 * diff),尤其是 執行-2 * diff,我不明白這個數學代碼。 球做代碼ball.move(0, -diff)好嗎?有什麼不同? 什麼是反彈邏輯?這裏的任何人都可以幫助我理解這個 的代碼,我不擅長數學。非常感謝你

/* 
* File: BouncingBall.java 
*-------------------------- 
* This program graphically simulates a bouncing ball 
*/ 

import acm.program.*; 
import acm.graphics.*; 

public class BouncingBall extends GraphicsProgram { 

/** Size (diameter) of the ball */ 
private static final int DIAM_BALL = 30; 

/** Amount Y velocity is increased each cycle 
* as result of gravity 
*/ 
private static final double GRAVITY = 3; 

/** Animation delay or pause time between call moves */ 
private static final int DELAY = 50; 

/** Initial X and Y location of ball */ 
private static final double X_START = DIAM_BALL; 
private static final double Y_START = 100; 

/** X Velocity */ 
private static final double X_VEL = 5; 

/** Amount Y Velocity is reduced when it bounces */ 
private static final double BOUNCE_REDUCE = 0.9; 

/** Starting X and Y Velocities */ 
private doublexVel = X_VEL; 
private doubleyVel = 0.0; 

/* private instance variable */ 
private GOval ball; 

public void run() { 
    setup(); 

    // Simulation ends when ball goes off right hand 
    // end of screen 
    while (ball.getX() < getWidth()) { 
     moveBall(); 
     checkForCollision(); 
     pause(DELAY); 
    } 

} 

/** Create and place a ball */ 
private void setup() { 
    ball = new GOval (X_START, Y_START, DIAM_BALL, DIAM_BALL); 
    ball.setFilled(true); 
    add(ball); 
} 

/** Update and move ball */ 
private void moveBall() { 
    // increase yVelocity due to gravity 
    yVel += GRAVITY; 
    ball.move(xVel, yVel); 
} 

/** Determine if collision with floor, update velocities 
* and location as appropriate 
*/ 
private void checkForCollision() { 
    if (ball.getY() > getHeight() - DIAM_BALL) { 

     // change ball's Y velocity to now bounce upwards. 
     yVel = -yVel * BOUNCE_REDUCE; 

     // Assume bounce will move ball an amount above 
     // the floor equal to the amount it would have dropped 
     // below the floor 
     double diff = ball.getY() - (getHeight() - DIAM_BALL); 
     ball.move(0, -2 * diff); 
     } 
    }  
} 

回答

1

ball.move被稱爲時,球已經超出了它反彈的表面。因此-diff會將其移回表面,-2 * diff會使其反彈。

+1

只需做ball.move(0,-diff)就可以將球放回表面,因爲球會在pause()之後,moveBall()之後調用moveBall(),可以反彈球,對嗎? (如下)週期: while(ball.getX() user3559982

+0

我試圖給評論添加代碼,但它被搞亂了,沒有格式化,對不起,使用stakoverflow更新 – user3559982

+0

你可以把它看作是一種能量 - 如果你只是將球移回到表面,你會失去了球應該有的一些高度。而丟失的數量幾乎是隨機的,這取決於球在地表下行進的距離。 (的確,計算應該是'ball.move(0, - (1 + BOUNCE_REDUCE)* diff)',因爲反彈應該減少) – Chrisky