Processingのサンプルを参考にコードを書いた。(立方体の回転)
概要
以下のようなコードです。
- 2つの立方体が、回転する。
- マウスを画面の右下に移動するほど、回転速度が上がる。
- マウスの画面の左上に移動するほど、回転速度が下がる。
- 関数setupの中の01.jpgを、サブフォルダdataを作って格納する。この画像が立方体に貼られる。
コード
PImage tex; float rotx = PI/4; float roty = PI/4; void setup() { size(809, 500, P3D); tex = loadImage("01.JPG"); textureMode(NORMALIZED); fill(255); stroke(color(44,48,32)); } void draw() { background(#dddddd); noStroke(); translate(width/2.0, height/2.0, -100); rotateX(rotx); rotateY(roty); scale(90); TexturedCube(tex); TexturedCube2(tex); autorotate(); } void autorotate() { float rate = 0.01; float speed = (mouseX+mouseY) * 0.02; rotx += speed * rate; roty += speed * rate;; } void TexturedCube2 (PImage tex) { beginShape(QUADS); texture(tex); // +Z "front" face vertex(-2, -2, 2, 0, 0); vertex( 2, -2, 2, 2, 0); vertex( 2, 2, 2, 2, 2); vertex(-2, 2, 2, 0, 2); // +Y "bottom" face vertex(-2, 2, 2, 0, 0); vertex( 2, 2, 2, 2, 0); vertex( 2, 2, -2, 2, 2); vertex(-2, 2, -2, 0, 2); // +X "right" face vertex( 2, -2, 2, 0, 0); vertex( 2, -2, -2, 2, 0); vertex( 2, 2, -2, 2, 2); vertex( 2, 2, 2, 0, 2); endShape(); } void TexturedCube(PImage tex) { beginShape(QUADS); texture(tex); // +Z "front" face vertex(-1, -1, 1, 0, 0); vertex( 1, -1, 1, 1, 0); vertex( 1, 1, 1, 1, 1); vertex(-1, 1, 1, 0, 1); // -Z "back" face vertex( 1, -1, -1, 0, 0); vertex(-1, -1, -1, 1, 0); vertex(-1, 1, -1, 1, 1); vertex( 1, 1, -1, 0, 1); // +Y "bottom" face vertex(-1, 1, 1, 0, 0); vertex( 1, 1, 1, 1, 0); vertex( 1, 1, -1, 1, 1); vertex(-1, 1, -1, 0, 1); // -Y "top" face vertex(-1, -1, -1, 0, 0); vertex( 1, -1, -1, 1, 0); vertex( 1, -1, 1, 1, 1); vertex(-1, -1, 1, 0, 1); // +X "right" face vertex( 1, -1, 1, 0, 0); vertex( 1, -1, -1, 1, 0); vertex( 1, 1, -1, 1, 1); vertex( 1, 1, 1, 0, 1); // -X "left" face vertex(-1, -1, -1, 0, 0); vertex(-1, -1, 1, 1, 0); vertex(-1, 1, 1, 1, 1); vertex(-1, 1, -1, 0, 1); endShape(); }
解説
autorotate関数の、(mouseX+mouseY) * 0.02が、マウスカーソルの座標の縦軸と、横軸の和が速度に影響するようにするための部分です。
0.02をかけているのは、そのままマウスカーソルの座標を入力として与えると大きすぎるのでそれを小さくするために使っています。
この値を操作することで、マウスカーソルの移動による速度の増加を制御できます。
参考
Processingのサンプル, TextureCube