PVector p1,p2,n;
float d = 0; void setup()
{
size(600,600); p1 = new PVector(150,30);//线段第一个端点
p2 = new PVector(-25,-100);//线段第二个端点 PVector vec = PVector.sub(p1,p2);
vec.normalize();
n = new PVector(-vec.y,vec.x);//与线段垂直的向量
d = n.dot(p1);
} void draw()
{
background(#CCCCCC);
translate(300,300);//重置坐标原点
strokeWeight(1);
stroke(#000000);
line(-300,0, 300,0);//画横纵轴
line(0,-300, 0,300); drawLine(p1,p2);
drawVector(n); PVector q = new PVector(mouseX-300,mouseY-300);
strokeWeight(8);
stroke(#EEEE00);//yellow
point(q.x,q.y); float temp = d - q.dot(n);
PVector nearestPnt = new PVector(n.x,n.y);
nearestPnt.mult(temp);
nearestPnt.add(q); PVector delV1,delV2;//线段上的 最近点 到两端点的向量
delV1 = PVector.sub(nearestPnt,p1);
delV2 = PVector.sub(nearestPnt,p2);
if(PVector.dot(delV1,delV2)>0)//如果两个向量的点积大于0,则最近点在线段外
{
nearestPnt = module(delV1)<module(delV2)?p1:p2;//则重置最近点到最近的端点
} drawLine(q,nearestPnt);
} //求向量的模
float module(PVector v)
{
return sqrt(pow(v.x,2)+pow(v.y,2));
} //画一条绿色的线段,端点加粗
void drawLine(PVector p1,PVector p2)
{
strokeWeight(1);
stroke(0,155,0);
line(p1.x,p1.y, p2.x,p2.y);
strokeWeight(5);
point(p1.x,p1.y);
point(p2.x,p2.y);
} //画一个红色向量,原点开始
void drawVector(PVector v)
{
int k = 50;
strokeWeight(1);
stroke(255,0,0);
line(0,0, v.x*k,v.y*k);
strokeWeight(5);
point(0,0);
}