确定点是否在斜边上或附近

时间:2013-10-17 09:02:43

标签: geometry collision-detection processing

在这个程序中,我试图将点画在斜边上。如果线是对角线,它似乎工作正常。但是线条越垂直或水平,点就越稀疏。如果线条完全垂直或水平,我没有点。红线也越长,点就越远离它。

这个问题似乎与我提出的问题类似,但我不明白答案。

How to check if a point (int - Coordinates) is within the hypotenuse of a triangle

我需要在红线上的每个像素上绘制一个点,但距离它不太远(最多1或2个像素)

此代码用于处理。

int sx,sy,ex,ey;
void setup(){
  sx=150;
  sy=150;
  ex=550;
  ey=550;
  size(600,600);
}

void draw(){
  background(255);
  stroke(#ff0000);
  fill(0);
  line(sx,sy,ex,ey);
  stroke(0);
  for(int y=0;y<height;y++){
    for(int x=0;x<width;x++){
      if(((x<=sx && x>=ex) || (x>=sx && x<=ex)) && ((y<=sy && y>=ey) || (y>=sy && y<=ey))){ 
        double xdiff=ex-sx;
        double ydiff=ey-sy;
        double xpos=(x-sx)/xdiff;
        double ypos=(y-sy)/ydiff;
        double diff=xpos-ypos;
        if(diff>-0.01 && diff < 0.01) ellipse(x,y,3,3);
      }
    }
  }
}

void mousePressed() {
    if(mouseButton == LEFT){
      ex=mouseX;
      ey=mouseY;
    }else{
      sx=mouseX;
      sy=mouseY;
    }   
}

1 个答案:

答案 0 :(得分:2)

您是否可以按照线条本身而不是测试每个像素?

int sx,sy,ex,ey;

void setup(){
  size(600,600); //size() should always be the first line of setup()
 sx=150;
 sy=150;
 ex=550;
 ey=550;
 background(255);
}

void draw(){}

void mousePressed(){
  background(255);
  fill(0);
  stroke(0);
  if(mouseButton == LEFT){
    ex=mouseX;
    ey=mouseY;
  }else{
    sx=mouseX;
    sy=mouseY;
  } 
  line(sx,sy,ex,ey);
  float dx = (ex-sx);
  float dy = (ey-sy);
  float numDots = sqrt(pow(ey-sy,2) + pow(ex-sx,2));

  for(int i = 0; i < numDots; i++){
    ellipse(sx + i*dx/numDots, sy + i*dy/numDots,3,3);
  }
}

或者,使用Processing的PVector类:

PVector start,end;

void setup(){
  size(600,600); //size() should always be the first line of setup()
  start = new PVector(150,150);
  end = new PVector(550,500);
  background(255);
}

void draw(){}

void mousePressed(){
  background(255);
  fill(0);
  stroke(0);
  if(mouseButton == LEFT)
    end.set(mouseX,mouseY);
  else
    start.set(mouseX,mouseY);
  line(start.x,start.y,end.x,end.y);
  PVector slope = new PVector(end.x-start.x,end.y-start.y);
  float numDots = end.dist(start);

  for(int i = 0; i < numDots; i++){
    ellipse(start.x + i*slope.x/numDots, start.y + i*slope.y/numDots,3,3);
  }
}