Need help with Array intersection.
in
Programming Questions
•
1 year ago
Hey guys, i have made some balls from an array which are just bouncing around at the moment...I have tried to make them bounce when they intersect with each other, but i have no clue of how to do it. I can manage it when there are only two instances of the ballclass... so please can someone tell me how to make the balls from the same array bounce away from each other?!
Code:
- Ball[] ball;
- int totalBalls = 0;
- int lastMillis = 0;
- void setup() {
- size(400, 400);
- smooth();
- // Initialize balls
- ball = new Ball[100];
- }
- void draw() {
- background(255);
- //timer; display a new ball randomly
- if (millis()- lastMillis>random(1000, 3000))
- {
- ball[totalBalls] = new Ball();
- lastMillis = millis();
- //add one each time
- totalBalls ++;
- }
- //when all balls have been created, start over
- if (totalBalls >= ball.length)
- {
- totalBalls = 0;
- }
- //move and display
- for (int i = 0; i<totalBalls; i++ )
- {
- ball[i].movement();
- ball[i].display();
- }
- }
- class Ball {
- float r; // radius
- float x, y;
- float xspeed, yspeed;
- color c = color(100, 50);
- // Constructor
- Ball() {
- r = random(20, 50);
- x = random(width);
- y = random(height);
- xspeed = 5;
- yspeed = 5;
- }
- //movement
- void movement() {
- x += xspeed; // Increment x
- y += yspeed; // Increment y
- // Check horizontal edges
- if (x > width || x < 0) {
- xspeed *= - 1;
- }
- // Check vertical edges
- if (y > height || y < 0) {
- yspeed *= - 1;
- }
- }
- // //bounce function
- // void bounce()
- // {
- // xspeed = xspeed * -1;
- // yspeed = yspeed * -1;
- // }
- // Draw the ball
- void display() {
- stroke(0);
- fill(c);
- ellipse(x, y, r*2, r*2);
- }
- }
1