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();
}