当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Multiple Bouncing Balls

问题描述:

public class BouncingBalls

{

public static void main(String[] args)

{

double[] balls = new double [10];

double[] x = new double[1];

double[] y = new double[1];

double[] xspeed = new double[1];

double[] yspeed= new double[1];

for(int i = 0; i < 10; i++)

{

x[i] = 0.5;

y[i] = 0.5;

double r = 0.05;

xspeed[i] = Math.random() / (5 * 24);

yspeed[i] = Math.random() / (5 * 24);

while(true)

{

StdDraw.clear();

StdDraw.circle(x[i],y[i],r);

x[i] = x[i] + xspeed[i];

y[i] = y[i] + yspeed[i];

if (x[i] > 1 || x[i] < 0)

xspeed[i] = xspeed[i] * -1;

if (y[i] > 1 || y[i] < 0)

yspeed[i] = yspeed[i] * -1;

StdDraw.show(1000/ 24);

}

}

}

}

I need to print 10 bouncing balls onto the screen and i can not figure out what i am doing wrong that it wont print all 10.

I do not know how to use any of the import methods or any thing like that. so if someone could please help me that would be great!!!

网友答案:

Your draw loop is inside of your for loop. Generally in animation, your draw loop should be the outermost loop.

public class BouncingBalls
{
    public static void main(String[] args)
    {    
        int balls = 10;
        double[] x = new double[balls];
        double[] y = new double[balls];
        double[] xspeed = new double[balls];
        double[] yspeed= new double[balls];

        double r = 0.05;

        /* initialize balls */
        for(int i = 0; i < balls; i++)
        {
            x[i] = 0.5;
            y[i] = 0.5;

            xspeed[i] = Math.random() / (5 * 24);
            yspeed[i] = Math.random() / (5 * 24);
        }

        /* draw loop */
        while(true)
        {
            StdDraw.clear();
            for(int i = 0; i < balls; i++)
            {
                /* Draw and update a ball */
                StdDraw.circle(x[i],y[i],r);
                x[i] = x[i] + xspeed[i];
                y[i] = y[i] + yspeed[i];

                if (x[i] > 1 || x[i] < 0)
                    xspeed[i] = xspeed[i] * -1;

                if (y[i] > 1 || y[i] < 0)
                    yspeed[i] = yspeed[i] * -1;
            }          
            StdDraw.show(1000/ 24);
        }     
    }
}
网友答案:

You might start by changing you while(true) loop, which will never terminate.

分享给朋友:
您可能感兴趣的文章:
随机阅读: