Advertisement
MrThoe

Ball Array #1

Feb 23rd, 2021
1,088
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var ball = [];  //Array of balls
  2.  
  3. function setup() {
  4.   createCanvas(400, 400);
  5. }
  6.  
  7. function draw() {
  8.   background(100);
  9.   for(var i = 0; i < ball.length; i++)
  10.   {
  11.     ball[i].show();
  12.     ball[i].move();
  13.   }
  14. }
  15.  
  16. //Called whenever the mouse button is pressed
  17. function mousePressed() {
  18.   var b = new Ball();  //Or var b = new Ball();
  19.   ball.push(b);
  20. }
  21.  
  22. /* Class Ball
  23.  
  24.  * VARIABLES:
  25.  * Postions (x and y)
  26.  * Velocity (Vx and Vy)
  27.  * Color control (r, g ,b)
  28.  *
  29.  * METHODS:
  30.  * constructor()
  31.  * show()
  32.  * bounce()
  33.  */
  34. class Ball
  35. {
  36.   constructor()
  37.   {
  38.     this.x = mouseX;
  39.     this.y = mouseY;
  40.     this.Vx = 0;
  41.     this.Vy = 5;
  42.     this.r = random(0,255); //Between 0 and 255
  43.     this.g = random(0, 255);
  44.     this.b = random(0, 255);
  45.   }
  46.  
  47.   show()
  48.   {
  49.     fill(this.r, this.g, this.b);
  50.     circle(this.x, this.y, 10);
  51.   }
  52.  
  53.   move()
  54.   {
  55.     this.bounce();
  56.     this.x += this.Vx;
  57.     this.y += this.Vy;
  58.   }
  59.  
  60.   bounce()
  61.   {
  62.     if(this.y > height || this.y < 0)
  63.     {
  64.       this.Vy *= -1;
  65.     }
  66.   }
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement