【Three.js】オブジェクトの位置を変更する

position.setやrotationメソッドでオブジェクトの位置を変更する。

window.addEventListener('load', init);

function init() {
  const width = 640;
  const height = 480;

  const renderer = new THREE.WebGLRenderer({
    canvas: document.querySelector('#myCanvas')
  });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(width, height);

  const scene = new THREE.Scene();

  const camera = new THREE.PerspectiveCamera(60, width / height);
  camera.position.set(15, 15, 15);
  camera.lookAt(new THREE.Vector3(0, 0, 0));

  const cube_geometry = new THREE.BoxGeometry(1, 1, 1);
  const cube_material = new THREE.MeshNormalMaterial();
  const cube = new THREE.Mesh(cube_geometry, cube_material);
  cube.position.set(0.5, 0.5, 0.5);
  scene.add(cube);
  
  const plane_geometry = new THREE.PlaneGeometry(10, 10, 1, 1);
  const plane_material = new THREE.MeshBasicMaterial({color: 0xffffff});
  const plane = new THREE.Mesh(plane_geometry, plane_material);
  plane.rotation.x = -0.5 * Math.PI;
  plane.position.set(5, 0, 5);
  scene.add(plane); 
  
  const axes = new THREE.AxesHelper(12);
  scene.add(axes);

  renderer.render(scene, camera);
}

今回は、以下のように出力される。

set-position by inoha_naito -p5.js Web Editor
A web editor for p5.js, a JavaScript library with the goal of making coding accessible to artists, designers, educators,...

参考

three.js docs
three.js docs

タイトルとURLをコピーしました