1

I'm using ThreeJS, how can you create an object / mesh on mouse click. Currently the object is not created on the exact mouse x and y position.

    var ge = new THREE.BoxBufferGeometry( 2, 2, 2 );
      ge.scale(2, 2, 2);
      var my = new THREE.MeshBasicMaterial( { 
      map: new THREE.TextureLoader().load( 'crate.gif' )
    } );
    ms = new THREE.Mesh( ge, my );

    var raycaster = new THREE.Raycaster();
    var mouse = new THREE.Vector2();
    mouse.x = ( event.clientX / renderer.domElement.width ) * 2 - 1;
    mouse.y = - ( event.clientY / renderer.domElement.height ) * 2 + 1;
    raycaster.setFromCamera( mouse, camera );
    ms.position.x=raycaster.ray.direction.x; 
    ms.position.y=raycaster.ray.direction.y; 
    ms.position.z=raycaster.ray.direction.z;
    scene.add( ms );
0

1 Answer 1

1

I had the same problem. The value raycaster.ray.position.(x|y|z) is always between -1 and 1.

After some testing i got, what i think, is what you want. One direction has to be defined. You actually need to create a Plane Object (not a mesh).

Here's how it works:

var vec = raycaster.ray.intersectPlane(new THREE.Plane(new THREE.Vector3(0, 1, 0)));

What you need to do here is get the rayintersection on a defined plane. The Plane is infinitely big and invisible. You also need to tell the plane in which direction it should point. In this case it's (x=0,y=1,z=0) which basically means it just lays there and points upward.

And then it should work with:

ms.position.x=vec.x; 
ms.position.y=vec.y; 
ms.position.z=vec.z;

On click, this is the result: (the red boxes are added on click) boxes on Click

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. This one really helped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.