Language:Processing. Using Processing, write a program that draws three circles
ID: 662402 • Letter: L
Question
Language:Processing.
Using Processing, write a program that draws three circles centred in the output window, each with a different random colour and size. Each of the circles will move in a random direction (both a horizontal and vertical component) until it hits one of the walls of the output window. Once a circle hits a wall it should just remain there. No part of any circle should leave the screen. Each circle should have a random direction and speed (in your program, direction and speed will be the same thing).
At any time in the program, if the key r or R is pressed, the program should reset with the balls in the centre (and with new random colours, sizes and speeds/directions). At any time in the program, when the mouse button is released (you will write the void mouseReleased() function) the direction of all the circles will reverse themselves. Circles that are stuck to a wall will remain stuck to the wall.
Explanation / Answer
public 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); // 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; if (Math.abs(ry + vy) > 1.0 - radius) vy = -vy; // update position rx = rx + vx; ry = ry + vy; // clear the background StdDraw.clear(StdDraw.GRAY); // draw ball on the screen StdDraw.setPenColor(StdDraw.BLACK); StdDraw.filledCircle(rx, ry, radius); // display and pause for 20 ms StdDraw.show(20); } } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.