MrThoe

2 Balls and a paddle in P5

Sep 14th, 2020 (edited)
299
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. /* Bouncing Balls (plural)
  2. * @Author: Allen Thoe
  3. */
  4.  
  5. //DECLARE VARIABLES
  6. var x, y, Vx, Vy;
  7. var x2, y2, Vx2, Vy2;
  8. var ballW, ballH; //Height and width of ball
  9. var r, g, b, r2, g2, b2; //Colors for ball
  10.  
  11. function setup() {
  12. createCanvas(400, 400);
  13. ballH = 20;
  14. ballW = 20;
  15. x = 220;
  16. y = 50;
  17. r = 255;
  18. g = 255;
  19. b = 255;
  20. r2 = 255;
  21. g2 = 255;
  22. b2 = 255;
  23. x2 = 50;
  24. y2 = 10;
  25. Vx2 = random(5);
  26. Vy2 = random(2,5);
  27. Vx = random(5); //(between 0 and 5)
  28. Vy = random(2,5); //(start, stop)
  29.  
  30. }
  31.  
  32. function draw() {
  33. background(80);
  34. drawBalls();
  35. checkCollide(); //ABSTRACT FROM Function
  36. drawPaddle();
  37. }
  38.  
  39. function drawPaddle(){
  40. strokeWeight(4);
  41. fill(255);
  42. rect(mouseX - 50, height - 30, 100, 20, 4);
  43. strokeWeight(1);
  44. }
  45. function checkCollide(){
  46. //Collides with walls
  47. if(x > width || x < 0){
  48. Vx *= -1;
  49. r = random(255);
  50. g = random(255);
  51. b = random(255);
  52. } // || Means 'OR', && means 'AND'
  53. if(y > height || y < 0){
  54. Vy *= -1;
  55. r = random(255);
  56. g = random(255);
  57. b = random(255);
  58. }
  59. if(x2 > width || x2 < 0){
  60. Vx2 *= -1;
  61. r2 = random(255);
  62. g2 = random(255);
  63. b2 = random(255);
  64. } // || Means 'OR', && means 'AND'
  65. if(y2 > height || y2 < 0){
  66. Vy2 *= -1;
  67. r2 = random(255);
  68. g2 = random(255);
  69. b2 = random(255);
  70. }
  71. //Collide with each other
  72. if(abs(x - x2) < ballW && abs(y - y2) < ballH){
  73. Vx *= -1;
  74. Vy *= -1;
  75. Vx2 *= -1;
  76. Vy2 *= -1;
  77. }
  78.  
  79. }
  80.  
  81. function drawBalls(){
  82. fill(r,g,b);
  83. ellipse(x, y, ballW, ballH);
  84. fill(r2, g2, b2);
  85. ellipse(x2, y2, ballW, ballH);
  86. //UPDATE POSITION
  87. x += Vx;
  88. y += Vy;
  89. x2 += Vx2;
  90. y2 += Vy2;
  91. }
Advertisement
Add Comment
Please, Sign In to add comment