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 }