在 3js 中为多维数据集添加单击事件侦听器

编程入门 行业动态 更新时间:2024-10-28 00:27:31
本文介绍了在 3js 中为多维数据集添加单击事件侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在我的代码中,我有两个多维数据集,我想向它们添加单击事件侦听器.例如提醒用户点击了哪个立方体.当我将单击事件侦听器添加到文档时,它运行良好,但是当我将相同的单击事件侦听器添加到多维数据集时,它没有显示任何内容.这是我的部分代码..

In my code I have two cubes, I want to add click event listener to them. for example alerting on which cube the user clicked. When I added the click event listener to the document it was worked perfectly, but when I added the same click event listener to the cube it isn't showing anything. Here is my part of code..

<script type = "text/javascript" src = "three.min.js"></script>
<script type="text/javascript">
var camera = new THREE.PerspectiveCamera(70,window.innerWidth/window.innerHeight,0.1,1000);
var scene = new THREE.Scene();
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);

document.body.appendChild(renderer.domElement);
camera.position.z=30;

var geometry = new THREE.CubeGeometry(10,10,10);
var material = new THREE.MeshBasicMaterial({color:0x778899});
var cube = new THREE.Mesh(geometry,material);
cube.addEventListener("mousedown", onDocumentMouseDown, false);
cube.position.x = -10;
scene.add(cube);

var cube1 = new THREE.Mesh(geometry,material);
cube.addEventListener("mousedown", onDocumentMouseDown, false);
cube1.position.x=10;
scene.add(cube1);

var render = function(){
    var timer = Date.now()*-0.0002;
    requestAnimationFrame(render);
    camera.position.x = 30* Math.cos(timer);
    camera.position.z = 30* Math.sin(timer);

    camera.lookAt(scene.position);
    renderer.render(scene,camera);
};

render();

function onDocumentMouseDown(event){
    alert('hi');
}
</script>

推荐答案

addEventListener 只能用于 DOM 元素.请参阅 EventTarget.addEventListener()

addEventListener can only be used for DOM elements. See EventTarget.addEventListener()

如果你想在 Three.js 场景中选择对象,你应该查看 Three.js Raycaster

If you want to select objects in a Three.js scene you should look into the Three.js Raycaster

Raycaster 基本上将光线从相机发送到场景中,并返回与光线相交的对象数组.要使用 Raycaster,您需要将 addEventListener 附加到窗口对象或 Three.js 画布.

The Raycaster basically sends a ray from the camera into the scene and returns an array of objects that intersect with the ray. To make use of the Raycaster you need to attach the addEventListener to the window object or your Three.js canvas.

例如:window.addEventListener('mousemove', onMouseMove, false );

Three.js 示例页面上有很多使用 Raycaster 的示例.

There are a lot of examples for using the Raycaster on the Three.js examples page.

这篇关于在 3js 中为多维数据集添加单击事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 15:42:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1396412.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多维   侦听器   单击   中为   事件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!