raycaster with class

by 蔡 育曄

HTML

<div id="info">raycaster
  <br>with class</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js">


</script>

CSS

#info {
  position: absolute;
  top: 0px;
  width: 100%;
  padding: 10px;
  text-align: center;
  color: #ffff00
}

body {
  overflow: hidden;
}

JavaScript

class Button {
  constructor(color, name) {
    this.on = false;
    this.hsl = color.getHSL(new THREE.Vector3());
    this.obj = this.makeButton(name);
  }

  get isOn() {
    return this.on;
  }

  toggle() {
    this.on = !this.on;
    this.update();
  }

  update() {
    if (this.on) {
      this.obj.scale.set (1,0.5,1);
      this.obj.children[0].material.color.setHSL 
        (this.hsl.h, 0, 1);
    } else {
    	this.obj.scale.set(1,1,1);
    	this.obj.children[0].material.color.setHSL 
         (this.hsl.h, this.hsl.s, this.hsl.l);
    }
  }
  

  makeButton(name) {
    let mesh = new THREE.Mesh(new THREE.BoxGeometry(20, 40, 20),
      new THREE.MeshLambertMaterial());
    let button = new THREE.Object3D();
    button.add(mesh);
    mesh.material.color.setHSL (this.hsl.h, this.hsl.s, this.hsl.l)
    mesh.position.y = 20;
    button.name = name;  // a string
    return button;
  }

}

var camera, scene, renderer, mesh, light, controls;
var raycaster = new THREE.Raycaster();
var pickables = [];
var mouse = new THREE.Vector2()

init();
animate();


function init() {
  scene = new THREE.Scene();

  camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 1000);
  camera.position.z = 500;

  light = new THREE.PointLight(0xffffff);
  light.position.set(100, 300, 200);
  scene.add(light);

  var gridXZ = new THREE.GridHelper(200, 20, 'red', 'white');
  scene.add(gridXZ);

  renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setClearColor(0xaaaaaa);

  controls = new THREE.OrbitControls(camera, renderer.domElement);

  document.body.appendChild(renderer.domElement);
  document.addEventListener('mousedown', onDocumentMouseDown, false);

  ///////////////////////////////////////////////////////////

  button = new Button(new THREE.Color (0x12ffff), 'cyan');
  scene.add(button.obj);
  pickables.push(button.obj);

  button2 = new Button(new THREE.Color (0xff12ff), 'purple');
 ...