Processingでは図形を再利用する仕組みが用意されている。 「繰り返し」のところで五角形を描いたが、それを少し変更すると星型が描かれる。
int i, th=0; size( 200, 200 ); beginShape(); for( i=0; i<5; i++ ){ vertex(50 + 20 * sin(radians(th)), 130 - 20 * cos(radians(th))); th = th + 144; } endShape(CLOSE);
これは点(50,130)を中心とする星形を描くスケッチであるが、これを変更して、(100,100), (150,30), (50, 130)の3か所に星を描くことにする。 同じことを3回書くこともできるが、Shapeを用いれば、次のスケッチのように、図形を再利用できる。 PShape star;で、starという名前のShapeを使うことを宣言する。 createShape()でShapeを用意する。 その下の6行の内容は、star.を加えることで、画面ではなくShapeに描くことを指定していること、中心を(0,0)にしていること以外は上とほぼ同様である。 shape(star, 100, 100)でShapeを画面の点100,100に描く。
int i, th=0; PShape star; size( 200, 200 ); star=createShape(); star.beginShape(); for( i=0; i<5; i++ ){ star.vertex(20 * sin(radians(th)), -20 * cos(radians(th))); th = th + 144; } star.endShape(CLOSE);
shape(star, 100, 100); shape(star, 150, 30); shape(star, 50, 130);
図形を拡大、縮小、回転したり、色を変えたりすることもできる。 以下の例では、2番目の星を36度回転し、3番目の星を線を赤で、塗りつぶしを黄色で描く。なお、resetMatrixは拡大、縮小、回転を元に戻す。
int i, th=0; PShape star; size( 200, 200 ); star=createShape(); star.beginShape(); for( i=0; i<5; i++ ){ star.vertex(20 * sin(radians(th)), -20 * cos(radians(th))); th = th + 144; } star.endShape(CLOSE); shape(star, 100, 100); star.rotate(radians(36)); shape(star, 150, 30); star.resetMatrix(); star.setStroke(color(255,0,0)); star.setFill(color(255,255,0)); shape(star, 50, 130);
いくつかの図形を組み合わせて一つのShapeを作ることもできる。 次の例では、星(star)と三角形(tri)を組み合わせた図形(star_tri)を作る。 tri = createShape(TRIANGLE, 20, 0, 40, 7, 42, -5); は、3点(20,0), (40,7), (42,-5)を頂点とする三角形のShapeを作る。
star_tri=createShape(GROUP);
でいくつかのShapeを組み合わせて新しいShapeを作る「入れ物」を用意する。
star_tri.addChild(...);
でstar_triに( )内のShapeを追加する。
int i, th=0; PShape star, tri, star_tri; size( 200, 200 ); star=createShape(); star.beginShape(); for( i=0; i<5; i++ ){ star.vertex(20 * sin(radians(th)), -20 * cos(radians(th))); th = th + 144; } star.endShape(CLOSE); tri = createShape(TRIANGLE, 20, 0, 40, 7, 42, -5); star_tri=createShape(GROUP); star_tri.addChild(star); star_tri.addChild(tri); shape(star_tri, 100, 100); star.rotate(radians(36)); shape(star, 150, 30); star.setStroke(color(255,0,0)); star.setFill(color(255,255,0)); shape(star, 50, 130);
createShapeではいろいろな図形で示した簡単な図形を作成することができる。
createShape(POINT,x,y); | 点(x,y) |
createShape(LINE,x1,y1,x2,y2); | 2点(x1,y1), (x2,y2)を結ぶ線分 |
createShape(TRIANGLE,x1,y1,x2,y2,x3,y3); | 3点(x1,y1), (x2,y2), (x3,y3)を頂点とする三角形 |
createShape(QUAD,x1,y1,x2,y2,x3,y3,x4,y4); | 4点(x1,y1), (x2,y2), (x3,y3), (x4,y4)を頂点とする四角形 |
createShape(RECT,x1,y1,x2,y2); | 2点(x1,y1), (x2,y2)を対角線とする長方形 |
createShape(ELLIPSE,x,y,dx,dy); | 中心(x,y)、x方向の直径dx、y方向の直径dyの楕円 |
createShape(ARC,x,y,dx,dy,a1,a2,mode); | 中心(x,y)、x方向の直径dx、y方向の直径dy、開始角a1、終了角a2の楕円弧。 |
createShape(BOX, w, h, d); | 直方体 |
createShape(SPHERE, r); | 球 |