2012-10-19 41 views
2

中的一條線我繪製了一條隨機線,並且我想在此情況下用一個Letter,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 
} 

回答

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,而不是完整的

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)

乾杯,

+0

Thanks guys ...原型代碼現在完美工作。 – Lance

0
  1. 查找行y的斜率= mx + c(m =斜率)。角=反正切(米)
  2. 角度旋轉= 2 * PI-角度,順時針
+0

謝謝你們.................. – Lance