We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.

Add an EventListener to a blender object

Home Forums Programming Add an EventListener to a blender object

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #39541
    elie520
    Participant

    Hello,
    I have a blender project from which I created a verge3d project. I used a bit of puzzle, but I would now like to directly use some JavaScript because it’s easier for me to organize my code.
    I’m at a point where I would simply like to add an eventlistener to detect a click on an object.

    I start by getting my hand on the desired object with let my_obj = app.scene.getObjectByName('myObjectName'). Then I naively tried my_obj.addEventListener('click', function(){console.log('my_obj was clicked!')}), but it won’t work, since I don’t think my_obj has that method. But is there a way to achieve what I want? Thank you!

    #39542
    GLiFTeK
    Customer
    #39574
    elie520
    Participant

    This is PERFECT thanks a lot!!

    For future reference, here’s a working example:

    function clickedBlenderObject(event) { // returns the clicked object if any, null otherwise
            let mouse = new v3d.Vector2();
            mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
            mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
            let raycaster = new v3d.Raycaster()
            raycaster.setFromCamera(mouse, app.camera);
            let intersected = raycaster.intersectObjects(app.scene.children)
            return intersected.length?intersected[0].object:null
        }
    
    function myFunction(event) {
            let clicked_object = clickedBlenderObject(event)
            if (clicked_object) {
                //do whatever you want with your clicked_object and the event
            }
        }
    
    window.addEventListener('click', myFunction);

    Of course, much more can be done since the raycasting encapsulates much more infos.

    Once more, thank you GlifTek :)

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.