如何在矩形的边框上绘制一个点?

时间:2014-03-04 17:04:01

标签: java vector trigonometry processing

我正试图解决这个问题...... 该点应位于鼠标指向的位置的边界上。换句话说,在矩形边界线与矩形中心和鼠标指针之间的线之间交叉。我需要以某种方式使用三角函数,因为矩形可能会旋转。下面的代码(处理中)使我能够绘制点,但只能在南边界...

int size = 200;

void setup() {
  size(1200,500);
  smooth();
  ellipseMode(CENTER);
  rectMode(CENTER);

}

void draw() {
  background(255);
  noFill();

  PVector center = new PVector(width/2,height/2);
  PVector mouse = new PVector(mouseX, mouseY);

  float mouseDistance = PVector.dist(center,mouse);

  mouse.sub(center); // mouse coordinates relative to center point

  float t = atan2(mouse.y, mouse.x);

  float borderDistance = (size/2) / sin(t); 
  float bx = cos(t) * borderDistance;
  float by = sin(t) * borderDistance;

  pushMatrix();
    translate(center.x, center.y);
    strokeWeight(5);
    stroke(255,0,0);
    point(0,0);
    point(mouse.x, mouse.y);
    point(cos(t)*size/2, sin(t)*size/2);
    point(bx,by);
    strokeWeight(1);
    stroke(0);
    ellipse(0, 0, size, size);
    rect(0,0, size, size);
    stroke(0,255,0);
    line(0, 0, mouse.x, mouse.y);
  popMatrix();
}

2 个答案:

答案 0 :(得分:7)

好的,这里的数学将为您提供所需点的位置。

参考图表:

Problem Diagram

要找到Green点,我们需要做的就是找到虚构矩形的高度和宽度(见图),标记为Adj和{{1}分别将这些值添加到Opp点。


如果您还记得Center,我们会利用SOH CAH TOA

TOA

可以重新安排:

Tan(Theta) = Opposite / Adjacent 

因此,我们需要先找到Opposite = Tan(Theta) * Adjacent Adjacent (Adj)


咨询图表,Theta显然是Adjy之间Orange的差异:

Center

但我们不知道Adj = Orange.y - Center.y ?好吧,Orange等于Orange加上矩形高度的一半:

Center

Orange = (Center.x, Center.y + Rect.Height/2) 的值重新计入我们的Orange计算:

Adj

接下来我们需要找到Adj = Center.y + Rect.Height/2 - Center.y Adj = Rect.Height/2

enter image description here

重新回到Theta SOH CAH TOA

CAH

我们之前已经知道Cos(Theta) = Adjacent / Hypotenuse Theta = acos(Adjacent / Hypotenuse) //Inverse cosine ,所以我们只需找到Adj = Rect.Height/2。要查找Hyp,我们可以使用distance formula来说明:

Hyp

在我们的案例中:

d = sqrt((x2 - x1)^2 + (y2 - y1)^2)

现在我们拥有Hyp = sqrt((Center.x - Mouse.x)^2 + (Center.y - Mouse.y)^2) 所需的一切:

Theta

最后,我们拥有Theta = acos(Adj / Hyp) //Inverse cosine 所需的内容:

Opp

这意味着我们拥有回答您问题所需的一切:

Opp = Tan(Theta) * Adjacent

注意:

  • 这是使用学位的“纸上数学”。许多编程语言都处理弧度而不是度数,因此您可能需要进行一些转换。

  • 正如@Jerry Andrews所指出的,这个问题会有四种不同的情况,它们对应于绘图点可能落在矩形的四个不同边:

  

要确定象限,他首先需要中心之间的角度   矩形和任何角落 - 因此,atan(高度/宽度)。这将   给出半角(中心到绿色,如果绿色在角落)。然后   atan(mouse.y / mouse.x)将提供该行的角度   矩形中心到鼠标光标(因为在他的代码中,鼠标   相对于矩形的中心位置。)

答案 1 :(得分:0)

OK!我设法解决了边界问题。处理this link

下的草图和代码

我使用atan2()函数计算mouseTheta,然后需要使用象限:

 // north
      borderPoint = new PVector(tan(mouseTheta-HALF_PI)*r, -r);
 // east
      if(mouseTheta > TWO_PI-QUARTER_PI || mouseTheta < QUARTER_PI) 
         borderPoint = new PVector(r, tan(mouseTheta)*r);
 // south
      if(mouseTheta >= QUARTER_PI && mouseTheta < QUARTER_PI+HALF_PI) 
         borderPoint = new PVector(-tan(mouseTheta-HALF_PI)*r, r); 
 // west
      if(mouseTheta >= HALF_PI+QUARTER_PI && mouseTheta < PI+QUARTER_PI) 
         borderPoint = new PVector(-r,-tan(mouseTheta)*r); 

看起来很丑,但有效......谢谢!