2016-05-04 29 views
0

我想實現以下處理 - Line在鼠標指針的方向

在我的代碼,如圖像的效果,我成功地創造出這種效果,但在重複的效果似乎繁殖向內。任何人都可以幫助我使我的代碼在上面的圖像中達到效果嗎?

void setup(){ 
    size(500,500); 
    frameRate(60); 
    ellipseMode(CENTER); 
    smooth(); 
    loop(); 
} 

void draw() { 

    background(#ffffff); 

    //border 
    strokeWeight(3); 
    fill(255); 
    arc(50, 50, 50, 50, -PI, -PI/2); 
    fill(255); 
    arc(450, 450, 50, 50, 0, PI/2.0); 
    line(25, 50, 25, 475); 
    line(25, 475, 450, 475); 
    line(475, 450, 475, 25); 
    line(475, 25, 135, 25); 
    fill(0); 
    text("MAGNETS", 60, 30); 

    //Lines  
for(int i=0; i<3; i++){ 
    drawMagnet(); 
} 
} 

    float angle = 0; 
    int x = 75; 
    int y = 75; 
    float tAngle = 0; 
    float easing = 0.1f; 

void drawMagnet(){ 

    int l = 10; //length 

    angle = atan2(mouseY - y, mouseX - x); 

    float dir = (angle - tAngle)/TWO_PI; 
    dir -= round(dir); 
    dir *= TWO_PI; 

    tAngle += dir * easing; 

    stroke(0); 
    translate(x, y); 
    rotate(tAngle); 
    line(-l, 0, l, 0); 
} 

回答

0

您的旋轉和翻譯堆疊,這是導致您的問題。爲了解決這個問題,你可以做這樣的事情:

pushMatrix(); 
    translate(x, y); 
    rotate(tAngle); 
    line(-l, 0, l, 0); 
    popMatrix(); 

這裏我使用的pushMatrix()popMatrix()功能,使您的旋轉和平移不疊加。

但是,然後所有的行都在相同的x,y位置。所以他們都對鼠標位置有相同的角度。

您正在使用translate()函數在不同的位置繪製它們,但這不會改變它們的基礎「模型」位置。

到我的回答對this question類似,您需要爲鹼您計算過的線路(使用screenX()screenY()功能)的屏幕位置,或者你需要停止依靠translate()移動你的線,並計算它們的直接定位。