Three.js怎么才可以对每一个mesh绑定事件?

需要兼容移动端事件,之前找到了一个事件库,可惜绑定touch事件会失败

有对threejs了解的大大吗?

阅读 14.1k
4 个回答

首先获取点击的位置,然后转换成3d的坐标,使用raycaster 向坐标发射一个射线,如果击中了表示点击成功。大概思路是这个,three.js有demo的。

还真的有人问这个问题。

three.js官方没有提供交互事件的支持,但是你可以试试我的这个库,可以让你轻松的为任何显示对象绑定浏览器的各种交互事件。

更多详情点击 three.interaction

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 linsten at parent or any display-tree node,
 * source event will bubble up along with display-tree.
 */
scene.on('touchstart', ev => {
  console.log(ev);
})
scene.on('touchmove', ev => {
  console.log(ev);
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题