2013-10-18 103 views
0

問題是我有一個PVectors陣列放置在我的主PVector這是在中間。我希望我的PVector陣列根據旋轉變量在我的主PVector周圍旋轉。有沒有辦法做到這一點?處理PVector旋轉

現在我有這個代碼,但它不旋轉PVectors,只是基於旋轉var將它們放在更遠的地方。

class Box { 
    PVector location; 
    PVector[] points; 
    float rotation = random(360); 
    Box() { 
    location = new PVector(random(width), random(height)); 
    points = new PVector[4]; 

    for(a = 0; a < points.length; a ++) { 
     points[a] = new PVector(0,0); 
    } 
    } 

    void update() { 
    points[0].x = location.x + 10 * sin(rotation); 
    points[0].y = location.y + 10 * sin(rotation); 

    points[1].x = location.x + 10 * sin(rotation); 
    points[1].y = location.y - 10 * sin(rotation); 

    points[2].x = location.x - 10 * sin(rotation); 
    points[2].y = location.y + 10 * sin(rotation); 

    points[3].x = location.x - 10 * sin(rotation); 
    points[3].y = location.y - 10 * sin(rotation); 
} 
+0

你沒有考慮到一個點的帳戶原始座標。這是故意的嗎? – Basilevs

回答

1

要旋轉矢量,你需要使用觸發功能,如sincos就像你在你的代碼有。但是,你的方法並不是最好的。在每次更新時添加到現有的(x,y)座標上並不可行,因爲您必須添加的數量每次都在變化。只需爲每次更新覆蓋並計算新值就更簡單了。對於給定的角度的xy座標由單位圓給出:

Unit Circle

因此,給定的PVectorxcos(theta)變化,並且與ysin(theta)變化。請檢查下面的代碼:

Box b; 

void setup(){ 
    size(300,300); 
    b = new Box(); 
} 
void draw(){ 
    background(255); 
    b.update(mouseX, mouseY); 
    b.display(); 
} 

class Box { 
    PVector location; 
    PVector[] points; 
    float rotation; 
    float radius; 
    Box() { 
    location = new PVector(width/2,height/2); 
    points = new PVector[7]; 
    rotation = 0; 
    radius = 50; 
    for(int i = 0; i < points.length; i ++) { 
     //this centers the points around (0,0), so you need to add in 
     //the box coordinates later on. 
     points[i] = new PVector(radius*cos(rotation + i*TWO_PI/points.length), 
           radius*sin(rotation + i*TWO_PI/points.length)); 
    } 
    } 
    void update(int x, int y) { 
    location.set(x,y); 
    rotation += 0.08; // change for different rotation speeds. 
    for(int i = 0; i < points.length; i++){ 
     points[i].set(radius*cos(rotation + i*TWO_PI/points.length), 
        radius*sin(rotation + i*TWO_PI/points.length)); 
    } 
    } 
    void display(){ 
    stroke(0); 
    for(int i = 0; i < points.length; i++){ 
     //points are treated as offsets from the center point: 
     line(location.x,location.y,location.x+points[i].x,location.y+points[i].y); 
     ellipse(location.x+points[i].x,location.y+points[i].y,10,10); 
    } 
    } 
} 

對於每一個update()調用,它增加了rotation變量,並計算陣列中的每個點的新xy值。通過將0.08更改爲更大/更小/正數/負數,您可以更改旋轉的速度和方向。

+0

謝謝你,我會試着把它寫入我的程序 – Mark9135

+0

這正是我在找的東西,謝謝你soo – Mark9135

+0

遇到了問題,即使我移動位置,點x和y也不會改變。 – Mark9135

0

要圍繞位置旋轉點:

double x = cos(rotation) * (point.x-location.x) - sin(rotation) * (point.y-location.y) + location.x; 
double y = sin(rotation) * (point.x-location.x) + cos(rotation) * (point.y-location.y) + location.y; 
point.x = x; 
point.y = y; 

Rotate a point by an angle