three.js, tween camera and mousemove event - three.js

I'm trying my hands on three.js
I am moving the camera using a tween, and it works quite good.
At the end of the animation, however, the camera jumps back to its initial position.
I found out that the mousemove event was causing that behavior.
How can i fix this problem and keep both the tween movement and the mouse move?
I have constructed my three.js based on this example;
Mousemove declared inside render function
function render() {
camera.position.x += ( mouseX - camera.position.x ) * 0.04;
camera.position.y += ( - mouseY - camera.position.y ) * 0.04;
camera.lookAt( scene.position );
TWEEN.update();
renderer.render( scene, camera );
}
Tween movement
function setupTween (position, target, duration) {
TWEEN.removeAll();
new TWEEN.Tween (position)
.to (target, duration)
.easing (TWEEN.Easing.Quadratic.InOut)
.onUpdate (
function() {
// copy incoming position into camera position
camera.position.copy (position);
})
.start();
};
tween function source
UPDATE
Complete working code:
<script>
var container,
i,
camera,
scene,
renderer,
particles,
geometry,
materials = [],
color,
sprite,
size,
mouseX = 0,
mouseY = 0,
isTweening,
windowHalfX = window.innerWidth / 2,
windowHalfY = window.innerHeight / 2;
// +++++ three.js +++++
// +++++ +++++ +++++ +++++ +++++
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.5, 2000 );
camera.position.set (0,0,1900);
scene = new THREE.Scene();
scene.fog = new THREE.FogExp2( 0x000000, 0.0005 );
geometry = new THREE.Geometry();
var textureLoader = new THREE.TextureLoader();
for ( i = 0; i < 1000; i ++ ) {
var vertex = new THREE.Vector3();
vertex.x = Math.random() * 2000 - 1000;
vertex.y = Math.random() * 2000 - 1000;
vertex.z = Math.random() * 2000 - 1000;
geometry.vertices.push( vertex );
}
sprite = textureLoader.load( "circle.png" );
color = [0.90, 0.05, 0.8];
size = 8.5;
materials = new THREE.PointsMaterial( { size: size, map: sprite, blending: THREE.AdditiveBlending, depthTest: false, transparent : false } );
materials.color.setHSL( color[0], color[1], color[2] );
particles = new THREE.Points( geometry, materials );
scene.add( particles );
renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseMove( event ) {
mouseX = event.clientX - windowHalfX;
mouseY = event.clientY - windowHalfY;
}
function animate() {
requestAnimationFrame( animate );
render();
}
function startTween() {
isTweening = false;
var target = new THREE.Vector3(getRandomNumber(), getRandomNumber(), getRandomNumber());
new TWEEN.Tween (camera.position.clone())
.to (target, 1000)
.easing (TWEEN.Easing.Quadratic.InOut)
.onUpdate( function() {
camera.position.copy(this);
})
.onStart ( function() {
isTweening = true;
})
.onComplete ( function() {
isTweening = false;
})
.start();
}
function getRandomNumber() {
// get a number between -1000 and -500 and 500 and 1000
return ( Math.random() * 500 + 500 ) * ( Math.random() < 0.5 ? -1 : 1 );
}
function render() {
if(!isTweening && (mouseX || mouseY)) {
// more a generic approach, not just transforming x and y (maybe it needs to be improved a bit)
var upVector = camera.up.clone().transformDirection(camera.matrix);
var forwardVector = new THREE.Vector3().subVectors(scene.position, camera.position).normalize();
var rightVector = new THREE.Vector3().crossVectors(forwardVector, upVector);
camera.translateOnAxis(rightVector, mouseX);
camera.translateOnAxis(upVector, -mouseY);
mouseX = mouseY = 0;
}
camera.lookAt( scene.position );
TWEEN.update();
renderer.render( scene, camera );
}
init();
animate();
setTimeout(function(){
startTween();
},2500);
</script>

I think, you should only update the position by the mousemove event, when it's not tweening. So you need to check if its currently tweening or not.
var isTweening = false;
new TWEEN.Tween (camera.position)
.to (target, duration)
.easing (TWEEN.Easing.Quadratic.InOut)
.onStart ( function() {
isTweening = true;
})
.onComplete ( function() {
isTweening = false;
})
.start();
// in your render loop
function render() {
if (!isTweening) {
camera.position.x += ( mouseX - camera.position.x ) * 0.04;
camera.position.y += ( - mouseY - camera.position.y ) * 0.04;
}
camera.lookAt( scene.position );
TWEEN.update();
renderer.render( scene, camera );
}
You don't need to set an onUpdate function and copy the new position to camera.position. You can just pass over camera.position to the tween and it will work.
EDIT:
I didn't see the link to example. Now, I know which kind of navigation is used (which is actually used in a lot of three.js examples). It's not the mousemove event that is causing your problem, it's this kind of calculating the new camera position (camera.position.x += ( mouseX - camera.position.x ) * 0.04;). So, I changed the code of the example a bit, especially the navigation. Here are the important parts:
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
function onDocumentMouseMove( event ) {
mouseX = (event.movementX * 0.5) || event.mozMovementX || event.webkitMovementX || 0;
mouseY = (event.movementY * 0.5) || event.mozMovementY || event.webkitMovementY || 0;
}
function render() {
if(!isTweening && (mouseX || mouseY)) {
// more a generic approach, not just transforming x and y (maybe it needs to be improved a bit)
var upVector = camera.up.clone().transformDirection(camera.matrix);
var forwardVector = new THREE.Vector3().subVectors(scene.position, camera.position).normalize();
var rightVector = new THREE.Vector3().crossVectors(forwardVector, upVector);
camera.translateOnAxis(rightVector, mouseX);
camera.translateOnAxis(upVector, -mouseY);
mouseX = mouseY = 0;
}
camera.lookAt( scene.position );
TWEEN.update();
}
function startTween() {
isTweening = false;
var target = new THREE.Vector3(getRandomNumber(), getRandomNumber(), getRandomNumber());
new TWEEN.Tween (camera.position.clone())
.to (target, 1000)
.easing (TWEEN.Easing.Quadratic.InOut)
.onUpdate( function() {
camera.position.copy(this);
})
.onStart ( function() {
isTweening = true;
})
.onComplete ( function() {
isTweening = false;
})
.start();
}
function getRandomNumber() {
// get a number between -1000 and -500 and 500 and 1000
return ( Math.random() * 500 + 500 ) * ( Math.random() < 0.5 ? -1 : 1 );
}
And you are right about TWEEN.onUpdate: you need to copy the new values to camera.position. My earlier approach do also work, but then all of the functionality of THREE.Vector3 gets lost. I didn't realize that until now.

