如何在加工中移动一个圆越过一条线?
How to move a circle across a line in processing?
我在加工草图中有一条线段和一个圆。在草图中,圆找到线段上的最近点,并创建另一条线来显示该最近点。我希望圆圈越过这条线向最近的点移动。
我也想让圆找到线段本身最近的点,但我现在的草图就像这条线永远延伸一样。感谢任何帮助。
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()
函数得到它们之间的一系列点。
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.
您可以创建一个变量,在 draw()
函数的多次调用之间用作 amt
参数。然后随时间增加该变量以移动该点,并在那里绘制圆圈。
我在加工草图中有一条线段和一个圆。在草图中,圆找到线段上的最近点,并创建另一条线来显示该最近点。我希望圆圈越过这条线向最近的点移动。 我也想让圆找到线段本身最近的点,但我现在的草图就像这条线永远延伸一样。感谢任何帮助。
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()
函数得到它们之间的一系列点。
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.
您可以创建一个变量,在 draw()
函数的多次调用之间用作 amt
参数。然后随时间增加该变量以移动该点,并在那里绘制圆圈。