I am attempting to incorporate a 3D model into the scene upon mouse click, where the mesh should align with the point clicked by the mouse. This involves utilizing raycasting and projection techniques.
The code for the mouseClick event is as follows:
var Material = new THREE.MeshLambertMaterial({color : 0xfb0000});
Material.side = THREE.DoubleSide;
function mouseClick(event) {
var mouse3D = new THREE.Vector3(( event.clientX / window.innerWidth ) * 2 - 1,
-( event.clientY / window.innerHeight ) * 2 + 1,
0.5);
var Projector = new THREE.Projector();
Projector.unprojectVector(mouse3D, Camera);
mouse3D.sub(Camera.position);
mouse3D.normalize();
var raycaster = new THREE.Raycaster(Camera.position, mouse3D,0.1,100000);
var intersects;
intersects = raycaster.intersectObjects(Scene.children);
if (intersects.length > 0) {
var Mesh = new THREE.Mesh(ArrowGeometry, Material);
Mesh.scale.set(0.05,0.05,0.05);
Scene.add(Mesh);
Mesh.name = "arrow";
if(Scene.getObjectByName("arrow")!= undefined) {
console.log("added");
}
console.log(intersects[0].point);
}
}
document.addEventListener('mousedown', mouseClick, false);
However, when the mesh position is set to 'intersects[0].point', the mesh is not visible. Here is the remaining code:
var Renderer;
var Scene;
var Light1;
var Camera;
var Mesh;
var Width;
var Height;
var Controls ;
var ArrowGeometry;
function initialize()
{
Width = window.innerWidth;
Height = window.innerHeight;
Renderer = new THREE.WebGLRenderer({antialias: true, alpha: true})
Renderer.setSize(Width, Height);
document.body.appendChild(Renderer.domElement);
Renderer.setClearColor(0x000000, 0);
Scene = new THREE.Scene();
Camera = new THREE.PerspectiveCamera(45, Width/Height, 0.1, 10000);
Camera.position.set(3, 12, 13);
Scene.add(Camera);
Light1 = new THREE.HemisphereLight(0xffffff, 0x080820, .8);
Light1.position.y = 100;
Scene.add(Light1);
var Geometry = new THREE.PlaneGeometry(20, 20);
var Material = new THREE.MeshLambertMaterial({color: 0xf6b68a});
Material.side = THREE.DoubleSide;
var Mesh = new THREE.Mesh(Geometry, Material);
Mesh.rotateX(Math.PI/2);
Mesh.name = "plane";
Scene.add(Mesh);
var Loader = new THREE.JSONLoader();
Loader.load('models/arrow.json',function(geometry){
ArrowGeometry = geometry;
});
Controls = new THREE.OrbitControls(Camera, Renderer.domElement);
function animate()
{
requestAnimationFrame(animate);
Renderer.render(Scene, Camera);
}
window.onload = function()
{
initialize();
animate();
}
}