Processing Month第一天 連接點 第一部分
這篇文章中,我們來看一下如何計算一個圓周上的點的座標,並將他們連接起來。我們將用靈活的方式來實現基於6個點和18個點的圖像
計算
要計算這些點的座標,必須知道圓上的點數量和圓的半徑。本例中,我們將畫12個點。
int numPoint = 12; float radius = 150;
下一步,我們來算一下每個點之間的角度。衆所周知一個整圓的角度是360度或2π弧度,所以用360度除以圓上的點數,就得到兩點之間的角度。例子中使用了弧度而不是角度,是因爲 cos() 和 sin() 函數的形參是弧度數,不是角度數。Processing中有一些關於圓和半圓的常量, TWO_PI 就代表了常量PI*2。(這裏的PVector其實是類型,代表這一個點)
float angle = TWO_PI / numPoint; for(int i=0 ; i<numberPoints;i++){ float x = cos(angle * i ) * radius; float y = sin(angle * i ) * radius; point[i] = new PVector(x,y ); }
我把計算的部分放在了setup()裏面,把結果存在了PVector數組裏,這樣我們就不用在draw函數裏一遍又一遍的計算點的x、y座標。我還用了一個for循環,用來計算每個點的座標,**angle*i** 會在每個循環中計算出一個點的座標。
繪製
接下來我們說一下,如何將圓上的點兩兩連線,我們需要用一個嵌套for循環,來遍歷數組中的每一個點。if語句用來比較i和j的數字,如果他們不相等,電腦就在這兩個點之間畫一條線。如果i和j相等,說明是同一個點,那麼就不用畫線了。
for (int i = 0; i < numPoints; i++) { for (int j = 0; j < numPoints; j++) { if ( j != i ) { line( points<i>.x, points<i>.y,points[j].x,points[j].y ); } } }
源碼:
int numPoints = 10;
PVector[] points = new PVector[numPoints];
float radius =150;
void setup()
{
size(450,400);
float angle = TWO_PI/numPoints;
for(int i=0;i<numPoints;i++)
{
float x = cos(angle * i ) * radius;
float y = sin(angle * i ) * radius;
points[i] = new PVector(x,y);
}
noLoop();
}
void draw()
{
smooth();
PImage img;
img = loadImage("images/laDefense.jpg");
background(img);
// background(0); //background(0,0,255);
//fill(0,0,255);
// fill(255,102,255);
stroke(0,0,255,60);
translate(width/2,height/2);
for(int i=0;i<numPoints;i++){
for(int j=0;j<numPoints;j++)
{
if(j!=i) {
// line( points<i>.x, points<i>.y,points[j].x,points[j].y );
line( points[i].x, points[i].y,points[j].x,points[j].y );
}
}
}
saveFrame("images/circle-connection-"+numPoints+".png");
}
成果: