Advertisement
Guest User

Untitled

a guest
Feb 16th, 2020
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. int numBalls = 12;
  2. float spring = 0.05;
  3. float gravity = 0.03;
  4. float friction = -0.9;
  5. Ball[] balls = new Ball[numBalls];
  6.  
  7. void setup() {
  8. size(1280, 720);
  9. for (int d = 0; d < drops.length; d++){
  10. drops[d] = new Drop();
  11. }
  12. for (int i = 0; i < numBalls; i++) {
  13. balls[i] = new Ball(random(width), random(height), random(30, 70), i, balls);
  14. }
  15. noStroke();
  16. fill(255, 204);
  17. }
  18.  
  19. void draw() {
  20. background(0);
  21. for (int d = 0; d < drops.length; d++){
  22. drops[d].fall();
  23. drops[d].show();
  24. }
  25. for (Ball ball : balls) {
  26. ball.collide();
  27. ball.move();
  28. ball.display();
  29. }
  30. }
  31.  
  32. class Ball {
  33.  
  34. float x, y;
  35. float diameter;
  36. float vx = 0;
  37. float vy = 0;
  38. int id;
  39. Ball[] others;
  40.  
  41. Ball(float xin, float yin, float din, int idin, Ball[] oin) {
  42. x = xin;
  43. y = yin;
  44. diameter = din;
  45. id = idin;
  46. others = oin;
  47. }
  48.  
  49. void collide() {
  50. for (int i = id + 1; i < numBalls; i++) {
  51. float dx = others[i].x - x;
  52. float dy = others[i].y - y;
  53. float distance = sqrt(dx*dx + dy*dy);
  54. float minDist = others[i].diameter/2 + diameter/2;
  55. if (distance < minDist) {
  56. float angle = atan2(dy, dx);
  57. float targetX = x + cos(angle) * minDist;
  58. float targetY = y + sin(angle) * minDist;
  59. float ax = (targetX - others[i].x) * spring;
  60. float ay = (targetY - others[i].y) * spring;
  61. vx -= ax;
  62. vy -= ay;
  63. others[i].vx += ax;
  64. others[i].vy += ay;
  65. }
  66. }
  67. }
  68.  
  69. void move() {
  70. vy += gravity;
  71. x += vx;
  72. y += vy;
  73. if (x + diameter/2 > width) {
  74. x = width - diameter/2;
  75. vx *= friction;
  76. }
  77. else if (x - diameter/2 < 0) {
  78. x = diameter/2;
  79. vx *= friction;
  80. }
  81. if (y + diameter/2 > height) {
  82. y = height - diameter/2;
  83. vy *= friction;
  84. }
  85. else if (y - diameter/2 < 0) {
  86. y = diameter/2;
  87. vy *= friction;
  88. }
  89. }
  90.  
  91. void display() {
  92. ellipse(x, y, diameter, diameter);
  93. }
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement