【发布时间】:2016-10-19 12:33:11
【问题描述】:
如果条件ball.getY() > getHeight() - DIAM_BALL 为真,这意味着,如果我正确理解球正在接触屏幕底部并且接下来应该发生的事情是弹跳,或者只是球需要从底部弹回。
因此,弹跳的过程或动作需要球改变球的方向,所以现在yVel 有负号并且它(球)保持其先前速度的 90%。我不明白的是球实际上是如何向上移动的?如果我们查看moveBall() 方法,我可以看到由于ball.move(xVel, yVel) + while 循环中的pause(DELEY) 正在发生移动的效果。但是在checkForCollision() 方法中,代码在此代码行yVel = -yVel * BOUNCE_REDUCE 中定义了必要的Y 速度及其方向,我看不出yVel 是如何以及在哪里实现的??? 我不明白向上移动的效果!yVel 是一个实例变量,它在这个程序中的行为如何?
还有一件事,告诉我们球会反弹多远,即如何知道何时再次开始下落?
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 a result of gravity */
private static final double GRAVITY = 3;
/** AnimatIon delay or pause time between ball moves */
private static final int DELEY = 50;
/** Initial X and Y location of the ball */
private static final double X_START = DIAM_BALL / 2;
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 double xVel = X_VEL;
private double yVel = 0.00;
/* private instance variable */
private GOval ball;
public void run(){
setup(); // Simulation ends when ball goes of right-hand-end of screen //
while(ball.getX() < getWidth()){
moveBall();
checkForCollision();
pause(DELEY);
}
}
/** Creates and place 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 on each cycle
yVel += GRAVITY;
ball.move(xVel, yVel);
}
/** Determine if collision with floor, update velocities and location as appropriate. */
private void checkForCollision(){
// Determine if the ball has dropped below the floor
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);
}
}
}
【问题讨论】:
-
yVel不是局部变量,而是类变量。查看run方法之前定义的位置?private double yVel = 0.00; -
请分享一个GOval类的代码