我知道這個問題已經被問到。我希望能夠改變對象的顏色,如果用鼠標選擇。我試着自己編寫代碼,但它似乎不工作,所以我想我錯過了一些東西。這基本上是腳本:用鼠標選擇對象 - Three.js
<script>
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth/2, window.innerHeight/2);
renderer.setClearColor(0xcccccc, 1);
document.body.appendChild(renderer.domElement);
scene.add(camera);
var geometry = new THREE.Geometry();
geometry.vertices.push(
new THREE.Vector3(-5, 5, 0),
new THREE.Vector3(-5, -5, 0),
new THREE.Vector3( 5, -5, 0)
);
var face = new THREE.Face3(0, 1, 2);
geometry.faces.push(face);
var material = new THREE.MeshBasicMaterial({color: 0x3300ff});
var triangle = new THREE.Mesh(geometry, material);
scene.add(triangle);
camera.position.z = 10;
document.addEventListener('mousedown', onDocumentMouseDown);
function onDocumentMouseDown(event) {
event.preventDefault();
var mouse3D = new THREE.Vector3((event.clientX/window.innerWidth) * 2 - 1,
-(event.clientY/window.innerHeight) * 2 + 1,
0.5);
var projector = new THREE.Projector();
var raycaster = projector.pickingRay(mouse3D.clone(), camera);
var intersects = raycaster.intersectObjects(objects);
if (intersects.length > 0) {
intersects[ 0 ].object.material.color.setHex(Math.random() * 0xffffff);
}
}
var render = function() {
requestAnimationFrame(render);
camera.lookAt(scene.position);
renderer.render(scene, camera);
};
render();
</script>
如果有人能幫助我,我將不勝感激。
使用eventcontrols)http://alexan0308.github.io/threejs/examples/controls_events_piano.html –
讓我提醒你,raycasting是在CPU上完成的,速度非常慢。更好的方法可以通過關鍵字「gpu picking」找到:你想渲染你的場景,每個可點擊的面具有不同的顏色,然後通過鼠標座標獲得像素的顏色。 –