Related

Three.js DeviceOrientationControl makes scene disappear

I have a glb model which loads successfully and reacts to mouse movements. However when I add DeviceOrientationControl.js which is intended for mobile devices, the scene disappears. No errors visible in the console. Funny enough, when I change
controls = new DeviceOrientationControls( camera, renderer.domElement );
to
controls = new DeviceOrientationControls( group, renderer.domElement );
it works, but has strangely displaces the model around the axis, which I am not able to readjust manually. Can someone help me find a solution? Why doesn't it work with camera but with group (model directly)?
Also when I add
camera.lookAt(scene.position);
and disable DeviceOrientationControls, the model works however the desired controls are not, which is my main issue.
Here is my code:
import * as THREE from '../node_modules/three/build/three.module.js';
import {OrbitControls} from '../node_modules/three/examples/jsm/controls/OrbitControls.js';
import {DeviceOrientationControls} from '../node_modules/three/examples/jsm/controls/DeviceOrientationControls.js';
import {GLTFLoader} from '../node_modules/three/examples/jsm/loaders/GLTFLoader.js';
import { DRACOLoader } from '../node_modules/three/examples/jsm/loaders/DRACOLoader.js';
import Stats from '../node_modules/three/examples/jsm/libs/stats.module.js';
var camera, scene, renderer, group, stats, controls, windowHalfX = window.innerWidth / 2,
windowHalfY = window.innerHeight / 2,
mouseX = 0,
mouseY = 0;
var renderer = new THREE.WebGLRenderer();
renderer.shadowMap.enabled = true;
renderer.shadowMapSoft = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
var width = window.innerWidth;
var height = window.innerHeight;
window.onload = function () {
init();
animate();
$(".loadmain").fadeOut(500);
}
var startButton = document.getElementById( 'startButton' );
startButton.addEventListener( 'click', function () {
$("#overlay").fadeOut(700, function(){
$(this).remove();
});
document.body.className += "loaded";
document.querySelector("canvas").className += " load";
}, false );
const gltfLoader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath('https://raw.githubusercontent.com/mrdoob/three.js/dev/examples/js/libs/draco/');
dracoLoader.setDecoderConfig({ type: 'js' });
gltfLoader.setDRACOLoader(dracoLoader);
function init() {
camera = new THREE.PerspectiveCamera(45, width / height, 1, 10000);
controls = new DeviceOrientationControls( camera, renderer.domElement );
camera.position.set(0, 0, 7);
camera.zoom = 1;
camera.updateProjectionMatrix();
scene = new THREE.Scene();
scene.updateMatrixWorld();
var directionalLight = new THREE.DirectionalLight(0xffffff, 3);
directionalLight.color.setHSL(0.1, 1, 0.95);
directionalLight.position.set(0, 1, 1);
directionalLight.position.multiplyScalar(10);
scene.add(directionalLight);
directionalLight.shadow.mapSize.width = 2048;
directionalLight.shadow.mapSize.height = 2048;
var spotLight1 = new THREE.DirectionalLight( 0xff4000 );
spotLight1.position.set( -15, 3, -4 );
spotLight1.target.position.set( 0, 1, 0 );
spotLight1.castShadow = true;
scene.add( spotLight1 );
var spotLight2 = new THREE.DirectionalLight( 0xff0aea );
spotLight2.position.set( 15, 3, -4 );
spotLight2.target.position.set( 0, 1, 0 );
spotLight2.intensity = 1.2;
spotLight2.castShadow = true;
scene.add( spotLight2 );
group = new THREE.Group();
group.position.x = 0;
scene.add( group );
scene.add( camera );
gltfLoader.load('../public/res/3D/model.glb', (gltf) => {
const root = gltf.scene;
root.rotateY(-89.55);
root.position.x = 0;
root.position.y = -0.7;
root.castShadow = true;
group.add(root);
});
renderer = new THREE.WebGLRenderer({ antialias: true, canvas: document.querySelector('canvas'), alpha: true, });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild( renderer.domElement );
window.addEventListener( 'resize', onWindowResize, false );
window.addEventListener('mousemove', onDocumentMouseMove, false);
}
function onDocumentMouseMove(event) {
event.preventDefault();
mouseX = (event.clientX / window.innerWidth) * 2 - 1;
mouseY = - (event.clientY / window.innerHeight) * 2 + 1;
}
function animate() {
window.requestAnimationFrame( animate );
if (group) {
group.rotation.y = mouseX * .5;
group.rotation.x = mouseY * -.5;
}
controls.update();
render();
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function render() {
//camera.lookAt(scene.position);
renderer.render( scene, camera );
}

How to animate a Collada model's children in three.js?

I'm trying to find a way to animate the children in a Collada model of the Canadarm2. The model contains 7 arm segments whose angles need to be set by reading in rotation angle data from each of 7 spreadsheet columns one row at a time. Each line holds 7 columns of data representing each second's angles in an hour, or longer, mission.
I'm hoping someone might suggest a solution to get me started -- perhaps something like the guesswork I've tried inside the animate() function below.
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, stats, clock;
var camera, scene, renderer, canadarm2;
init();
animate();
function init() {
container = document.getElementById( 'container' );
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 2000 );
camera.position.set( 8, 10, 80 );
camera.lookAt( new THREE.Vector3( 0, 3, 0 ) );
scene = new THREE.Scene();
clock = new THREE.Clock();
// loading manager
var loadingManager = new THREE.LoadingManager( function() {
scene.add( canadarm2 );
} );
// collada
var loader = new THREE.ColladaLoader( loadingManager );
//loader.load( 'examples/models/collada/elf/elf.dae', function ( collada ) {
loader.load( 'canadarm2.dae', function ( collada ) {
canadarm2 = collada.scene;
} );
//
var ambientLight = new THREE.AmbientLight( 0xcccccc, 0.4 );
scene.add( ambientLight );
var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.8 );
directionalLight.position.set( 1, 1, 0 ).normalize();
scene.add( directionalLight );
//
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
//
stats = new Stats();
container.appendChild( stats.dom );
//
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
/*
//#######################################
// doesn't work
var armEP = canadarm2.getChildByName("EP", true);// EP is one of 7 arms
armEP.position.x += 0.01;
armEP.rotation.y += 45;
//#######################################
*/
render();
stats.update();
}
function render() {
var delta = clock.getDelta();
if ( canadarm2 !== undefined ) {
canadarm2.rotation.z += delta * 0.5;
}
renderer.render( scene, camera );
}
This seems to work although it seems an awfully roundabout way to locate the arms.
scene.traverse(function (child) {
switch(child.name) {
case "SR":
child.rotation.x += 0.01;
break;
case "SP":
child.rotation.y += 0.01;
break;
case "SY":
child.rotation.y += 0.01;
break;
case "EP":
child.rotation.y += 0.01;
break;
case "WP":
child.rotation.x += 0.01;
break;
case "WY":
child.rotation.y += 0.01;
break;
case "WR":
child.rotation.x += 0.01;
break;
}
});

