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);//yellow32 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)