1 PVector p1,p2,n;
2 float d = 0;
3
4 void setup()
5 {
6 size(600,600);
7
8 p1 = new PVector(150,30);//线段第一个端点
9 p2 = new PVector(-25,-100);//线段第二个端点
10
11 PVector vec = PVector.sub(p1,p2);
12 vec.normalize();
13 n = new PVector(-vec.y,vec.x);//与线段垂直的向量
14 d = n.dot(p1);
15 }
16
17 void draw()
18 {
19 background(#CCCCCC);
20 translate(300,300);//重置坐标原点
21 strokeWeight(1);
22 stroke(#000000);
23 line(-300,0, 300,0);//画横纵轴
24 line(0,-300, 0,300);
25
26 drawLine(p1,p2);
27 drawVector(n);
28
29 PVector q = new PVector(mouseX-300,mouseY-300);
30 strokeWeight(8);
31 stroke(#EEEE00);//yellow
32 point(q.x,q.y);
33
34 float temp = d - q.dot(n);
35 PVector nearestPnt = new PVector(n.x,n.y);
36 nearestPnt.mult(temp);
37 nearestPnt.add(q);
38
39 PVector delV1,delV2;//线段上的 最近点 到两端点的向量
40 delV1 = PVector.sub(nearestPnt,p1);
41 delV2 = PVector.sub(nearestPnt,p2);
42 if(PVector.dot(delV1,delV2)>0)//如果两个向量的点积大于0,则最近点在线段外
43 {
44 nearestPnt = module(delV1)<module(delV2)?p1:p2;//则重置最近点到最近的端点
45 }
46
47 drawLine(q,nearestPnt);
48 }
49
50 //求向量的模
51 float module(PVector v)
52 {
53 return sqrt(pow(v.x,2)+pow(v.y,2));
54 }
55
56 //画一条绿色的线段,端点加粗
57 void drawLine(PVector p1,PVector p2)
58 {
59 strokeWeight(1);
60 stroke(0,155,0);
61 line(p1.x,p1.y, p2.x,p2.y);
62 strokeWeight(5);
63 point(p1.x,p1.y);
64 point(p2.x,p2.y);
65 }
66
67 //画一个红色向量,原点开始
68 void drawVector(PVector v)
69 {
70 int k = 50;
71 strokeWeight(1);
72 stroke(255,0,0);
73 line(0,0, v.x*k,v.y*k);
74 strokeWeight(5);
75 point(0,0);
76 }
![]()