Can't rotate each mesh on animation update

I am quite new to Three.js and have been experimenting to get familiar with it.
I am making this exercise where I add to the scene 35 icosahedrons. I would like for each one of them to rotate when calling requestAnimationFrame.
I thought that by looping into each group children element (which is each mesh) and adding value to x and y rotation I could make the meshes rotate. Why is not so? Any help is very appreciated. Thank you.
This my approach:
var camera, scene, renderer;
var geometry, material, mesh;
var edgesGeometry, edgesMaterial, edges;
var group;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init()
animate()
function init() {
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 1500;
scene = new THREE.Scene();
group = new THREE.Group();
for ( var i = 0; i < 35; i ++ ) {
var randomSize = Math.floor( Math.random() * (150 - 20) + 20 )
geometry = new THREE.IcosahedronGeometry( randomSize, 1 );
material = new THREE.MeshBasicMaterial({ color: 0x000000 });
mesh = new THREE.Mesh( geometry, material );
mesh.position.x = Math.random() * 2000 - 1000;
mesh.position.y = Math.random() * 2000 - 1000;
mesh.position.z = Math.random() * 2000 - 1000;
mesh.rotation.x = Math.random() * 2 * Math.PI;
mesh.rotation.y = Math.random() * 2 * Math.PI;
edgesGeometry = new THREE.EdgesGeometry( mesh.geometry )
edgesMaterial = new THREE.LineBasicMaterial( { color: 0x63E260, linewidth: 2 } )
edges = new THREE.LineSegments( edgesGeometry, edgesMaterial )
mesh.add( edges )
mesh.matrixAutoUpdate = false;
mesh.updateMatrix();
group.add( mesh );
}
scene.add( group );
//
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
//
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
//
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseMove( event ) {
mouseX = ( event.clientX - windowHalfX ) * 0.25;
mouseY = ( event.clientY - windowHalfY ) * 0.25;
}
function animate() {
requestAnimationFrame( animate );
for ( var i = 0; i < group.children.length; i ++ ) {
group.children[i].rotation.x += 0.001;
group.children[i].rotation.y += 0.001;
}
render();
}
function render() {
camera.position.x += ( mouseX - camera.position.x ) * 0.05;
camera.position.y += ( - mouseY - camera.position.y ) * 0.05
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/93/three.js"></script>
To expand on #prisoner849's comment:
When three.js renders a scene, it parses the entire scene looking for renderable items (visible, within the view frustum, etc.). Part of that process involves multiplying out the transformation matrices to populate the world matrix (matrixWorld) of each renderable item is up-to-date. As you can imagine, this can potentially be a process hog, so you also have the ability to turn off that auto-update.
It looks like you understand that, because your line of code: mesh.matrixAutoUpdate = false; does exactly that, then you follow it up by manually updating the mesh's matrix. This is mostly correct, but you also need to do this for each frame.
For a simple/shallow scene like yours, #prisoner849's approach is correct--just let three.js auto-update the matrices by removing the lines mentioned. But if your scene is more complex, and you want finer control over it, you'll need to exert that control for each frame you want to render.
In the example below, I took your original code and made it so that only every second icosahedron rotates. This is accomplished by collecting them into an array, and then only updating the matrices for objects in that array. (Also note I turned off matrix auto-updating for the entire scene, rather than individual objects.)
var camera, scene, renderer;
var geometry, material, mesh;
var edgesGeometry, edgesMaterial, edges;
var group;
var mouseX = 0,
mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var updatableObjects = [];
init()
animate()
function init() {
camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.z = 1500;
scene = new THREE.Scene();
scene.autoUpdateMatrix = false; // turn off automatic matrix computation
group = new THREE.Group();
for (var i = 0; i < 35; i++) {
var randomSize = Math.floor(Math.random() * (150 - 20) + 20)
geometry = new THREE.IcosahedronGeometry(randomSize, 1);
material = new THREE.MeshBasicMaterial({
color: 0x000000
});
mesh = new THREE.Mesh(geometry, material);
mesh.position.x = Math.random() * 2000 - 1000;
mesh.position.y = Math.random() * 2000 - 1000;
mesh.position.z = Math.random() * 2000 - 1000;
mesh.rotation.x = Math.random() * 2 * Math.PI;
mesh.rotation.y = Math.random() * 2 * Math.PI;
edgesGeometry = new THREE.EdgesGeometry(mesh.geometry)
edgesMaterial = new THREE.LineBasicMaterial({
color: 0x63E260,
linewidth: 2
})
edges = new THREE.LineSegments(edgesGeometry, edgesMaterial)
mesh.add(edges)
if (i % 2) {
updatableObjects.push(mesh);
}
group.add(mesh);
}
scene.add(group);
//
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
//
document.addEventListener('mousemove', onDocumentMouseMove, false);
//
window.addEventListener('resize', onWindowResize, false);
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX) * 0.25;
mouseY = (event.clientY - windowHalfY) * 0.25;
}
function updateMeshes(mesh) {
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.01;
mesh.updateMatrix();
}
function animate() {
requestAnimationFrame(animate);
updatableObjects.forEach(updateMeshes);
render();
}
function render() {
camera.position.x += (mouseX - camera.position.x) * 0.05;
camera.position.y += (-mouseY - camera.position.y) * 0.05
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/93/three.js"></script>

Object moving in different direction after rotating the plane, three js(v73)

I am have having issue in moving the object, when using mouse. When i move the object initially it works fine, but after rotating the scene about the y-axis, the object starts moving in opposite direction of the mouse. I have created a jsfiddle for that. Here is the code:
//define global variables here
var container, renderer;
var camera, scene, projector,mouseVector,controls;
var mouseX, mouseY, draggable;
var pen,c_mesh,interactiveObj = [];
var cube_selected=false;
var wallWidth=1200;
var wallHeight=400;
var raycaster = new THREE.Raycaster(); // create once
var mouse = new THREE.Vector2(); // create once
init();
animate();
function init(){
container=document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 10, 10000);
//camera.position.set(0,-wallWidth/2+10,wallWidth);
camera.position.set(0,-wallHeight/2+10,wallWidth);
// camera.lookAt(new THREE.Vector3(0,-wallWidth/2 +10,10));
//camera.lookAt(new THREE.Vector3(10,10,10));
scene = new THREE.Scene();
var ambient = new THREE.AmbientLight(0x666666);
scene.add(ambient);
//walls
walls = new THREE.Object3D();
var groundMat = new THREE.MeshPhongMaterial({color:0x808080});
var groundGeo_2 = new THREE.PlaneGeometry(wallWidth, wallWidth); //for roof and floor
var ground = new THREE.Mesh(groundGeo_2, groundMat);
ground.overdraw = true;
ground.position.set(0, -wallHeight, 0);
ground.rotation.x = -Math.PI/2;
walls.add(ground);
var cube_geometry = new THREE.CubeGeometry(500,300,100);
var c_material = new THREE.MeshNormalMaterial();
c_mesh = new THREE.Mesh(cube_geometry, c_material);
c_mesh.overdraw = true;
c_mesh.name = "first_cube";
c_mesh.position.set(0, -wallHeight+100/2-1 ,0); //c_mesh.add(camera);
c_mesh.rotation.x = Math.PI * 0.1;
interactiveObj.push(c_mesh);
walls.add(c_mesh);
scene.add(walls);
//projector = new THREE.Projector();
mouseVector = new THREE.Vector3();
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMapEnabled = true;
container.appendChild( renderer.domElement );
//IE, Chrome, Safari, Opera
document.addEventListener('mousewheel',onDocumentMouseWheel, false);
//Firefox
document.addEventListener('DOMMouseScroll', onDocumentMouseWheel, false);
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
document.addEventListener('mousedown', onDocumentMouseDown, false);
document.addEventListener('mouseup', onDocumentMouseUp, false);
window.addEventListener( 'resize', onWindowResize, false );
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
renderer.render( scene, camera );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseDown(event){
draggable = true;
event.preventDefault();
mouse.x = ( event.clientX / renderer.domElement.width ) * 2 - 1;
mouse.y = - ( event.clientY / renderer.domElement.height ) * 2 + 1;
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObjects( interactiveObj, true );
console.log(intersects);
if ( intersects.length > 0 ) {
if(intersects[0].object == c_mesh) {
renderer.domElement.style.cursor = 'pointer';
console.log("cube selected "); cube_selected=true;
}else{
cube_selected=false;
}
draggable = false;
}
}
function onDocumentMouseUp(event){
draggable = false;
cube_selected=false;
renderer.domElement.style.cursor = 'auto';
}
function onDocumentMouseMove( event ) {
if(draggable){
if(mouseX != 0 && mouseY != 0){
deltaX = event.clientX - mouseX;
deltaY = event.clientY - mouseY;
walls.rotation.y += deltaX * 0.01;
walls.rotation.x += deltaY * 0.01;
}
}else if (cube_selected==true){
if(mouseX != 0 && mouseY != 0){
deltaX = event.clientX - mouseX;
deltaY = event.clientY - mouseY;
c_mesh.position.x += deltaX*1.5 ;
c_mesh.position.y -= deltaY*1.5 ;
}
}
mouseX = event.clientX;
mouseY = event.clientY;
render();
}
function onDocumentMouseWheel( event ) {
mouseDelta = (-event.wheelDeltaY|| event.detail);
camera.position.z += mouseDelta * 1 ;
// console.log("camera position : "+ camera.position.z);
render();
}
https://jsfiddle.net/pn1pL4jb/5/
What i have done:
Added object in plane, rather then to scene because I want the same rotation of plane and object in the same direction.
The problem was that when you rotated the walls/ground with the mouse drag, the cube's rotation was not updated to match. So when you went to drag the cube after a world rotation, the cube is still operating in its old coordinate system. Also, be careful how you add children to parents. The cube should be a child of the scene (or world coordinate system) if you intend to move it all around. If it is a child of the floor or walls, things can get wacky really fast. :)
I updated your JSFiddle as well as cleaned up the code a little bit:
https://jsfiddle.net/aucyekux/
The magic is happening on line 126 with the copying of the wall's rotation into the cube's rotation so it matches:
c_mesh.rotation.copy(walls.rotation);
I won't assume how much 3D math you know, but I'll just say that copying the ground's rotation essentially creates a new frame of reference or local coordinate system for the cube so that when you drag it to the right, and the code says x = x + ... , its new coordinate system has its x direction pointing in the same direction as the ground/walls' new x direction (after the rotation you performed on them).
Hope this makes sense - don't worry if you don't quite get how it all works. I am a veteran 3D game programmer hobbyist for 20 years and I still sometimes forget how this all works and I have struggled with it plenty. I also refresh my understanding by browsing scratchapixel (the 3D math / coordinate system primer section) every now and then. It keeps all this 3D math stuff fresh. Good luck to you! :)
The following is a 2nd answer to this problem. The OP has added orbitControls.js to his app and now all the objects are more manageable. Here is the whole app's .html file, updated to reflect the changes. Now, you can click/drag to rotate the whole room. And then you can click/drag on the chair or the sofa and drag them around the room. Their Y positions are clamped to the ground (0.0) so that they do not incorrectly penetrate the floor.
The sliding of objects along the floor is achieved through raycasting against just the ground (when the mouse has selected them and dragging them). The raycast returns the intersection point in world space, so I just copy that into the draggable objects' position. Then a post-clamp of their Y positions prevent them from falling through the floor.
Even better, is the fact that we don't need localToWorld and worldToLocal matrix 'hacks' anymore because everything is relative to the Scene, which is how it is in real life. :) To prove this, I added an example update the chair's rotation around its own Y axis, so we have a spinning chair that is able to rotate around its own local center of gravity, while also being able to move its position relative to the Scene (world).
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head lang="en">
<meta charset="UTF-8">
<title>Room</title>
</head>
<body>
<script src="http://alexan0308.github.io/threejs/build/three.min.js"></script>
<script src="http://alexan0308.github.io/threejs/examples/js/loaders/OBJLoader.js"></script>
<script src="http://alexan0308.github.io/threejs/examples/js/loaders/MTLLoader.js"></script>
<script src="http://alexan0308.github.io/threejs/examples/js/loaders/OBJMTLLoader.js"></script>
<script src="http://threejs.org/examples/js/controls/OrbitControls.js"></script>
<div id="workspace"></div>
<script>
//define global variables here
var container, renderer;
var camera, scene, projector, mouseVector, controls;
var mouseX, mouseY, draggable;
var pen, c_mesh, interactiveObj = [], rotateObj = [], groundRaycastObj = [];
var wallWidth = 1200;
var wallHeight = 400;
var chair_model, sofa_model;
var chair_selected = false;
var sofa_selected = false;
var raycaster;
var mouse = new THREE.Vector2(), INTERSECTED;
var radius = 100, theta = 0;
var oldIntersectPoint = new THREE.Vector3();
var newIntersectPoint = new THREE.Vector3();
var intersectOffset = new THREE.Vector3();
var chair_rotate = false;
var walls;
var mesh_box;
var wallright, wallleft, wallback, wallfront, ceiling, ground;
var strDownloadMime = "image/octet-stream";
init();
animate();
function init() {
container = document.getElementById('workspace'); //document.createElement('div');
document.body.appendChild(container);
//camera
//camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 10, 10000);
// camera.position.set(0, -wallHeight / 2 + 10, wallWidth);
// camera.lookAt(new THREE.Vector3(10, 10, 10));
//renderer
renderer = new THREE.WebGLRenderer({preserveDrawingBuffer: true});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x889988);
renderer.shadowMapEnabled = true;
container.appendChild(renderer.domElement);
scene = new THREE.Scene();
raycaster = new THREE.Raycaster();
var ambient = new THREE.AmbientLight(0xffffff);
scene.add(ambient);
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z= wallWidth;
camera.position.y= wallWidth/2;
controls = new THREE.OrbitControls( camera, renderer.domElement );
//controls.addEventListener( 'change', render ); // add this only if there is no animation loop (requestAnimationFrame)
controls.enableDamping = true;
controls.dampingFactor = 0.25;
//controls.enableZoom = false;
//walls
walls = new THREE.Object3D();
var groundGeo_2 = new THREE.PlaneGeometry(wallWidth, wallWidth); //for roof and floor
var groundGeo = new THREE.PlaneGeometry(wallWidth, wallHeight);
var wallTextureRight = new THREE.MeshBasicMaterial({
map: THREE.ImageUtils.loadTexture('textures/walls/rainbow.jpg')
});
wallTextureRight.map.needsUpdate = true;
var wallTextureLeft = new THREE.MeshBasicMaterial({
map: THREE.ImageUtils.loadTexture('textures/walls/rainbow.jpg')
});
var wallTextureFront = new THREE.MeshBasicMaterial({
map: THREE.ImageUtils.loadTexture('textures/walls/wall4.jpg')
});
var wallTextureBack = new THREE.MeshBasicMaterial({
map: THREE.ImageUtils.loadTexture('textures/walls/wall3.png')
});
var floorTexture = new THREE.MeshBasicMaterial({
map: THREE.ImageUtils.loadTexture('textures/walls/floor.jpg')
});
floorTexture.map.needsUpdate = true;
var ceilTexture = new THREE.MeshBasicMaterial({
map: THREE.ImageUtils.loadTexture('textures/walls/wall4.jpg')
});
ground = new THREE.Mesh(groundGeo_2, floorTexture);
ground.overdraw = true;
ground.position.set(0, 0, 0);
ground.rotation.x = -Math.PI / 2;
walls.add(ground);
console.log(ground);
wallleft = new THREE.Mesh(groundGeo, wallTextureLeft);
wallleft.overdraw = true;
wallleft.position.set(-wallWidth / 2, wallHeight / 2, 0);
wallleft.rotation.y = Math.PI / 2;
walls.add(wallleft);
wallright = new THREE.Mesh(groundGeo, wallTextureRight);
wallright.overdraw = true;
wallright.position.set(wallWidth / 2, wallHeight / 2, 0);
wallright.rotation.y = -Math.PI / 2;
walls.add(wallright);
wallback = new THREE.Mesh(groundGeo, wallTextureBack);
wallback.overdraw = true;
wallback.position.set(0, wallHeight / 2, -wallWidth / 2);
walls.add(wallback);
wallfront = new THREE.Mesh(groundGeo, wallTextureFront);
wallfront.overdraw = true;
wallfront.position.set(0, wallHeight / 2, wallWidth / 2);
wallfront.rotation.y = -Math.PI;
walls.add(wallfront);
ceiling = new THREE.Mesh(groundGeo_2, ceilTexture);
ceiling.position.set(0, wallHeight, 0);
ceiling.rotation.x = Math.PI / 2;
walls.add(ceiling);
scene.add(walls);
groundRaycastObj.push(walls);
//load bed texture
var bed_texture = new THREE.ImageUtils.loadTexture("textures/cb-rochelle-gray_baked.png");
var bedMaterial = new THREE.MeshBasicMaterial({
map: bed_texture,
side: THREE.DoubleSide
});
//load bed
var loader = new THREE.JSONLoader();
loader.load('js/sofa.js', function (geometry) {
sofa_model = new THREE.Mesh(geometry, bedMaterial);
for (var i = 0; i < sofa_model.children.length; i++) {
sofa_model.children[i].material = material;
sofa_model.children[i].userDataParent = sofa_model;
sofa_model.children[i].name = 'sofa_model';
}
sofa_model.position.set(200,0, -200);
sofa_model.rotation.set(0, 0, 0);
sofa_model.scale.set(3, 3, 3);
sofa_model.name = 'sofa_model';
interactiveObj.push(sofa_model);
scene.add(sofa_model);
});
//load chair texture
var chair_texture = new THREE.ImageUtils.loadTexture("textures/chair.png");
var chairMaterial = new THREE.MeshBasicMaterial({
map: chair_texture,
side: THREE.DoubleSide
});
//load chair
var loader = new THREE.JSONLoader();
loader.load('js/chair_model.js', function (geometry) {
chair_model = new THREE.Mesh(geometry, chairMaterial);
for (var i = 0; i < chair_model.children.length; i++) {
chair_model.children[i].material = material;
chair_model.children[i].userDataParent = sofa_model;
chair_model.children[i].name = 'chair_model';
}
chair_model.position.set(-200,0, -200);
chair_model.rotation.set(0, 0, 0);
chair_model.scale.set(3, 3, 3);
chair_model.name = 'chair_model';
interactiveObj.push(chair_model);
scene.add(chair_model);
});
//IE, Chrome, Safari, Opera
document.addEventListener('mousewheel', onDocumentMouseWheel, false);
//Firefox
document.addEventListener('DOMMouseScroll', onDocumentMouseWheel, false);
document.addEventListener('mousemove', onDocumentMouseMove, false);
document.addEventListener('mousedown', onDocumentMouseDown, false);
document.addEventListener('mouseup', onDocumentMouseUp, false);
window.addEventListener('resize', onWindowResize, false);
}
function animate() {
requestAnimationFrame(animate);
chair_model.rotation.y += 0.02;
controls.update();
// Render the frame
//Don't render twice, it will slow down your animation!
//render();
renderer.render(scene, camera);
}
function render() {
renderer.render(scene, camera);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
//controls.handleResize();
}
function onDocumentMouseDown(event) {
draggable = true;
event.preventDefault();
var testIntersects;
testIntersects = raycaster.intersectObjects(groundRaycastObj, true);
if (testIntersects.length > 0)
oldIntersectPoint.copy(testIntersects[0].point);
// find intersections
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(interactiveObj, true);
if (intersects.length > 0) {
controls.enabled=false;
if (intersects[0].object.name == 'chair_model') {
container.style.cursor = 'pointer';
chair_selected = true;
} else if (intersects[0].object.name == 'sofa_model') {
container.style.cursor = 'pointer';
sofa_selected = true;
}
else {
chair_selected = false;
sofa_selected = false;
}
draggable = false;
}
}
function onDocumentMouseUp(event) {
draggable = false;
chair_selected = false;
sofa_selected = false;
chair_rotate = false;
container.style.cursor = 'auto';
controls.enabled=true;
oldIntersectPoint.set(0,0,0);
newIntersectPoint.set(0,0,0);
intersectOffset.set(0,0,0);
}
function onDocumentMouseMove(event) {
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = -( event.clientY / window.innerHeight ) * 2 + 1;
var deltaX = event.clientX - mouseX;
var deltaY = event.clientY - mouseY;
var testIntersects;
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(interactiveObj, true);
if (intersects.length > 0) {
container.style.cursor = 'pointer';
//addRotationLine(intersects[0].object);
} else {
container.style.cursor = 'auto';
}
if (draggable) {
} else if (chair_selected == true) {
testIntersects = raycaster.intersectObjects(groundRaycastObj, true);
if (testIntersects.length > 0) {
newIntersectPoint.copy(testIntersects[0].point);
intersectOffset.copy(newIntersectPoint);
intersectOffset.sub(oldIntersectPoint);
//uncomment below if you want more precision mouse movements of objects
//intersectOffset.multiplyScalar(0.1);
oldIntersectPoint.copy(newIntersectPoint);
chair_model.position.add(intersectOffset);
}
// clamp chair position to the ground
chair_model.position.y = 0;
} else if (chair_rotate == true) {
rotate_object(chair_model, event);
}
else if (sofa_selected == true) {
testIntersects = raycaster.intersectObjects(groundRaycastObj, true);
if (testIntersects.length > 0) {
newIntersectPoint.copy(testIntersects[0].point);
intersectOffset.copy(newIntersectPoint);
intersectOffset.sub(oldIntersectPoint);
//uncomment below if you want more precision mouse movements of objects
//intersectOffset.multiplyScalar(0.1);
oldIntersectPoint.copy(newIntersectPoint);
sofa_model.position.add(intersectOffset);
}
// clamp sofa position to the ground
sofa_model.position.y = 0;
}
mouseX = event.clientX;
mouseY = event.clientY;
//render(); // no need to render
}
function onDocumentMouseWheel(event) {
// This is automatically handled for you by orbitControls.js,
// but you can't disable zoom on the controls - so don't type controls.enableZoom = false;
//mouseDelta = (-event.wheelDeltaY || event.detail);
//camera.position.z += mouseDelta * 1;
//render(); // no need to render
}
function addRotationLine(objModel) {
var material = new THREE.LineBasicMaterial({
color: 0x0000ff,
linewidth: 6
});
var geometry = new THREE.Geometry();
geometry.vertices.push(
new THREE.Vector3(-10, 500, 0),
new THREE.Vector3(1000, 500, 0)
);
var line = new THREE.Line(geometry, material);
objModel.add(line);
}
function rotate_object(object, event) {
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = -( event.clientY / window.innerHeight ) * 2 + 1;
var deltaX = event.clientX - mouseX;
var deltaY = event.clientY - mouseY;
object.rotation.y += deltaX * 0.02;
object.rotation.y += deltaY * 0.01;
}
</script>
</body>
</html>
Change line 143 of the fiddle to:
c_mesh.position.x += deltaX*1.5 * Math.cos( walls.rotation.y);
When you rotate the scene, the plane the mouse moves on doesn't rotate with it. So you have to act like it does by scaling by the cosine of the rotation.

