如果条件ball.getY() > getHeight() - DIAM_BALL为true,则意味着,如果我正确理解球正在触摸屏幕的底部,并且接下来应该发生的事情是弹跳,或者只是球需要从底部弹起。

因此,弹跳的过程或动作需要球改变球的方向,因此现在yVel具有负号,并且它(球)保持其先前速度的90%。我不明白球实际上是如何向上移动的?如果我们看一下moveBall()方法,我可以看到由于while循环中的ball.move(xVel, yVel) + 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,仅现在重要。另外,您还有一个GRAVITYBOUNCE_REDUCE

一旦您的球开始下落,您将其位置增加GRAVITY
(添加重力使其下降,因为0,0是左上角)

yVel += GRAVITY;
ball.move(xVel, yVel);


一旦撞到地面,yVel = -yVel将改变其方向
将其减小一点,以使球不会弹回其原始位置,您可以乘以0.9来减小yVel。

向上行驶时(仅使用先前速度的90%),您正在向其添加GRAVITY(其为负速度),因此它会减速并在到达0 vel时停止并再次开始下降。

一个简单的例子:

以10个单位的高度将球以3 GRAVITY的高度落下,它将以30的速度以-27的速度(yVel = -yVel * BOUNCE_REDUCE;)弹回地面;并在每次迭代中添加3 GRAVITY,它将达到9个单位高度。

我希望它足够详细。

09-11 23:28