我在three.js中创建了两个3d对象“网格”。 我想向这些对象添加click事件,这样当我点击其中一个对象时,它会按比例放大,当我点击另一个时,它会旋转。
我尝试使用此方法将click事件添加到对象中,但它无效。
<script src='threex.domevent.js'> </script>
<script>
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(20, window.innerWidth/window.innerHeight, 1, 1000);
camera.position.z = 100;
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var geometry = new THREE.CubeGeometry(1,1,1);
var material = new THREE.MeshBasicMaterial({color: 0x00ff00});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
cube.addEventListener( 'click',function(){cubeScale()} , false );
function cubeScale()
{
cube.scale.x *= 20;
}
var render = function () {
requestAnimationFrame(render);
cube.rotation.y += 0.1;
renderer.render(scene, camera);
};
render();
</script>
答案 0 :(得分:7)
你绝对需要实现 raycaster 来选择/点击/选择three.js中的某个对象。我已经在我的一个项目中使用three.js和raycaster对照collada模型实现了它。供您参考,这些链接可以帮助您:
答案 1 :(得分:1)
您可以使用此活动管理器three.interaction
并查看此demo
import { Scene, PerspectiveCamera, WebGLRenderer, Mesh, BoxGeometry, MeshBasicMaterial } from 'three';
import { Interaction } from 'three.interaction';
const renderer = new WebGLRenderer({ canvas: canvasElement });
const scene = new Scene();
const camera = new PerspectiveCamera(60, width / height, 0.1, 100);
// new a interaction, then you can add interaction-event with your free style
const interaction = new Interaction(renderer, scene, camera);
const cube = new Mesh(
new BoxGeometry(1, 1, 1),
new MeshBasicMaterial({ color: 0xffffff }),
);
scene.add(cube);
cube.cursor = 'pointer';
cube.on('click', function(ev) {});
cube.on('touchstart', function(ev) {});
cube.on('touchcancel', function(ev) {});
cube.on('touchmove', function(ev) {});
cube.on('touchend', function(ev) {});
cube.on('mousedown', function(ev) {});
cube.on('mouseout', function(ev) {});
cube.on('mouseover', function(ev) {});
cube.on('mousemove', function(ev) {});
cube.on('mouseup', function(ev) {});
// and so on ...
/**
* you can also listen on parent-node or any display-tree node,
* source event will bubble up along with display-tree.
* you can stop the bubble-up by invoke ev.stopPropagation function.
*/
scene.on('touchstart', ev => {
console.log(ev);
})
scene.on('touchmove', ev => {
console.log(ev);
})
&#13;
答案 2 :(得分:0)
您可以使用pickingRay
按照以下代码中的正交相机进行点击:
var vector = new THREE.Vector3(
(event.clientX / window.innerWidth) * 2 - 1,
-(event.clientY / window.innerHeight) * 2 + 1, 0.5);
var rayCaster = projector.pickingRay(vector, camera);
var intersectedObjects = rayCaster.intersectObjects(scene.children, true);
但如果你想要点击透视相机,你必须使用unprojectVector
进行点击,如下所示:
var vector = new THREE.Vector3(
(event.clientX / window.innerWidth) * 2 - 1,
- (event.clientY / window.innerHeight) * 2 + 1,
0.5 );
var rayCaster = projector.unprojectVector(vector, camera);
var intersectedObjects = rayCaster.intersectObjects(objects);