在three.js中,可以通过以下步骤来实现单击更改几何图形颜色:
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, window.innerHeight);
document.body.appendChild(renderer.domElement);
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
document.addEventListener('mousedown', onMouseDown, false);
function onMouseDown(event) {
event.preventDefault();
var mouse = new THREE.Vector2();
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
// 调用射线投射函数
raycast(mouse);
}
var raycaster = new THREE.Raycaster();
function raycast(mouse) {
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(scene.children, true);
if (intersects.length > 0) {
// 获取第一个相交物体
var intersect = intersects[0];
// 更改几何体的颜色
intersect.object.material.color.set(0xff0000);
}
}
function animate() {
requestAnimationFrame(animate);
// 旋转几何体
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
animate();
通过以上步骤,当在three.js场景中单击几何体时,几何体的颜色将会变为红色。你可以根据自己的需求修改颜色、几何体类型等。
领取专属 10元无门槛券
手把手带您无忧上云