We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpPrograms › Collisions within a circle
Page Index Toggle Pages: 1
Collisions within a circle (Read 229 times)
Collisions within a circle
Jan 7th, 2009, 8:29pm
 
I'm trying to have small circles move around inside a larger circle but when they hit the inside of the circle I want the small circle to bounce off. How would I implement this?

Here's some of my code, I just cannot figure out the collisions.
Code:

Circle[] buzz = new Circle[20];
float x;
float y;
boolean change;

void setup()
{
 size(450, 450);
 smooth();
 x = width/2;
 y = height/2;
 change = false;
 for (int i = 0; i < buzz.length; i++)
 {
   buzz[i] = new Circle();
 }
}

void draw()
{
 background(255);
 for (int i = 0; i < buzz.length; i++)
 {
   buzz[i].display();
 }
 if (!mousePressed)
 {
   noStroke();
   fill(140, 200);
   ellipse(x, y, 100, 100);
 }
 else
 {
   stroke(140);
   strokeWeight(10);
   noFill();
   ellipse(x, y, 90, 90);
   for (int i = 0; i < buzz.length; i++)
   {
       buzz[i].x -= (buzz[i].x - x)/12;
       buzz[i].y -= (buzz[i].y - y)/12;
   }
 }
 
 x -= (x - mouseX)/8;
 y -= (y - mouseY)/8;
}

class Circle
{
 float x;
 float y;
 float xdir;
 float ydir;
 float dx; // speed
 float dy; // speed
 color c;
 
 // constructor
 Circle()
 {
   x = random(5, width - 5);
   y = random(5, height - 5);
   xdir = 1;
   ydir = 1;
   dx = random(-2, 2);
   dy = random(-2, 2);
   c = (int) random(190, 240);
 }
 
 void display()
 {
   noStroke();
   fill(c);
   ellipse(x, y, 10, 10);
   if (x > width - 5 || x < 5)
   {
     xdir *= -1;
   }
   if (y > height - 5 || y < 5)
   {
     ydir *= -1;
   }
     x += dx * xdir;
     y += dy * ydir;
 }  
}
Page Index Toggle Pages: 1