LoginSignup
0
1

More than 3 years have passed since last update.

three.jsで深度のみを書き込む方法

Posted at

three.jsで3Dオブジェクトの色は描画せずに、深度のみを書き込む方法です。

THREE.MaterialcolorWriteプロパティをfalseにすることで実現できます。この際オブジェクトの描画順により最終的な描画結果が変わるので、THREE.Object3DrenderOrderプロパティで明示的に描画順を設定しましょう。

以下、サンプルコードです。キューブを横切るように深度のみを書き込む平面を配置しています。平面のrenderOrder-1を設定して最初に描画されるようにしています。
three-only-depth.gif

<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r118/three.min.js"></script>
    <style>
      body { margin: 0; }
      canvas { display: block; }
    </style>
  </head>
  <body>
    <script>
      const scene = new THREE.Scene();
      scene.background = new THREE.Color('#999999')
      const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

      const renderer = new THREE.WebGLRenderer();
      renderer.setSize(window.innerWidth, window.innerHeight);
      document.body.appendChild(renderer.domElement);

      const cube = new THREE.Mesh(
        new THREE.BoxBufferGeometry(),
        new THREE.MeshNormalMaterial()
      );
      scene.add(cube);

      const invisiblePlane = new THREE.Mesh(
        new THREE.PlaneBufferGeometry(3, 3),
        new THREE.MeshBasicMaterial({
          colorWrite: false,
          side: THREE.DoubleSide
        })
      );
      invisiblePlane.renderOrder = -1;
      invisiblePlane.rotation.y = Math.PI * 0.25;
      scene.add(invisiblePlane);

      camera.position.z = 3;

      const animate = function() {
        requestAnimationFrame(animate);
        cube.rotation.x += 0.01;
        cube.rotation.y += 0.01;
        renderer.render(scene, camera);
      };
      animate();
    </script>
  </body>
</html>
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1