元Webデザイナー兼コーダーの備忘録

ウェブデザインやプログラミング、ブログのカスタマイズなどについてアウトプットしています。

 メニュー

» HTML入門のまとめはこちらです。

【Three.js入門】物体操作:position,scale,rotation

物体操作について書きます。position,scale,rotationの値を操作して動きの変化を観察します。

position

オブジェクトの位置を指定します。一度に指定する方法とx,y,zを個別に指定する方法があります。コードの記述例は、以下です。

// 一度に指定する
オブジェクト.position.set(10, 10, 10);

// x,y,zを個別に指定する
オブジェクト.position.x = 10;
オブジェクト.position.y = 10;
オブジェクト.position.z = 10;

positionを使ったコード例

(function(){
  'use strict';

  const width = 500;  //表示領域の幅
  const height = 250;  //表示領域の高さ

  // Scene
  const scene = new THREE.Scene();

  // Mesh = Geometry + Material
  const geometry = new THREE.BoxGeometry(50, 50, 50);
  const material = new THREE.MeshLambertMaterial( { color: 0x0000ff} );
  const cube = new THREE.Mesh(geometry, material);
  cube.position.set(0, 0, 0);
  scene.add(cube);

  // Camera
  const camera = new THREE.PerspectiveCamera(45, width/height, 1, 1000);
  camera.position.set(0, 200, 300);
  camera.lookAt(scene.position);

  // Light
  const light = new THREE.DirectionalLight(0xffffff);
  light.intensity = 1;
  light.position.set(0, 0, 100);
  scene.add(light);

  // GridHelper
  const gridHelper = new THREE.GridHelper(200, 10);
  scene.add(gridHelper);

  // AxesHelper
  const axesHelper = new THREE.AxesHelper(180);
  scene.add(axesHelper);

  // Renderer
  const renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setSize(width, height);
  renderer.setClearColor(0xefefef);
  renderer.setPixelRatio(window.devicePixelRatio);
  document.getElementById('stage').appendChild(renderer.domElement);

  let v = 1;
  // アニメーション処理
  function animate(){
    requestAnimationFrame(animate);

    cube.position.x += v;
    if(50 < cube.position.x ){
      v = -1;
    }
    if(cube.position.x < -50){
      v = 1;
    }

    renderer.render(scene, camera);
  }

  animate();

})();

立方体が行ったり来たりします。

scale

オブジェクトの拡大・縮小の大きさを指定します。一度に指定する方法とx,y,zを個別に指定する方法があります。コードの記述例は、以下です。

// 一度に指定する
オブジェクト.scale.set(0.5, 2, 1);

// x,y,zを個別に指定する
オブジェクト.scale.x = 2;
オブジェクト.scale.y = 2;
オブジェクト.scale.z = 2;

scaleを使ったコード例

アニメーション処理の部分を抜粋します。

(function(){
  'use strict';

  ...

  // アニメーション処理
  function animate(){
    requestAnimationFrame(animate);

    // 拡大
    cube.scale.y += 0.01;
    renderer.render(scene, camera);
  }

  animate();

})();

立方体がy軸方向に拡大します。

rotation

オブジェクトの回転を指定します。一度に指定する方法とx,y,zを個別に指定する方法があります。コードの記述例は、以下です。

// 一度に指定する
オブジェクト.rotation.set(0, 1, -1);

// x,y,zを個別に指定する
オブジェクト.rotation.x += 0.01;
オブジェクト.rotation.y += 0.01;
オブジェクト.rotation.z += 0.01;

rotationを使ったコード例

アニメーション処理の部分を抜粋します。

(function(){
  'use strict';

  ...

  // アニメーション処理
  function animate(){
    requestAnimationFrame(animate);

    // 回転
    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;
    renderer.render(scene, camera);
  }

  animate();

})();

立方体がx軸、y軸を軸に回転します。

まとめ

  • position:オブジェクトの位置を指定
  • scale:オブジェクトの拡大・縮小の大きさを指定
  • rotation:オブジェクトの回転を指定

参考サイト

» HTML入門のまとめはこちらです。