|
// BOUNCE 1 // declaring global variables float x; float y; float vx; float vy; void setup() { size(200, 200); framerate(25); // initializing variables x = 30; y = 80; vx = 2.5; // the horizontal component of the velocity vy = 4.25; // the vertical component of the velocity } void loop() { background(127); drawShape(); // updating the position of the ball using velocity x = x + vx; y = y + vy; // the 2
following tests are keeping the ball within the boundaries of the screen if (x < 0 || x > width) { vx = -vx; // inverting the horizontal velocity //component of the ball whenever it reaches the left or //the right of the screen } if (y < 0 || y > height) { vy = -vy; // inverting the vertical velocity component //of the ball whenever it reaches the bottom or the top //of the screen } } void drawShape() { ellipseMode(CENTER_RADIUS); noStroke(); fill(255); ellipse(x, y, 4, 4); } |
// BOUNCE 1 – Object Oriented
Ball[] myBalls; // declaring a global variable //to hold an array of ball objects void setup() { size(200, 200); framerate(25); myBalls = new Ball[55];// creating an //object of type Ball for (int i = 0; i
< 55; i++) // iterating 55 //times { myBalls[i] = new Ball(); myBalls[i].x = random(0,200); myBalls[i].y = random(0,200); myBalls[i].vx =
random (0, 2.5); // the
horizontal component of the velocity myBalls[i].vy =
random (0, 4.25); // the vertical
component of the velocity } } void loop() { background(127); for (int i = 0; i<55;i++) {
myBalls[i].run();// invoking the object's //method named run } } class Ball // defining a custom class { //defining fields float x; float y; float vx; float vy; void run() { drawShape ();//
invoking a method for //drawing the ball // updating
the position of the ball using //velocity x = x + vx; y = y + vy; // the 2 following tests are keeping the ball within the boundaries of the screen if (x < 0 || x > width) { vx = -vx; // inverting the horizontal velocity component of the ball whenever it reaches the left or the right of the screen } if (y < 0 || y > height) { vy = -vy; // inverting the vertical velocity component of the ball whenever it reaches the bottom or the top of the screen } } void drawShape() { ellipseMode(CENTER_RADIUS); noStroke(); fill(255); ellipse(x, y, 4, 4); } } |