弹跳球,弹跳时不会碰到“墙”

时间:2019-12-17 20:06:31

标签: java stddraw

我试图通过随机改变弹子的弹跳速度来制作自己的弹跳球代码,但有时当它改变速度时,它会从那里弹跳而不会撞到墙壁,你们能告诉我哪里在我的代码中是错误的,我该如何解决。 谢谢大家。

import java.awt.event.KeyEvent;

public class Main {
    public static void main(String[] args) {
        // set the scale of the coordinate system

        StdDraw.setXscale(-1.0, 1.0);

        StdDraw.setYscale(-1.0, 1.0);

        StdDraw.enableDoubleBuffering();

        // initial values

        double rx = 0.480, ry = 0.860;     // position

        double vx = 0.015, vy = 0.023;     // velocity

        double radius = 0.05;              // radius

        // main animation loop

        while (true)  {


            int r = (int)(Math.random() * (200-50)+ 50);

            while(r >= 0) {

                System.out.println(r);

                r--;

                if(r == 0) {

                    double rr = Math.random() * (0.05-(-0.05))+(-0.05);

                    vy = rr;

                    vx = rr;

                }
                // bounce off wall according to law of elastic collision

                if(Math.abs(rx + vx) > 1.0 - radius){

                    vx = -vx;

                } else if(Math.abs(ry + vy) > 1.0 - radius){

                    vy = -vy;
                }

                // update position

                rx = rx + vx;

                ry = ry + vy;

                // clear the background
                StdDraw.clear(StdDraw.LIGHT_GRAY);

                // draw ball on the screen

                StdDraw.setPenColor(StdDraw.BLACK);

                StdDraw.filledCircle(rx, ry, radius);


                StdDraw.show();

                StdDraw.pause(20);}}}}

0 个答案:

没有答案