我在加工草图中有一个线段和一个圆。在草图中,圆找到线段上的最接近点,然后创建另一条线以显示该最接近点。我希望圆越过这条线向最近的点移动。
我也希望圆在线段本身上找到最接近的点,但是我的草图现在的作用就好像线永远在继续。任何帮助表示赞赏。
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();
}
最佳答案
如果有两个点,则可以使用lerp()
函数在它们之间获得一系列点。
以特定的增量计算两个数字之间的数字。 amt
参数是在两个值之间进行插值的量,其中0.0等于第一个点,0.1紧邻第一个点,0.5介于第一个点的中间,依此类推。lerp函数便于沿a轴创建运动。直线路径和用于绘制虚线。
您可以在多次调用amt
函数之间创建一个变量,用作draw()
参数。然后随时间增加该变量以移动点,并在那里绘制圆。