Search code examples
objectgeometryprocessingtrigonometrycalculus

Processing: How do I make an object move in a circular path?


I have created a class where I define Shape objects for my program. Each of these Shapes has a transparent ellipse drawn around it (I defined that in my constructor) and if any other Shape moves into that circular ellipse area, I want that Shape to change it's direction so that it moves in a circular path.

Each Shape object has a defined radius attribute (because of the ellipse I draw around each object) and I want to use that value to determine how big of a circular pattern the Shape has to move in when it collides.

Please help! Anything is greatly appreciated!

EDIT:

As I said above, I want the shape to move into a circular path. HOWEVER, I want it only to move in a circular path once (meaning it moves around a circle once) and then I want it to continue on the original path it was programmed with.


Solution

  • The short answer is that you'll have to use basic trig to figure out the angle between the points, and then more basic trig to determine subsequent points on the circular path.

    Check out the trigonometry section of the Processing reference for more info.

    But basically, if you have two points, you can use the atan2() function to calculate the angle between them. You'd use this to find the starting angle from the center of your circle to the shape.

    Once you have that angle, you can simply increment it, and then use cos() and sin() to figure out the x and y coordinates at that new angle.

    Here is a basic sketch that does all of the above:

    PVector center;
    float angle;
    float radius;
    
    void setup() {
      size(500, 500);
      center = new PVector(width/2, height/2);
    
      //get the initial point
      //for you, this would be the initial location of the object
      PVector point = new PVector(random(width), random(height));
    
      //find the angle between the points
      float deltaX = center.x - point.x;
      float deltaY = center.y - point.y;
      angle = atan2(deltaX, deltaY);
    
      //find the radius of the circle
      radius = dist(center.x, center.y, point.x, point.y);
    
      ellipseMode(RADIUS);
    }
    
    void draw() {
      background(0);
    
      //draw the center point
      ellipse(center.x, center.y, 10, 10);
    
      //find the point based on the angle
      float x = center.x + cos(angle)*radius;
      float y = center.y + sin(angle)*radius;
    
      //draw the traveling point
      ellipse(x, y, 10, 10);
    
      //increment the angle to move the point
      angle += PI/120;
    }