在iTunes U上发布的CS106A课程第10讲中,老师向班级展示了一个弹跳球项目。我稍微摆弄它,以便球从屏幕开始时以相同的y值返回,但由于某种原因,一旦球变得非常低,它就永远不会停止弹跳,有时反弹甚至比它更高。之前的反弹是没有意义的,因为它应该始终降低。这是代码:
import acm.program.*;
import acm.graphics.*;
public class bouncingBall extends GraphicsProgram {
int setupCount = 0;
/** 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 DELAY = 50;
/** Initial X and Y location of 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.95;
/** Starting X and Y Velocities */
private double xVel = X_VEL;
private double yVel = 0.0;
/* private instance variable */
private GOval ball;
public void run() {
while (true) {
setup();
// Simulation ends when ball goes off right hand
// end of screen
while (ball.getX() < getWidth()) {
moveBall();
checkForCollision();
pause(DELAY);
}
}
}
/** Create and place ball. */
private void setup() {
if(setupCount==0) {
ball = new GOval(X_START, Y_START, DIAM_BALL, DIAM_BALL);
ball.setFilled(true);
add(ball);
setupCount += 1;
}
else {
double tempY = ball.getY();
ball.setBounds(X_START, tempY, DIAM_BALL, DIAM_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 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);
}
}
}
注意:我对Java很新,所以请不要给我一个非常复杂的解释。谢谢!
答案 0 :(得分:0)
我认为这是由于checkCollisions()
下的两行 double diff = ball.getY() - (getHeight() - DIAM_BALL);
ball.move(0, -2 * diff);
当球非常接近地板时的圆角误差可能会导致这些线条使球跳跃。 尝试删除它们。
祝你好运!