概要
plunkerでthree.jsやってみた。
練習問題、やってみた。
練習問題
クリックして、線を引け。
方針
- raycaster使う
- clickイベント使う
- line使う
写真
サンプルコード
let scene,
camera,
light,
renderer;
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(400, 400);
document.body.appendChild(renderer.domElement);
scene = new THREE.Scene();
scene.background = new THREE.Color(0xbfd1e5);
camera = new THREE.PerspectiveCamera(45, 400 / 400, 1, 1000);
camera.position.set(0, 0, 200);
scene.add(camera);
light = new THREE.AmbientLight(0xFFFFFF);
scene.add(light);
const size = 70;
const geometry = new THREE.BoxGeometry(size, size, size);
const material = new THREE.MeshNormalMaterial()
const box = new THREE.Mesh(geometry, material);
scene.add(box);
renderer.render(scene, camera);
var raycaster = new THREE.Raycaster();
var controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.update();
renderer.domElement.addEventListener('click', function(e) {
var raymouse = new THREE.Vector2();
raymouse.x = (e.offsetX / 400) * 2 - 1;
raymouse.y = -(e.offsetY / 400) * 2 + 1;
raycaster.setFromCamera(raymouse, camera);
var intersects = raycaster.intersectObjects(scene.children);
if (intersects.length > 0)
{
const material0 = new THREE.LineBasicMaterial({
color: 0xff0000
})
const points = new Array()
points.push(intersects[0].point)
points.push(new THREE.Vector3(50, -50, 40))
const geometry0 = new THREE.BufferGeometry().setFromPoints(points)
const line = new THREE.Line(geometry0, material0)
scene.add(line)
renderer.render(scene, camera);
}
})
function tick() {
requestAnimationFrame(tick);
renderer.render(scene, camera);
controls.update();
}
tick();
成果物
以上。