22/02/28

【three.js】PlaneGeometryを地面として使う

PlaneGeometryはただの平面を表示させるジオメトリ。

公式ドキュメントを見てこんなのいつ使うんだろう?と疑問に思ったけど、

どうやらこれで地面を表現できるらしいのでやってみた。

See the Pen
Untitled
by minomino (@minomino_)
on CodePen.

 

考え方はとてもシンプルだがただの覚え書き。

大きめのPlaneGeometryを表示させ、

X方向に-90°回転させる。90°は1/2π。(ちなみに+90°だと平面が他の物体の下方向に隠れてしまう)

そのままだと他の物体の中心に平面がきてしまうので、

Y方向に-0.5してあげるとSphereの下にぴったり引っ付くといった具合。

const boxGeometry = new THREE.BoxGeometry();
const sphereGeometry = new THREE.SphereGeometry(0.5, 32, 16);
const planeGeometry = new THREE.PlaneGeometry(10, 10);

//マテリアル
const material = new THREE.MeshNormalMaterial();

//メッシュ化
const box = new THREE.Mesh(boxGeometry, material);
const sphere = new THREE.Mesh(sphereGeometry, material);
const plane = new THREE.Mesh(planeGeometry, material);
sphere.position.x = 1.5;
plane.rotation.x = -Math.PI * 0.5;
plane.position.y = -0.5;

scene.add(box, sphere, plane);