Legebatterie

p5js--bounceBalls2.0

Mar 27th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. //change te number of balls by changing "number"
  2. var number = 4;
  3.  
  4. var frac=1.01;
  5.  
  6.  
  7. frameRate = 60
  8. var balls = []
  9. var alp = 100;
  10.  
  11. class Bubble {
  12. constructor() {
  13. this.x = random(20,width-20)
  14. this.y = random(20,height-20)
  15. this.vx = random(-3, 3);
  16. this.vy = random(-3, 3);
  17. this.mass = random(5,80);
  18. }
  19. move() {
  20. this.x = this.x + this.vx
  21. this.y = this.y + this.vy
  22. }
  23.  
  24. bounce() {
  25. if (this.x > width - this.mass / 2 || this.x - this.mass / 2 < 0) {
  26. this.vx = this.vx * -1*frac;
  27. this.vx = this.vx * 1*frac;
  28. }
  29. if (this.y > height - this.mass / 2 || this.y - this.mass / 2 < 0) {
  30. this.vy = this.vy * -1
  31. this.vx = this.vx * 1
  32. }
  33. }
  34.  
  35. show() {
  36. var r = map(this.x, 0, width, 0, 255)
  37. var b = map(this.x, 0, width, 255, 0)
  38. var g = map(this.y, 0, height, 0, 255)
  39. //stroke(255);
  40. strokeWeight(1)
  41. fill(r, g, b, alp);
  42. ellipse(this.x, this.y, this.mass, this.mass);
  43. }
  44.  
  45. collide(him) {
  46.  
  47. for (this.i = 1; this.i <= number; this.i++) {
  48. if (this.i > him || this.i < him) {
  49. if(dist(balls[him].x,balls[him].y,balls[this.i].x,balls[this.i].y)<(balls[him].mass+balls[this.i].mass+2)/2){
  50.  
  51.  
  52.  
  53. this.aa = balls[him].vx;
  54. this.bb = balls[him].vy;
  55.  
  56. balls[him].vx = (balls[this.i].vx * balls[this.i].mass) / balls[him].mass;
  57. balls[him].vy = (balls[this.i].vy * balls[this.i].mass) / balls[him].mass;
  58.  
  59. balls[this.i].vx = (this.aa * balls[him].mass*frac) / balls[this.i].mass;
  60. balls[this.i].vy = (this.bb * balls[him].mass*frac) / balls[this.i].mass;
  61.  
  62. }
  63. }
  64. }
  65. }
  66. }
  67. function setup() {
  68. createCanvas(600, 400);
  69.  
  70.  
  71. for (var i = 1; i <= number; i++) {
  72. balls[i] = new Bubble();
  73. }
  74. }
  75.  
  76.  
  77. function draw() {
  78.  
  79. background(0, 0, 0);
  80. for (var i = 1; i <= number; i++) {
  81. balls[i].show()
  82. balls[i].move()
  83. balls[i].bounce()
  84. balls[i].collide(i)
  85.  
  86.  
  87. }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment