The object disappear from the screen while trying to change its position

Hi guys, I’m trying to set the position of my 3d Object on the screen to where the user clicked but as soon as i click somewhere my object just disappear here is my code:

    threecanvas.onclick = myClickHandler;
    function myClickHandler(event) {
	 var x=event.clientX;
	 var y=event.clientY;
	 var z=0;
	  model.position.set(x,y,z);
    }

model is model.scene

Just assigning the even data to the model’s position does not work. The correct computation of mouse coordinates in NDC space is:

mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

You can unproject this vector like so (unprojecting means converting from NDC to world space):

worldPosition.set( mouse.x, mouse.y, 0.5 ).unproject( camera );

Live demo: https://jsfiddle.net/rk27L4oh/

However, this approach might not be ideal for your use case since the object will be placed right before the camera’s near plane. Consider to setup your code similar to the following example but raycast against a THREE.Plane. It will represent there are where you will place your objects.

https://threejs.org/examples/webgl_interactive_cubes

1 Like