Mouse click in wrong location

For my project I need some buttons on the side of my window. So I changed the size of the window. However, I need to be able to select objects in the scene by clicking on them, which is misbehaving.
I suspect it to have something to do with this function while I suspect it has to do with transformation of the mouse position to select the object:

    private onMouseMove = (event: { clientX: number; clientY: number; }) => {
    const mouse: THREE.Vector2 = new THREE.Vector2((event.clientX / window.innerWidth) * 2 - 1,
        - (event.clientY / window.innerHeight) * 2 + 1);

    this.perspectiveCamera.updateMatrixWorld();
    this.raycaster.setFromCamera(mouse, this.perspectiveCamera);
}

Can you try it with this (JS) code instead:

function onClick(event) {

    const rect = renderer.domElement.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;

    mouse.x = ( x / canvas.clientWidth ) *  2 - 1;
    mouse.y = ( y / canvas.clientHeight) * - 2 + 1

    this.perspectiveCamera.updateMatrixWorld();
    this.raycaster.setFromCamera( mouse, this.perspectiveCamera );

}

It will respect the relative position of the canvas in your HTML document.

4 Likes

That was what I was looking for. couldnt find the actual code to get it to work. Thank you.