我是stanford cs106a公共资源的新学习者。 当我读到BouncingBall时,我被困了,下面是完整的代码 我从cs106a讲义。
问题是,对于本页底部的checkForCollision
方法代码,
为什么球应该执行代码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);
}
}
}
答案 0 :(得分:1)
当ball.move
被召唤时,球已经移动到它弹跳的表面之外。因此-diff
会将其移回水面,-2 * diff
会使其反弹。