主题源于我7月22日的课程结束后,同学课后在论坛提到的一个问题。原帖见
http://www.hudo.it/index.php?topic=412.msg1722#msg1722 追踪正N边形的轨迹与绘制一个正N边形完全不同,后者自然要简单许多,一般使用beginShape(),endShape() 以及vertex() 来连接多边形的各个端点即可,而端点坐标则可使用极坐标来确定,保证每个端点的极坐标(r,theta) 中r 恒定不变,theta 在2PI 的范围内平均分布即可。
而前者的方法较之比较复杂,所以单独开一个帖子,抛砖引玉。
先上我的代码,这里可以说明一下,sides 控制多边形的边数,dimemsion 控制每个端点离多边形中心的距离,即控制多边形的大小。如果你不高兴看完此帖,或看不懂此帖,但需要实现类似的功能,复制以下代码根据你的需要修改sides 以及dimemsion 即可。
PVector location;
PVector incre;
int sides = 3;
float dimension = 200;
float sideLength;
float increLength;
float currentLength;
float interiorAngle;
float degree;
void setup(){
size(800,800);
smooth();
colorMode(HSB);
background(255);
interiorAngle = 180*(sides-2)/float(sides);
increLength = 1;
sideLength = sin(radians(180/sides))*dimension*2;
location = new PVector(dimension,0);
degree += (360-interiorAngle)/2;
incre = new PVector(increLength*cos(radians(degree)),increLength*sin(radians(degree)));
}
void draw(){
translate(width/2,height/2);
if(currentLength<sideLength){
currentLength += increLength;
currentLength = constrain(currentLength,0,sideLength);
}else{
degree += 180-interiorAngle;
currentLength = 0;
}
incre.set(increLength*cos(radians(degree)),increLength*sin(radians(degree)),0);
location.add(incre);
stroke(0);
point(location.x,location.y);
}
然后详细说一下写以上代码的思路。使用到一些简单的向量运算。
向量 location 控制当前正N边形上点的位置,向量incre 控制正N边形上点位置的变化量,向量incre 的模保持恒定,而它的方向会根据具体情况发生改变,也就是当点走到多边形端点需要拐弯时发生改变。
而degree 控制的就是点走的角度,不同的正N边形拐弯时degree 的变化等于它的外角,即代码中的180-interiorAngle。而正N边形的内角可用中学的知识来求得,即(N-2)*180/N。

然后需要解决的是如何判断点走到多边形的端点位置。我的方法是声明了一个currentLength,对它累加increLength (也就是向量incre 的模)来得到当前点累积走过的距离,当currentLength 一旦超过多边形一边的长度,即刻使它归零,并使向量incre 的方向发生改变,currentLength 重新开始累加。
代码中有包含如何通过dimension 来计算多边形的一边长。
sideLength = sin(radians(180/sides))*dimension*2;
不理解见下图。

最后把向量location 与向量incre 相加,就可以得到多边形的边缘轨迹。
欢迎各种关于其他方法的交流,以及基于此的艺术作品。