processing绘制三角形网格构成半球体
时间: 2024-01-25 13:47:11 浏览: 31
以下是使用processing绘制三角形网格构成半球体的示例代码:
```processing
int numRings = 10; // 网格环数
int numSegments = 20; // 网格每环的段数
float radius = 200; // 半径
float[][] vertices = new float[numSegments+1][numRings+1]; // 存储顶点坐标的数组
void setup() {
size(500, 500, P3D);
noStroke();
fill(255);
// 计算顶点坐标
for (int j = 0; j <= numRings; j++) {
float theta = j * PI / numRings;
for (int i = 0; i <= numSegments; i++) {
float phi = i * TWO_PI / numSegments;
vertices[i][j] = radius * sin(theta) * cos(phi);
vertices[i][j] += heightAt(theta, phi);
vertices[i][j] *= -1;
}
}
}
void draw() {
background(0);
translate(width/2, height/2, -radius*2);
rotateX(map(mouseY, 0, height, -HALF_PI, HALF_PI));
rotateY(map(mouseX, 0, width, -PI, PI));
// 绘制三角形网格
for (int j = 0; j < numRings; j++) {
beginShape(TRIANGLE_STRIP);
for (int i = 0; i <= numSegments; i++) {
vertex(vertices[i][j], vertices[i][j+1], 0);
vertex(vertices[i][j], vertices[i][j+1], heightAt(j * PI / numRings, i * TWO_PI / numSegments) * radius);
}
endShape();
}
}
float heightAt(float theta, float phi) {
// 计算半球体上的高度
return map(noise(cos(phi)*2, sin(phi)*2, cos(theta)*2), 0, 1, -radius/4, radius/4);
}
```
代码中,`numRings`和`numSegments`分别表示网格的环数和每环的段数,`radius`表示半球体的半径。在`setup()`中,通过计算每个顶点的坐标并存储在`vertices`数组中。在`draw()`中,先将画布移到半球体的中心位置,再根据鼠标的位置进行旋转。然后通过循环绘制每个三角形网格,其中每个三角形由两行顶点构成,通过`TRIANGLE_STRIP`参数传递给`beginShape()`函数。最后,通过`heightAt()`函数计算半球体上每个点的高度,并将其乘以半径作为z轴坐标,绘制出半球体的形状。