How to move a circle across a line in processing?

2019-07-27 00:56发布

问题:

I have a line segment and a circle in a processing sketch. In the sketch the circle finds the closest point on the line segment and another line is created to show that closest point. I want the circle to move across this line towards the closest point. Also I want the circle to find the closest point on the line segment itself, but my sketch right now acts as though the line goes on forever. Any help is appreciated.

float x1,y1,x2,y2;
float cx,cy;
float x4,y4;

void setup() {
   size(600,600);
}

void init() {
   x1 = (int)random(100,500);
   y1 = (int)random(100,500);
   x2 = (int)random(100,500);
   y2 = (int)random(100,500);
   cx = (int)random(100,500);
   cy = (int)random(100,500);   
}   

void draw() {
   background(60);
   init();
   stroke(220);
   line(x1,y1,x2,y2);
   noFill();
   ellipse(cx,cy,50,50);
   noStroke();
   fill(220,20,20);//red- center of circle
   ellipse(cx,cy,8,8);
   // calculate the point
   float k = ((y2-y1) * (cx-x1) - (x2-x1) * (cy-y1)) / 
        ((y2-y1)*(y2-y1) + (x2-    x1)*(x2-x1));
   float x4 = cx - k * (y2-y1);
   float y4 = cy + k * (x2-x1);
   fill(20,20,220); //blue - point on line segment
   ellipse(x4,y4, 8,8);
   stroke(0);
   line(cx,cy,x4,y4);
   noLoop();
}

void keyPressed() { 
   loop(); 
} 

回答1:

If you have two points, you can use the lerp() function to get a series of points between them.

Calculates a number between two numbers at a specific increment. The amt parameter is the amount to interpolate between the two values where 0.0 equal to the first point, 0.1 is very near the first point, 0.5 is half-way in between, etc. The lerp function is convenient for creating motion along a straight path and for drawing dotted lines.

You can create a variable that you use as the amt argument between multiple calls to the draw() function. Then just increase that variable over time to move the point, and draw your circle there.