Finding the index of a clicked object on the canvas

五迷三道 提交于 2019-12-13 03:47:14

问题


Edit: here is a simplified JSFiddle. The event listener is on line 60.

I'm using js and three.js to animate moving dandelion seeds, and I need to stop a seed if it is clicked. I'm adding an event listener to each seed, like so:

for (var i = 0; i < seeds.length; i++) {
    s=seeds[i];
    domEvents.addEventListener(seeds[i].mesh, 'click', function(event){
        s.clicked = true;
        console.log('you clicked on the mesh');
        $('#id01').modal('show');
    }, false);
}

The problem is that when a seed is clicked, the computer no longer knows what 's' or seeds[i] is, because the loop has ended. If I manually add an event listener to each seed, then the seeds stop correctly. This is inefficient however. It would be 19 blocks of this, with the only change being the number:

    domEvents.addEventListener(seeds[1].mesh, 'click', function(event){
        seeds[1].clicked = true;
        $('#id01').modal('show');
    }, false);

My code to stop the seed is the following:

        if (s.clicked === true) {
            console.log('hi');
            s.mesh.position.x = s.currentX;
            s.mesh.position.y = s.currentY;
        } else { run the code that moves the seed

The code to stop the seed works, but for the wrong seed. It stops whichever seed was last added to the seeds array.

See the full code here

Is there an efficient way to add the event listener correctly to each seed? How could I know the index of the clicked seed?

来源:https://stackoverflow.com/questions/52008133/finding-the-index-of-a-clicked-object-on-the-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!