计算旋转角度以跟随Processing中的一条线

时间:2012-10-19 07:56:15

标签: java processing

我画了一条随机线,我希望在这种情况下用字母V来跟踪。我想要V的底点旋转并遵循线的方向,无论线的方向或方向是什么。但我真的不知道如何计算这个角度。下面是一些简单的代码来演示我的问题。你会看到正在绘制红线,我希望V的底点引导线条。

提前感谢任何建议。

float [ ] lineProgress = { 75, 350, 350, 350, 0 };
int lineSpeed = 25;
float angle = 0;

void setup() {
  background (255);
  size(400,400);
  noFill();
  frameRate(5);
}

void draw() 
{
    background (255);
    strokeWeight(1);

    stroke (0,255,0);
    line(lineProgress[0],lineProgress[1],lineProgress[2],lineProgress[3]);

    stroke (255,0,0);

    fill(255, 0,0, 125);

    float angle;
    //How Do I calculate this based on the line being drawn?
    angle =radians(270);

     line(
         lineProgress[0]
         , lineProgress[1]
         , lerp(lineProgress[0], lineProgress[2],lineProgress[4]/lineSpeed)
         , lerp(lineProgress[1], lineProgress[3],lineProgress[4]/lineSpeed)

         );

    rotLetter(
              "V"
               , lerp(lineProgress[0]
               , lineProgress[2]
               , lineProgress[4]/lineSpeed)
               , lerp(lineProgress[1]
               , lineProgress[3],lineProgress[4]/lineSpeed)
               , angle
               ) ;

     rotLetter("V", 200,200,angle) ;               

     lineProgress[4]++;
     if (lineProgress[4]>lineSpeed)
     {
       lineProgress[4]=0;
       lineProgress[0]=random(50,350);
       lineProgress[1]=random(50,350);
       lineProgress[2]=random(50,350);
       lineProgress[3]=random(50,350);
     }

}

void rotLetter(String l, float x, float y, float ang) {
  pushMatrix(); // save state
  textAlign(CENTER); // center letter horiz
  translate(x, y); // move to position
  rotate(ang); // rotate
   // draw char centered on acsender
   // this will work for most Caps, and some lc letters
   // but it will not allways vert center letters
  text(l, 0, textAscent()/2);
  popMatrix(); // return to saved coordinate matrix
}

3 个答案:

答案 0 :(得分:1)

给定从(x0, y0)(x1, y1)的行,其中X偏移dx = x1 - x0和Y偏移dy = y1 - y0,角度为:

atan2(dy, dx)

以弧度为单位。

使用atan2(y, x)代替atan(y / x)可确保返回的角度位于右侧象限。 atan仅将结果从-π/2返回到+π/2,而不是完整的

答案 1 :(得分:0)

你的朋友在计算旋转角度时是sine/cosine relations。您可以使用它们中的任何一个,但切线不涉及计算斜边的长度:

tan A = a / b

所以你的角度是

A = arctan( a / b )

或用Java术语:

double angle = Math.atan( ( lineprogress[ 3 ] - lineprogress[ 1 ] ) / 
                          ( lineprogress[ 2 ] - lineprogress[ 0 ] ) );

或@Alnitak也写道,使用atan2获取右象限的结果:

double angle =  Math.atan2( lineprogress[ 2 ] - lineprogress[ 0 ] ,
                            lineprogress[ 3 ] - lineprogress[ 1 ] );

假设(x1,y1)==(lineprogress [0],lineprogress [1])并且一致地为(x2,y2)

干杯,

答案 2 :(得分:0)

  1. 找到y = mx + c(m =斜率)的斜率。角=反正切(M)
  2. 旋转角度= 2 * Pi角度,顺时针