Three Js Object3D Button Group Detect Single Object Click While Mouse Movement Causes Object3D Button Group Zoomi

I am trying to detect a cube click in an Object3D group of Cubes. I have viewed, and tried to incorporate the examples and tutorials found at:
http://mrdoob.github.com/three.js/examples/webgl_interactive_cubes.html
and
http://mrdoob.github.com/three.js/examples/canvas_interactive_cubes.html
Also, I have consulted the posts on this site at:
Three.js - how to detect what shape was selected? after drag
and
how to Get CLICKED element in THREE.js
But for some reason, it's still not working. Can anyone please tell me what I'm doing wrong?
Here is my code, thanks:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Double Stamp It No Erasies</title>
<style>
html {
background: url(Images/ComicBookExplosionBackground.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
body {
}
</style>
<script src="ThreeJs/build/three.min.js"></script>
</head>
<body onLoad="onLoad();" style="">
<div id="container" style="width:100%; height:100%; position:absolute;"></div>
<script>
var container, ButtonsCamera, ButtonsScene, ButtonsRenderer, ButtonsGeometry, ButtonsGroup;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
/****************************** CLICK START **********************************/
var mouse = { x: 0, y: 0 }, projector, INTERSECTED;
var objects = [];
/****************************** CLICK END **********************************/
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
//document.addEventListener( 'mousedown', onDocumentMouseDown, false );
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
ButtonsCamera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
ButtonsCamera.position.z = 500;
ButtonsScene = new THREE.Scene();
ButtonsScene.fog = new THREE.Fog( 0xffffff, 1, 10000 );
/*************************** STACKOVERFLOW 1ST ANSWER START **********************************/
var ButtonsGeometry = new THREE.CubeGeometry( 100, 100, 100 );
var ButtonsMaterial = new THREE.MeshFaceMaterial( [
new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'Images/Twitter.jpg' ) } ),
new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'Images/Twitter.jpg' ) } ),
new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'Images/Twitter.jpg' ) } ),
new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'Images/Twitter.jpg' ) } ),
new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'Images/Twitter.jpg' ) } ),
new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'Images/Twitter.jpg' ) } )] );
/*************************** STACKOVERFLOW 1ST ANSWER END **********************************/
ButtonsGroup = new THREE.Object3D();
for ( var i = 0; i < 100; i ++ ) {
var ButtonsMesh;
if(i == 0)
{
ButtonsMesh = new THREE.Mesh( ButtonsGeometry, ButtonsMaterial );
}
else
{
ButtonsMesh = new THREE.Mesh( ButtonsGeometry, ButtonsMaterial );
}
ButtonsMesh.position.x = Math.random() * 2000 - 1000;
ButtonsMesh.position.y = Math.random() * 2000 - 1000;
ButtonsMesh.position.z = Math.random() * 2000 - 1000;
ButtonsMesh.rotation.x = Math.random() * 360 * ( Math.PI / 180 );
ButtonsMesh.rotation.y = Math.random() * 360 * ( Math.PI / 180 );
ButtonsMesh.matrixAutoUpdate = false;
ButtonsMesh.updateMatrix();
ButtonsGroup.add( ButtonsMesh );
}
ButtonsScene.add( ButtonsGroup );
/****************************** CLICK START **********************************/
objects.push( ButtonsMesh );
projector = new THREE.Projector();
/****************************** CLICK END **********************************/
ButtonsRenderer = new THREE.WebGLRenderer();
ButtonsRenderer.setSize( window.innerWidth, window.innerHeight );
ButtonsRenderer.sortObjects = false;
container.appendChild( ButtonsRenderer.domElement );
window.addEventListener( 'resize', onWindowResize, false );
/****************************** CLICK START **********************************/
document.addEventListener( 'mousedown', onDocumentMouseDown, false );
/****************************** CLICK END **********************************/
}
/****************************** CLICK START **********************************/
function onDocumentMouseDown( event ) {
//alert('clicky');
event.preventDefault();
var vector = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, - ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
projector.unprojectVector( vector, ButtonsCamera );
var raycaster = new THREE.Raycaster( ButtonsCamera.position, vector.subSelf( ButtonsCamera.position ).normalize() );
var intersects = raycaster.intersectObjects( objects);
if ( intersects.length > 0 ) {
intersects[ 0 ].object.material.color.setHex( Math.random() * 0xffffff );
var particle = new THREE.Particle( particleMaterial );
particle.position = intersects[ 0 ].point;
particle.scale.x = particle.scale.y = 8;
ButtonsScene.add( particle );
}
/*
// Parse all the faces
for ( var i in intersects ) {
intersects[ i ].face.material[ 0 ].color.setHex( Math.random() * 0xffffff | 0x80000000 );
}
*/
}
/****************************** CLICK END **********************************/
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
ButtonsCamera.aspect = window.innerWidth / window.innerHeight;
ButtonsCamera.updateProjectionMatrix();
ButtonsRenderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseMove(event) {
mouseX = ( event.clientX - windowHalfX ) * 10;
mouseY = ( event.clientY - windowHalfY ) * 10;
}
function animate() {
requestAnimationFrame( animate );
render();
ButtonsStats.update();
}
/****************************** CLICK START **********************************/
var radius = 100;
var theta = 0;
/****************************** CLICK END **********************************/
function render() {
var ButtonsTime = Date.now() * 0.001;
var rx = Math.sin( ButtonsTime * 0.7 ) * 0.5,
ry = Math.sin( ButtonsTime * 0.3 ) * 0.5,
rz = Math.sin( ButtonsTime * 0.2 ) * 0.5;
ButtonsCamera.position.x += ( mouseX - ButtonsCamera.position.x ) * .05;
ButtonsCamera.position.y += ( - mouseY - ButtonsCamera.position.y ) * .05;
ButtonsCamera.lookAt( ButtonsScene.position );
ButtonsGroup.rotation.x = rx;
ButtonsGroup.rotation.y = ry;
ButtonsGroup.rotation.z = rz;
ButtonsRenderer.render( ButtonsScene, ButtonsCamera );
}
</script>
</body>
</html>
Hey I hope I am not too late but anyway the solution to your problem is
a misplaced statement and a deprecated method.
You only have one object in your objects array that is why when you click on a
random box the raycaster is unlikely to detect an intersection.
Move the array push call into the for loop in order to add every object into
the array instead of the last object created.
for (var i = 0; i < 100; i++) {
var ButtonsMesh;
if (i == 0)
{
ButtonsMesh = new THREE.Mesh(ButtonsGeometry, ButtonsMaterial);
}
else
{
ButtonsMesh = new THREE.Mesh(ButtonsGeometry, ButtonsMaterial);
}
ButtonsMesh.position.x = Math.random() * 2000 - 1000;
ButtonsMesh.position.y = Math.random() * 2000 - 1000;
ButtonsMesh.position.z = Math.random() * 2000 - 1000;
ButtonsMesh.rotation.x = Math.random() * 360 * (Math.PI / 180);
ButtonsMesh.rotation.y = Math.random() * 360 * (Math.PI / 180);
ButtonsMesh.matrixAutoUpdate = false;
ButtonsMesh.updateMatrix();
ButtonsGroup.add(ButtonsMesh);
objects.push(ButtonsMesh);
}
The second problem is that newer versions of THREE don't use subSelf(),
it is replaced by sub(). So make the change to the Raycaster definition.
var raycaster = new THREE.Raycaster(ButtonsCamera.position,
vector.sub(ButtonsCamera.position).normalize());
That should solve your problems but there are more errors in your code
but they are all trivial.
I hope this helps and here is a working version: http://jsbin.com/uhihoq/1/edit
Peace!

Resources