keeping an ellipse inside a larger ellipse
in
Programming Questions
•
2 years ago
I'm trying to have a small circle stay inside a larger circle. For the most part the conde i have below works, but at times the small circle escapes, acts erratically for a few moments, then returns inside the circle.
I've been trying to debug why this is happening and haven't had success yet. I would really appreciate if someone can help out and see my error.
When you run the code, if you click inside the large circle a small circle is drawn.
- int radius, diameter;
- int count, numCirc, circSize;
- int centerX, centerY;
- //boolean inside = false;
- Circ[] colliz;
- void setup(){
- size(500, 500);
- background(0);
- //set up the circular boundary
- diameter = width-100;
- radius = diameter/2;
- centerX = width/2;
- centerY = height/2;
- circSize = 10;
- count = 0;
- numCirc = 100;
- colliz = new Circ[numCirc];
- for (int i = 0; i < numCirc; i++){
- colliz[i] = new Circ();
- }
- //x = width/2;
- //y = height/2;
- //radius = width/2;
- //debug boundary
- fill(255);
- ellipse(centerX, centerY, diameter, diameter);
- }
- void draw(){
- background(0);
- fill(200);
- ellipse(centerX, centerY, diameter, diameter);
- for(int i = 0; i < count; i++){
- colliz[i].move();
- colliz[i].inside();
- //cycle through the array, call isIn for each index
- }
- }
- void mousePressed(){
- //when mouse is pressed start a circ at the mouseX, mouseY
- colliz[count].start(mouseX, mouseY, circSize, radius);
- count++;
- }
- class Circ{
- int x, y; //hold the current x and y for each circ object
- int mX, mY;
- int xOrigin = width/2;
- int yOrigin = height/2;
- int cDiameter, cRadius;
- int directionX = 1;
- int directionY = 1;
- int speed = 3;
- boolean isIn = true;
- boolean isOn = false;
- void start(int startX, int startY, int dia, int bounds){
- x = startX;
- y = startY;
- cRadius = bounds;
- cDiameter = dia;
- fill(255);
- ellipse(x, y, cDiameter, cDiameter);
- move();
- }
- void inside(){
- //x = sx;
- //y = sy;
- if ((sq(x - xOrigin) + sq(y - yOrigin)) <= sq(cRadius)){
- isIn = true;
- } else {
- isIn = false;
- }
- //println(isIn);
- //return isIn;
- }
- void directionShift(){
- //if the ball hits boundary, change direction *-1
- float xDist = abs(x - radius);
- float yDist = abs(y - radius);
- println("xDist:"+ xDist);
- println("yDist:"+ yDist);
- if(xDist > yDist){
- directionX *= -1;
- println("x direction change");
- } else if(yDist > xDist){
- directionY *= -1;
- println("y direction change");
- } else {
- println("else!");
- directionX *= -1;
- directionY *= -1;
- }
- }
- void move(){
- inside();
- if(isIn == false){
- directionShift();
- }
- x = x + (speed * directionX);
- y = y + (speed * directionY);
- fill(255);
- ellipse(x, y, cDiameter, cDiameter);
- }
- //write a function to check for collisions,
- //call directionShift when a collision happens
- }
1