Joey Abano
Joey Abano

Reputation: 61

ThreeJs Create Object / Mesh On Click

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 );

Upvotes: 1

Views: 932

Answers (1)

Tim.G.
Tim.G.

Reputation: 299

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

Upvotes: 1

Related Questions