Question: Need to add c) to this java code. c) Randomily the ball will change direction and speed. Create a random number(using Math.random()) on the interval
Need to add c) to this java code.
c) Randomily the ball will change direction and speed. Create a random number(using Math.random()) on the interval 50-200 which decided the number steps left until the direction change. When that times come (when the steps are 0) then create random number for the values vx and vy which are on interval [-0.05, 0.05) for the velocity change.
import java.awt.event.KeyEvent;
class BouncingBall { 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) {
// 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; } if (StdDraw.isKeyPressed(KeyEvent.VK_UP)){ radius = radius + (radius*0.05); } else if(StdDraw.isKeyPressed(KeyEvent.VK_DOWN)) { radius = radius - (radius*0.05); } if (StdDraw.isKeyPressed(KeyEvent.VK_PAGE_UP)){ vx = vx + (vx*0.05); vy = vy + (vy*0.05); } else if(StdDraw.isKeyPressed(KeyEvent.VK_PAGE_DOWN)) { vx = vx - (vx*0.05); vy = vy - (vy*0.05); } // 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);
// copy offscreen buffer to onscreen StdDraw.show();
// pause for 20 ms StdDraw.pause(20);
} } }
http://introcs.cs.princeton.edu/java/stdlib/StdDraw.java.html
StdDraw can be downloaded here!
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
