Search code examples
three.jsdom-eventsmobile-devices

How tro make clicks on mobile devices in ThreeJS?


I use DomEvents library to make clicks on elements in scene.

I create eleemets:

domEvents = new THREEx.DomEvents(camera, renderer.domElement);
material0 = new THREE.MeshBasicMaterial({ 
 transparent: true,
 opacity: 0,
 map: runnerTexture, 
 side: THREE.DoubleSide,
 depthWrite: false
});
mesh_un[3] = new THREE.Mesh( geometry0, material0 );
mesh_un[3].name = 'obj3';
mesh_un[3].position.set(-1200, 7200, 5800);
mesh_un[3].add(new THREE.Mesh( geometry, material ));

And then add events:

domEvents.addEventListener(element, touchEvent, function(event) {
 console.log(event);
 page.popup(index);
 return true;
});

They works very good on desktop, but not working on mobile devices.

Is it problem of library or in my scene? How to make clicks working good on all devices?

DEMO: http://cavsys.ru/o-tehnologii/fizicheskij-uroven/

enter image description here


Solution

  • I use something like this:

    this.init = function (picker) {
        camera = GameScene.getCamera()
        container = GameRenderer.getDomElement()
    
        container.addEventListener('mousedown', picker.onContainerMouseDown, false)
        container.addEventListener('mousemove', picker.onContainerMouseMove, false)
        container.addEventListener('mouseup', picker.onContainerMouseUp, false)
        container.addEventListener('mouseout', picker.onContainerMouseOut, false)
    
    
        container.addEventListener('touchstart', picker.onContainerTouchStart, true)
        container.addEventListener('touchmove', picker.onContainerTouchMove, true)
        container.addEventListener('touchend', picker.onContainerTouchEnd, true)
        container.addEventListener('touchcancel', picker.onContainerTouchEnd, true)
    }
    

    and

    this.onContainerTouchStart = function (event) {
        event.offsetX = event.changedTouches[0].clientX
        event.offsetY = event.changedTouches[0].clientY
    
        handleDownStart(event)
    }
    this.onContainerMouseMove = function (event) {
        if (Page.hasTouch()) {
            return
        }
        handleMove(event)
    }
    this.onContainerTouchMove = function (event) {
        event.offsetX = event.changedTouches[0].clientX
        event.offsetY = event.changedTouches[0].clientY
    
        handleMove(event)
    }
    this.onContainerMouseUp = function (event) {
        if (Page.hasTouch()) {
            return
        }
        //console.log('up')
        event.preventDefault()
        dragStart = 0
    }
    this.onContainerMouseOut = function (event) {
        event.preventDefault()
        dragStart = 0
    }
    this.onContainerTouchEnd = function (event) {
        //console.log('touchEnd')
        dragStart = 0
    }
    

    You can see full code here: https://jsfiddle.net/brbfdLo5/1/