Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Bouncy Bubbles
- * based on code from Keith Peters.
- *
- * Multiple-object collision.
- */
- int numBalls = 1;//numarul de balls
- float spring = 0.05;//arc
- float gravity = 0.03;//coeficient la gravity
- float friction = -0.9;//coeficient de a se indeparta in parte opusa dupa ciocnire
- Ball[] balls = new Ball[numBalls];//creaza un array de obiecte de tip ball din numBalls
- void setup() {
- size(300, 300);//size la screen
- for (int i = 0; i < numBalls; i++) {//initializeaza mingile
- balls[i] = new Ball(random(width), random(height), random(30, 70), i, balls);//initialieaza obiectul in constructor
- }
- noStroke();//disable la stroke la balls
- fill(255, 210);//fill in interiorul la balls
- }
- void draw() {
- background(0);//background negru
- for (Ball ball : balls) {//for (datatype element : array)
- ball.collide();
- ball.move();
- ball.display();
- }
- }
- class Ball {
- float x, y;
- float diameter;
- float vx = 0;
- float vy = 0;
- int id;
- Ball[] others;
- Ball(float xin, float yin, float din, int idin, Ball[] oin) {
- x = xin;//coordonata x
- y = yin;//cordonata y
- diameter = din;//diametru
- id = idin;//id la balls
- others = oin;//obiect de tip balls
- }
- void collide() {
- for (int i = id + 1; i < numBalls; i++) {
- float dx = others[i].x - x;//distanta dintra obiecte pe coordonata x
- float dy = others[i].y - y;// distanta dintre obiecte pe coordonata y
- float distance = sqrt(dx*dx + dy*dy);//formula de calcul dinstanta dintre obiecte
- float minDist = others[i].diameter/2 + diameter/2;//mindist- distanta mininam de ciocnire dintre doua obiecte pentru a avea inteactiune
- if (distance < minDist) { //daca distanta minima de ciocnire dintre obiecte este mai mare decit distanta dintre obiecte
- float angle = atan2(dy, dx);//Calculates the angle (in radians) from a specified point to the coordinate origin as measured from the positive x-axis
- float targetX = x + cos(angle) * minDist;//punctul de ciocnire
- float targetY = y + sin(angle) * minDist;//punctul de ciocnire
- float ax = (targetX - others[i].x) * spring;//
- float ay = (targetY - others[i].y) * spring;
- vx -= ax;
- vy -= ay;
- others[i].vx += ax;
- others[i].vy += ay;
- }
- }
- }
- void move() {
- int dir=(int)random(0,4);
- if(dir==0)
- vy -= gravity;
- else if(dir==1)
- vy += gravity;
- else if(dir==2)
- vx+=gravity;
- else if(dir==3)
- vx-=gravity;
- x += vx;
- y += vy;
- if (x + diameter/2 > width) {
- x = width - diameter/2;
- vx *= friction;
- }
- else if (x - diameter/2 < 0) {
- x = diameter/2;
- vx *= friction;
- }
- if (y + diameter/2 > height) {
- y = height - diameter/2;
- vy *= friction;
- }
- else if (y - diameter/2 < 0) {
- y = diameter/2;
- vy *= friction;
- }
- }
- void display() {
- ellipse(x, y, diameter, diameter);//creaza cerc cu parametri
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement