Three JS objects rotation point - three.js

I'm new in Three JS, learning by myself. I'm creating a spinning fidget spinner, but have one problem. Spinner spinning wrong. I need that all objects will spin round in center point of spinner. Now it making a big round.
I know you don't have time for this stuff, but it will be a good kick to me to keep going.
So my code is:
var loader = new THREE.TextureLoader();
var plane;
loader.load( 'img/stalas.jpg',
function ( texture ){ // užkrovus
texture.minFilter = THREE.NearestMipMapNearestFilter;
texture.magFilter = THREE.NearestMipMapNearestFilter;
var bump = new THREE.TextureLoader().load( "img/stalas.jpg" );
var planeGeometry = new THREE.PlaneGeometry(40,40);
var planeMaterial = new THREE.MeshStandardMaterial({ map: texture, bumpMap: bump, bumpScale: -0.2, overdraw: 0.5 });
planeMaterial.side = THREE.DoubleSide;
plane = new THREE.Mesh(planeGeometry,planeMaterial);
plane.receiveShadow = true;
plane.material.map.repeat.set(1, 1);
plane.material.map.wrapS = THREE.RepeatWrapping;
plane.material.map.wrapT = THREE.RepeatWrapping;
plane.rotation.x=-0.5*Math.PI;
plane.position.x=0;
plane.position.y=0;
plane.position.z=-5;
scene.add(plane);
},
function ( xhr ) { // krovimo metu
console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
},
function ( xhr ) { // klaidos atveju
console.log( 'Texture stalas.jpg cant be loaded!' );
}
);
//var group = new THREE.Object3D();
var pivot = new THREE.Object3D();
pivot.position.x=0;
pivot.position.y=3;
pivot.position.z=0;
var torus;
loader.load('img/metalas.jpg',
function (texture){
var torusGeometry = new THREE.TorusGeometry( 2, 0.6, 6, 100, 6.3 );
var torusMaterial = new THREE.MeshStandardMaterial({ map: texture, overdraw: 0.5 });
var bump = new THREE.TextureLoader().load( "img/metalas.jpg" );
torusMaterial.bumpMap = bump;
torusMaterial.bumpScale = 0.6;
torusMaterial.metalness = 0.1; // non metal 0-1 metal default 0.5
torusMaterial.roughness = 0.8; // mirror 0-1 diffuse default 0.5
torus = new THREE.Mesh(torusGeometry, torusMaterial);
torus.castShadow = true;
torus.material.map.repeat.set(0.5,0.5);
torus.rotation.x=-0.5*Math.PI;
torus.position.x=4.5;
torus.position.y=-2.48;
torus.position.z=0.5;
pivot.add( torus );
},
function (xhr) {
console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
},
function ( xhr ) {
console.log( 'Texture metalas.jpg cant be loaded!' );
}
);
scene.add(pivot);
var torus;
loader.load('img/metalas.jpg',
function (texture){
var torusGeometry = new THREE.TorusGeometry( 2, 0.6, 6, 100, 6.3 );
var torusMaterial = new THREE.MeshStandardMaterial({ map: texture, overdraw: 0.5 });
var bump = new THREE.TextureLoader().load( "img/metalas.jpg" );
torusMaterial.bumpMap = bump;
torusMaterial.bumpScale = 0.6;
torusMaterial.metalness = 0.1; // non metal 0-1 metal default 0.5
torusMaterial.roughness = 0.8; // mirror 0-1 diffuse default 0.5
torus = new THREE.Mesh(torusGeometry, torusMaterial);
torus.castShadow = true;
torus.material.map.repeat.set(0.5,0.5);
torus.rotation.x=-0.5*Math.PI;
torus.position.x=-3;
torus.position.y=-2.48;
torus.position.z=5;
pivot.add( torus );
},
function (xhr) {
console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
},
function ( xhr ) {
console.log( 'Texture metalas.jpg cant be loaded!' );
}
);
scene.add(pivot);
var torus;
loader.load('img/metalas.jpg',
function (texture){
var torusGeometry = new THREE.TorusGeometry( 2, 0.6, 6, 100, 6.3 );
var torusMaterial = new THREE.MeshStandardMaterial({ map: texture, overdraw: 0.5 });
var bump = new THREE.TextureLoader().load( "img/metalas.jpg" );
torusMaterial.bumpMap = bump;
torusMaterial.bumpScale = 0.6;
torusMaterial.metalness = 0.1; // non metal 0-1 metal default 0.5
torusMaterial.roughness = 0.8; // mirror 0-1 diffuse default 0.5
torus = new THREE.Mesh(torusGeometry, torusMaterial);
torus.castShadow = true;
torus.material.map.repeat.set(0.5,0.5);
torus.rotation.x=-0.5*Math.PI;
torus.position.x=5;
torus.position.y=-2.48;
torus.position.z=9;
pivot.add( torus );
},
function (xhr) {
console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
},
function ( xhr ) {
console.log( 'Texture metalas.jpg cant be loaded!' );
}
);
scene.add(pivot);
var torus;
loader.load('img/metalas.jpg',
function (texture){
var torusGeometry = new THREE.TorusGeometry( 3, 1.2, 6, 100, 6.3 );
var torusMaterial = new THREE.MeshStandardMaterial({ map: texture, overdraw: 0.5 });
var bump = new THREE.TextureLoader().load( "img/metalas.jpg" );
torusMaterial.bumpMap = bump;
torusMaterial.bumpScale = 0.6;
torusMaterial.metalness = 0.1; // non metal 0-1 metal default 0.5
torusMaterial.roughness = 0.8; // mirror 0-1 diffuse default 0.5
torus = new THREE.Mesh(torusGeometry, torusMaterial);
torus.castShadow = true;
torus.material.map.repeat.set(0.5,0.5);
torus.rotation.x=-0.5*Math.PI;
torus.position.x=2;
torus.position.y=-2.48;
torus.position.z=5;
pivot.add( torus );
},
function (xhr) {
console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
},
function ( xhr ) {
console.log( 'Texture metalas.jpg cant be loaded!' );
}
);
scene.add(pivot);
var cylinder;
loader.load('img/metalas.jpg',
function (texture){
var cylinderGeometry = new THREE.CylinderGeometry( 2.2, 2.2, 2, 64, 1 );
var cylinderMaterial = new THREE.MeshStandardMaterial({ map: texture, overdraw: 0.5 });
var bump = new THREE.TextureLoader().load( "img/metalas.jpg" );
cylinderMaterial.bumpMap = bump;
cylinderMaterial.bumpScale = 0.6;
cylinderMaterial.metalness = 0.1; // non metal 0-1 metal default 0.5
cylinderMaterial.roughness = 0.8; // mirror 0-1 diffuse default 0.5
cylinder = new THREE.Mesh(cylinderGeometry, cylinderMaterial);
cylinder.castShadow = true;
cylinder.material.map.repeat.set(0.5,0.5);
//cylinder.rotation.x=-0.5*Math.PI;
cylinder.position.x=2;
cylinder.position.y=-2.48;
cylinder.position.z=5;
pivot.add( cylinder );
},
function (xhr) {
console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
},
function ( xhr ) {
console.log( 'Texture metalas.jpg cant be loaded!' );
}
);
scene.add(pivot);
// renderer.setClearColor(0xFFFFFF);
renderer.setClearColor(0xEEEEEE);
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
//renderer.shadowMap.type = THREE.PCFSoftShadowMap; //THREE.BasicShadowMap | THREE.PCFShadowMap | THREE.PCFSoftShadowMap
// --- 4 ---
container.appendChild( renderer.domElement );
fpsContainer.appendChild( stats.dom );
show();
function show() {
requestAnimationFrame( show );
var delta = clock.getDelta();
camControls.update( delta );
pivot.rotation.y += 0;
What I have now:
WRONG
NEED THIS
Thank you

Related

MTLLoader breaks other 3js code and isn't loading texture right

I am having trouble getting the MTLLoader to work correctly. I have already been able to use the OBJLoader by itself to load the 3d object and I have a camera that works properly too in my scene. When I try and use the MTLLoader with the OBJLoader the object loads but it breaks my other three.js code. I get these errors:
three.js:24415 Uncaught TypeError: Cannot set property 'value' of undefined
at initMaterial (three.js:24415)
at setProgram (three.js:24493)
at WebGLRenderer.renderBufferDirect (three.js:23552)
at renderObject (three.js:24269)
at renderObjects (three.js:24239)
at WebGLRenderer.render (three.js:24037)
at render (demo2.html:480)
The object loads and it looks like some textures load but the textures don't look right, the camera breaks. I have been having trouble with this and could really use some guidance.
Here is my MTLLoader code by itself
var mesh = null;
var mtlLoader = new THREE.MTLLoader();
mtlLoader.load( 'dapHouseGood5.mtl', function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.load( 'dapHouseGood5.obj', function ( object ) {
mesh = object;
scene.add( mesh );
} );
Here is the rest of my three.js code for reference
<script>
/* global THREE */
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas});
const renderer2 = new THREE.WebGLRenderer({canvas});
var kitchenCameraActive = false;
document.getElementById("roomSelect").addEventListener("change", changeIt);
function changeIt(e) {
document.getElementById(e.target.value).click();
console.log(e);
}
var fov = 45;
var aspect = 2; // the canvas default
var near = 0.1;
var far = 100;
var camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(-97.570, 5.878, -5.289);
camera.rotation.set(0,0,0);
const controls = new THREE.OrbitControls(camera, canvas);
controls.target.set(0, 5, 0);
controls.update();
document.getElementById("kitchen").addEventListener("click", changeCamera);
document.getElementById("bathroom").addEventListener("click", changeCamera);
document.getElementById("deck").addEventListener("click", changeCamera);
document.getElementById("livingRoom").addEventListener("click", changeCamera);
document.getElementById("bedRoom").addEventListener("click", changeCamera);
document.getElementById("walkway").addEventListener("click", changeCamera);
document.getElementById("sideHouse").addEventListener("click", changeCamera);
document.getElementById("frontPorch").addEventListener("click", changeCamera);
document.getElementById("garageDoor").addEventListener("click", changeCamera);
document.getElementById("insideGarage").addEventListener("click", changeCamera);
function changeCamera(e) {
camera.rotation.set(e.toElement.attributes[5].nodeValue,
e.toElement.attributes[6].nodeValue, e.toElement.attributes[7].nodeValue);
camera.fov = e.toElement.attributes[4].nodeValue;
camera.position.set(e.toElement.attributes[1].nodeValue,
e.toElement.attributes[2].nodeValue, e.toElement.attributes[3].nodeValue);
camera.updateProjectionMatrix();
if (e.target.id == "walkway" || e.target.id == "frontPorch" || e.target.id ==
"garageDoor" || e.target.id == "insideGarage")
{
controls.target.set(0, 5, 0);
controls.update();
}
if(e.target.id == "kitchen"){
controls.target.set(7, 6, 7);
}
if(e.target.id == "bathroom"){
controls.target.set(-9,15,-7);
}
if(e.target.id == "deck"){
controls.target.set(31, 7, 1);
}
if(e.target.id == "livingRoom"){
controls.target.set(-12.5, 1.5, -18.5);
}
if(e.target.id == "bedRoom"){
controls.target.set(-15.7, 14, -21);
}
if(e.target.id == "insideGarage"){
controls.target.set(24.405, 6.733, -6.425);
}
controls.update();
console.log(e);
}
const scene = new THREE.Scene();
scene.background = new THREE.Color('black');
{
const planeSize = 40;
}
{
const skyColor = 0xB1E1FF; // light blue
const groundColor = 0xB97A20; // brownish orange
const intensity = 1;
const light = new THREE.HemisphereLight(skyColor, groundColor, intensity);
scene.add(light);
}
{
const color = 0xFFFFFF;
const intensity = 1;
const light = new THREE.DirectionalLight(color, intensity);
light.position.set(5, 10, 2);
scene.add(light);
scene.add(light.target);
}
var mesh = null;
var mtlLoader = new THREE.MTLLoader();
mtlLoader.load( 'dapHouseGood5.mtl', function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.load( 'dapHouseGood5.obj', function ( object ) {
mesh = object;
scene.add( mesh );
} );
} );
function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
function render() {
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
function onPositionChange(o) {
console.log("position changed in object");
console.log(o);
console.log('camera_default: '+camera.position.x+', '+camera.position.y+',
'+camera.position.z);
console.log('camera_default: '+camera.rotation.x+', '+camera.rotation.y+',
'+camera.rotation.z);
console.log(camera.fov);
console.log('quaternion_default: '+camera.quaternion.x+', '+
camera.quaternion.y+', '+camera.quaternion.z+', '+camera.quaternion.w);
}
controls.addEventListener('change', onPositionChange);
var mouse = new THREE.Vector2();
var raycaster, mouse = { x : 0, y : 0};
init();
function init () {
//Usual setup code here.
raycaster = new THREE.Raycaster();
renderer.domElement.addEventListener( 'click', raycast, false );
}
function raycast ( e ) {
//1. sets the mouse position with a coordinate system where the center
// of the screen is the origin
mouse.x = ( e.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( e.clientY / window.innerHeight ) * 2 + 1;
//2. set the picking ray from the camera position and mouse coordinates
raycaster.setFromCamera( mouse, camera );
//var mouse3D = new THREE.Vector3( ( event.clientX / window.innerWidth ) * 2 - 1, -(
event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
//raycaster.setFromCamera( mouse3D, camera );
//3. compute intersections
var intersects = raycaster.intersectObjects( scene.children, true );
for ( var i = 0; i < intersects.length; i++ ) {
console.log( intersects[ i ].object.name );
}
}
}
main();
</script>

How to make camera update on zoom

I finally found how to zoom with the mousescroll, but the camera only updates the zoom level when I move the camera by clicking and dragging.
I tried copy pasting code from three.js examples, I tried different browers, I tried adding controls.update(); to both the render and the gameloop function and I tried Googling my issue.
var renderer = new THREE.WebGLRenderer( );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
// check when the browser size has changed and adjust the camera accordingly
window.addEventListener( 'resize', function( )
{
var WIDTH = window.innerWidth;
var HEIGHT = window.innerHeight;
renderer.setSize( WIDTH, HEIGHT );
camera.aspect = WIDTH / HEIGHT;
camera.updateProjectionMatrix( );
} );
scene.add( new THREE.AmbientLight( 0x00020 ) );
var controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.addEventListener( 'change', render ); // use only if there is no animation loop
controls.minDistance = 10;
controls.maxDistance = 200;
controls.enableZoom = true;
camera.position.z = 7;
// CUBE
var geometry = new THREE.CubeGeometry( 2, 2, 2 );
var cubeMaterials =
[
new THREE.MeshLambertMaterial( { map: new THREE.TextureLoader( ).load( 'img/1.png' ), side: THREE.DoubleSide } ), // Right side
new THREE.MeshPhongMaterial( { map: new THREE.TextureLoader( ).load( 'img/2.png' ), side: THREE.DoubleSide } ), // Left side
new THREE.MeshLambertMaterial( { map: new THREE.TextureLoader( ).load( 'img/3.png' ), side: THREE.DoubleSide } ), // Top side
new THREE.MeshPhongMaterial( { map: new THREE.TextureLoader( ).load( 'img/4.png' ), side: THREE.DoubleSide } ), // Bottom side
new THREE.MeshLambertMaterial( { map: new THREE.TextureLoader( ).load( 'img/5.png' ), side: THREE.DoubleSide } ), // Front side
new THREE.MeshPhongMaterial( { map: new THREE.TextureLoader( ).load( 'img/6.png' ), side: THREE.DoubleSide } ) // Back side
];
// Create a MeshFaceMaterial, which allows the cube to have different materials on each face
var cubeMaterial = new THREE.MeshFaceMaterial( cubeMaterials );
var cube = new THREE.Mesh( geometry, cubeMaterial );
scene.add( cube );
// Floor
var floorGeometry = new THREE.CubeGeometry( 496, 1, 350 );
var floorMaterial = new THREE.MeshLambertMaterial( { map: new THREE.TextureLoader( ).load( 'images/ctr.png' ), side: THREE.DoubleSide } );
var floorCube = new THREE.Mesh( floorGeometry, floorMaterial );
floorCube.position.y = -5;
scene.add( floorCube );
var ambientLight = new THREE.AmbientLight( 0xFFFFFF, 5.0 );
scene.add(ambientLight);
var light1 = new THREE.PointLight( 0xff0040, 4, 50 );
//scene.add( light1 );
var light2 = new THREE.PointLight( 0x0040ff, 3, 50 );
//scene.add( light2 );
var light3 = new THREE.PointLight( 0x80ff80, 4, 50 );
//scene.add( light3 );
var directionalLight = new THREE.DirectionalLight( 0xFFFFFF, 1 );
directionalLight.position.set( 0, 1, 0 );
//scene.add( directionalLight );
var spotLight = new THREE.SpotLight( 0xFF45F6, 25 );
spotLight.position.set( 0, 3, 0 );
scene.add( spotLight );
// game logic
var update = function( )
{
//cube.rotation.x += 0.01;
//cube.rotation.y += 0.005;
var time = Date.now( ) * 0.0005;
light1.position.x = Math.sin( time * 0.7 ) * 30;
light1.position.y = Math.cos( time * 0.5 ) * 40;
light1.position.z = Math.cos( time * 0.3 ) * 30;
light2.position.x = Math.cos( time * 0.3 ) * 30;
light2.position.y = Math.sin( time * 0.5 ) * 40;
light2.position.z = Math.sin( time * 0.7 ) * 30;
light3.position.x = Math.sin( time * 0.7 ) * 30;
light3.position.y = Math.cos( time * 0.3 ) * 40;
light3.position.z = Math.sin( time * 0.5 ) * 30;
};
// draw scene
var render = function( )
{
renderer.render( scene, camera );
};
// run game loop (update, render, repeat)
var GameLoop = function( )
{
requestAnimationFrame( GameLoop );
update( );
render( );
};
GameLoop( );
</script>
I would really love to be able to zoom in instantly when I scroll and not have it update only when I perform a pan.

Three.js : remove texture on top/bottom of CylinderGeometry

I'm using Three.js to make basic 3D cylinder rendering. I'm using TextureLoader to load texture async (based on UI interactions).
All is ok, but I would like those textures not to be applied on the cylinder top / bottom.
How can I achieve that?
Here's what I've done so far:
function threeJsRenderer() {
var width = 325;
var height = 375;
var scene = new THREE.Scene();
var camera = new THREE.OrthographicCamera(width / - 2, width / 2, height / 2, height / - 2, -200, 1000);
var renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
renderer.setClearColor( 0x000000, 0 );
renderer.setSize(width,height);
document.getElementById('projection').appendChild(renderer.domElement);
// CylinderGeometry(radiusTop : Float, radiusBottom : Float, height : Float, radialSegments : Integer, heightSegments : Integer, openEnded : Boolean, thetaStart : Float, thetaLength : Float)
var geometry = new THREE.CylinderGeometry(135,128,110,64,1, false, 0, Math.PI-2);
var loader = new THREE.TextureLoader();
var material = new THREE.MeshPhongMaterial();
var cone = new THREE.Mesh();
var pointLight = new THREE.AmbientLight( 0xFFFFFF );
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;
scene.add(pointLight);
camera.position.z = 40;
camera.position.y = 0;
cone.rotation.x = 0.01;
cone.rotation.y = -10;
jQuery(document).on('new3DConfigReady', function () {
scene.remove(cone);
var newGeometry = new THREE.CylinderGeometry(state.cylinderGeometry.radiusTop,state.cylinderGeometry.radiusBottom,state.cylinderGeometry.height,64,1, false, 0, Math.PI-2);;
cone = new THREE.Mesh(newGeometry, material);
cone.rotation.x = 0.01;
cone.rotation.y = -0.55;
cone.position.y = state.cylinderGeometry.positionY;
geometry.dispose();
if(state.textureUrl !== ''){
scene.add(cone);
}
});
jQuery(document).on('newTextureReady', function () {
loader.load( state.textureUrl, function (texture){
material.map = texture;
material.map.anisotropy = 256;
material.map.needsUpdate = true;
material.needsUpdate = true;
scene.add(cone);
});
});
var render = function () {
requestAnimationFrame(render);
renderer.render(scene, camera);
};
render();
}
Using a materials array you can have different materials on the sides and ends of your cylinder.
var geometry = new THREE.CylinderBufferGeometry( 5, 5, 10, 16, 1 );
var materials = [
new THREE.MeshPhongMaterial( { map: texture } ),
new THREE.MeshPhongMaterial( { color: 0x0000ff } ),
new THREE.MeshPhongMaterial( { color: 0xff0000 } )
];
var mesh = new THREE.Mesh( geometry, materials );
three.js r.100

three.js camera tween with switch statement

I am trying to tween a camera in three.js.
I have the following code in my init function.
A switch statement i am passing through an iFrame.
window.onmessage = function(evt) {
switch (evt.data.cameraYpos) {
case 'Ypos01':
var from01 = {
y: camera.position.y
};
var to01 = {
y: yPos01
};
TWEEN.removeAll();
var tween = new TWEEN.Tween(from01)
.to(to01, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function() {
camera.position.set(this.y);
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.onComplete(function() {
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.start();
break;
case 'Ypos02':
var from02 = {
y: camera.position.y
};
var to02 = {
y: yPos02
};
TWEEN.removeAll();
var tween = new TWEEN.Tween(from02)
.to(to02, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function() {
camera.position.set(this.y);
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.onComplete(function() {
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.start();
break;
case 'Ypos03':
var from03 = {
y: camera.position.y
};
var to03 = {
y: yPos03
};
TWEEN.removeAll();
var tween = new TWEEN.Tween(from03)
.to(to03, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function() {
camera.position.set(this.y);
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.onComplete(function() {
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.start();
break;
}
}
In my main website where the iFrame is, I have 3 buttons.
Once one of them is pressed I want the camera to animate to the new Y position.
export function button03_click(event, $w) {
$w("#html2").postMessage({cameraYpos: 'Ypos03'});
console.log("cameraPos = -300");
}
export function button02_click(event, $w) {
$w("#html2").postMessage({cameraYpos: 'Ypos02'});
console.log("cameraPos = 0");
}
export function button01_click(event, $w) {
$w("#html2").postMessage({cameraYpos: 'Ypos01'});
console.log("cameraPos = 300");
}
This is my animate function
function animate() {
TWEEN.update();
requestAnimationFrame(animate);
render();
}
and this is my render function
function render() {
camera.lookAt(scene.position);
camera.position.x += ( - mouseX - camera.position.x ) * 0.05;
camera.lookAt( scene.position );
webglRenderer.render(scene, camera);
}
I manged to get it working with out a tween but now with the tween set
as soon as I press one of the buttons the model disappears from view.
I am sorry for not having a live version I am under strict NDA and switching the models just for this is allot of work. hope you understand.
Any help is most appreciated.
Thanks
You can see the full code here
<script>
/* Global vars
---------------------------------------------------
*/
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var camera, scene;
var canvasRenderer, webglRenderer;
var models_loaded = false;
var textures_loaded = false;
var container, mesh, geometry, loader, preloader;
var cameraPos
var yPos01 = 300;
var yPos02 = 0;
var yPos03 = -300;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var light;
var mouseX = 0, mouseY = 0;
/*
---------------------------------------------------
*/
/* Global materials and lighting controls
---------------------------------------------------
*/
//material
var roughness = 0.83;
var metal = 0.8;
var diffuse = 0x675f00;
//lights
var environmentInt = 0.5;
var ambiLightInt = 0.2;
var dirLightInt = 1.2;
var dirLightScalar = 1;
var hemiLightInt = 1;
/*
---------------------------------------------------
*/
/* Page Preloader
---------------------------------------------------
*/
preloader = document.createElement('img');
preloader.onload = function(){
window.addEventListener("mousemove", onmousemove, false);
init();
animate();
}
preloader.src = "https://assets.parastorage.com/marketingstudio/jessica_walsh/06/textures_512/preloader.gif";
preloader.className = "preloader";
document.body.appendChild(preloader);
/*
---------------------------------------------------
*/
/* init start
-----------------------------------------------------------------------------------------------------------------------------
*/
function init() {
/* 3D Json Loader
---------------------------------------------------
*/
container = document.createElement('div');
container.className = 'container';
container.style.visibility = 'hidden';
document.body.appendChild(container);
var manager = new THREE.LoadingManager();
manager.onStart = function ( url, itemsLoaded, itemsTotal ) {
console.log( 'Started loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' );
};
function onComplete(){
if(models_loaded && textures_loaded){
document.body.removeChild(preloader);
container.style.visibility = 'visible';
container.style.opacity =1;
SITE_BACKGROUNDcurrentVideovideo.play();
console.log( 'Loading completed');
}
}
manager.onLoad = function ( ) {
models_loaded = true;
onComplete();
};
manager.onProgress = function ( url, itemsLoaded, itemsTotal ) {
//console.log( 'Loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' );
};
manager.onError = function ( url ) {
//console.log( 'There was an error loading ' + url );
};
loader = new THREE.JSONLoader(manager);
/*
---------------------------------------------------
*/
/* Creating the camera
---------------------------------------------------
*/
camera = new THREE.PerspectiveCamera(20, window.innerWidth / window.innerHeight, 10, 1500);
camera.position.z = 340;
/* Passing event through the iframe
---------------------------------------------------
*/
window.onmessage = function (evt) {
switch (evt.data.cameraYpos) {
case 'Ypos01':
var from01 = {y: camera.position.y};
var to01 = {y: yPos01};
TWEEN.removeAll();
var tween01 = new TWEEN.Tween(from01)
.to(to01, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function () {
camera.position.set(this.y);
camera.lookAt(0, 0, 0);
})
.onComplete(function () {
camera.lookAt(0, 0, 0);
})
.start();
break;
case 'Ypos02':
var from02 = {y: camera.position.y};
var to02 = {y: yPos02};
TWEEN.removeAll();
var tween02 = new TWEEN.Tween(from02)
.to(to02, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function () {
camera.position.set(this.y);
camera.lookAt(0, 0, 0);
})
.onComplete(function () {
camera.lookAt(0, 0, 0);
})
.start();
break;
case 'Ypos03':
var from03 = {y: camera.position.y};
var to03 = {y: yPos03};
TWEEN.removeAll();
var tween03 = new TWEEN.Tween(from03)
.to(to03, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function () {
camera.position.set(this.y);
camera.lookAt(0, 0, 0);
})
.onComplete(function () {
camera.lookAt(0, 0, 0);
})
.start();
break;
}
};
/* Bulding the scene
---------------------------------------------------
*/
scene = new THREE.Scene();
//Lights
scene.add(new THREE.AmbientLight(0xffffff, ambiLightInt));
/* Main light
---------------------------------------------------
*/
light = new THREE.DirectionalLight(0xffffff, dirLightInt);
//light.position.set(100, -350, 0);
light.position.multiplyScalar(dirLightScalar);
//light.position.x = 100;
light.position.y = 100;
light.position.z = 100;
//Shadow parameters
light.castShadow = true;
light.shadowCameraVisible = true;
//light.shadowBias = 0.001;
light.shadowMapWidth = 1024;
light.shadowMapHeight = 1024;
//Shadow camera fov and position
var d = 50;
light.shadowCameraLeft = -d;
light.shadowCameraRight = d;
light.shadowCameraTop = d;
light.shadowCameraBottom = -d;
light.shadowcameranear = 0.1;
light.shadowCameraFar = 2000;
light.shadowcamerafov = 30;
light.shadowDarkness = 0;
scene.add(light);
/*
---------------------------------------------------
*/
//Skylight
var skylight = new THREE.HemisphereLight( 0xffffff, 0x080820, hemiLightInt );
scene.add( skylight );
/* Texture Loader
---------------------------------------------------
*/
var tx_manager = new THREE.LoadingManager();
tx_manager.onStart = function ( url, itemsLoaded, itemsTotal ) {
//console.log(itemsTotal);
//console.log( 'Started loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' );
};
var total_textures = 0
tx_manager.itemEnd=function (url){
total_textures++;
if(total_textures == 20){
textures_loaded = true;
onComplete();
}
//console.log(++total_textures);
}
tx_manager.onLoad = function ( x) {
console.log(textureLoader);
//console.log( 'tx_manager complete!');
};
var textureLoader = new THREE.TextureLoader(tx_manager);
/*
---------------------------------------------------
*/
/* Environment map images
---------------------------------------------------
*/
var envUrls = [
'textures/env/02/px.jpg',
'textures/env/02/nx.jpg',
'textures/env/02/py.jpg',
'textures/env/02/ny.jpg',
'textures/env/02/pz.jpg',
'textures/env/02/nz.jpg'
],
// wrap it up into the object that we need
cubemap = THREE.ImageUtils.loadTextureCube(envUrls);
// set the format, likely RGB unless you've gone crazy
cubemap.format = THREE.RGBFormat;
/*
---------------------------------------------------
*/
/* 3D Json files loading
---------------------------------------------------
*/
// TRUNK 01
loader.load( "models/trunk_01.json", function( geometry, mat ) {
//var trunk_color = 0x0061ff;
//var trunk_01_color = textureLoader.load( "textures/trunk_01_curvature.jpg" );
var trunk_01_normal = textureLoader.load( "textures_512/trunk_01_normal.jpeg" );
var trunk_01_roughness = textureLoader.load( "textures_512/trunk_01_roughness.jpeg" );
trunk_01_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: trunk_01_roughness,
normalMap: trunk_01_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var trunk_01 = new THREE.Mesh( geometry, mat );
trunk_01.material = trunk_01_Material;
trunk_01.scale.set( 1, 1, 1 );
trunk_01.position.x = 0;
trunk_01.position.z = 0;
trunk_01.position.x = 0;
trunk_01.castShadow = true;
trunk_01.receiveShadow = true;
trunk_one = trunk_01;
scene.add( trunk_01 );
//controls_01 = new THREE.DeviceOrientationControls(trunk_one, true);
} );
// TRUNK 02
loader.load( "models/trunk_02.json", function( geometry, mat ) {
//var trunk_02_color = textureLoader.load( "textures/trunk_02_curvature.jpg" );
var trunk_02_normal = textureLoader.load( "textures_512/trunk_02_normal.jpeg" );
var trunk_02_roughness = textureLoader.load( "textures_512/trunk_02_roughness.jpg" );
trunk_02_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: trunk_02_roughness,
normalMap: trunk_02_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var trunk_02 = new THREE.Mesh( geometry, mat );
trunk_02.material = trunk_02_Material;
trunk_02.scale.set( 1, 1, 1 );
trunk_02.position.x = 0;
trunk_02.position.z = 0;
trunk_02.position.x = 0;
trunk_02.castShadow = true;
trunk_02.receiveShadow = true;
trunk_two = trunk_02;
scene.add( trunk_02 );
//controls_02 = new THREE.DeviceOrientationControls(trunk_two, true);
} );
// LEAFS
loader.load( "models/leafs.json", function( geometry, mat ) {
//var leafs_color = textureLoader.load( "textures/leafs_curvature.jpg" );
var leafs_normal = textureLoader.load( "textures_512/leafs_normal.jpeg" );
var leafs_roughness = textureLoader.load( "textures_512/leafs_roughness.jpeg" );
leafs_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: leafs_roughness,
normalMap: leafs_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var leafs = new THREE.Mesh( geometry, mat );
leafs.material = leafs_Material;
leafs.scale.set( 1, 1, 1 );
leafs.position.x = 0;
leafs.position.z = 0;
leafs.position.x = 0;
leafs.castShadow = true;
leafs.receiveShadow = true;
all_leafs = leafs;
scene.add( leafs );
//controls_03 = new THREE.DeviceOrientationControls(all_leafs, true);
} );
// ROSES
loader.load( "models/roses.json", function( geometry, mat ) {
//var roses_color = textureLoader.load( "textures/roses_curvature.jpg" );
var roses_normal = textureLoader.load( "textures_512/roses_normal.jpeg" );
var roses_roughness = textureLoader.load( "textures_512/roses_roughness.jpeg" );
roses_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: roses_roughness,
normalMap: roses_normal,
normalScale: new THREE.Vector2( 0.7, 0.7 ),
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var roses = new THREE.Mesh( geometry, mat );
roses.material = roses_Material;
roses.scale.set( 1, 1, 1 );
roses.position.x = 0;
roses.position.z = 0;
roses.position.x = 0;
roses.castShadow = true;
roses.receiveShadow = true;
all_roses = roses;
scene.add( roses );
//controls_04 = new THREE.DeviceOrientationControls(all_roses, true);
} );
// TOPS
loader.load( "models/tops.json", function( geometry, mat ) {
//var tops_color = textureLoader.load( "textures/tops_curvature.jpg" );
var tops_normal = textureLoader.load( "textures_512/tops_normal.jpeg" );
var tops_roughness = textureLoader.load( "textures_512/tops_roughness.jpeg" );
tops_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: tops_roughness,
normalMap: tops_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var tops = new THREE.Mesh( geometry, mat );
tops.material = tops_Material;
tops.scale.set( 1, 1, 1 );
tops.position.x = 0;
tops.position.z = 0;
tops.position.x = 0;
tops.castShadow = true;
tops.receiveShadow = true;
all_tops = tops;
scene.add( tops );
//controls_05 = new THREE.DeviceOrientationControls(all_tops, true);
} );
// STEMS
loader.load( "jessica_walsh/06/models/stems.json", function( geometry, mat ) {
//var stems_color = textureLoader.load( "textures/stems_curvature.jpg" );
var stems_normal = textureLoader.load( "textures_512/stems_normal.jpeg" );
var stems_roughness = textureLoader.load( "textures_512/stems_roughness.jpeg" );
stems_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: stems_roughness,
normalMap: stems_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var stems = new THREE.Mesh( geometry, mat );
stems.material = stems_Material;
stems.scale.set( 1, 1, 1 );
stems.position.x = 0;
stems.position.z = 0;
stems.position.x = 0;
stems.castShadow = true;
stems.receiveShadow = true;
all_stems = stems;
scene.add( stems );
//controls_06 = new THREE.DeviceOrientationControls(all_stems, true);
} );
// THORNES 01
loader.load( "models/thornes_01.json", function( geometry, mat ) {
//var thornes_01_color = textureLoader.load( "textures/thornes_01_curvature.jpg" );
var thornes_01_normal = textureLoader.load( "textures_512/thornes_01_normal.jpeg" );
var thornes_01_roughness = textureLoader.load( "textures_512/thornes_01_roughness.jpeg" );
thornes_01_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: thornes_01_roughness,
normalMap: thornes_01_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var thornes_01 = new THREE.Mesh( geometry, mat );
thornes_01.material = thornes_01_Material;
thornes_01.scale.set( 1, 1, 1 );
thornes_01.position.x = 0;
thornes_01.position.z = 0;
thornes_01.position.x = 0;
thornes_01.castShadow = true;
thornes_01.receiveShadow = true;
thornes_one = thornes_01;
scene.add( thornes_01 );
//controls_07 = new THREE.DeviceOrientationControls(thornes_one, true);
} );
// THORNES 02
loader.load( "models/thornes_02.json", function( geometry, mat ) {
//var thornes_02_color = textureLoader.load( "textures/thornes_02_curvature.jpg" );
var thornes_02_normal = textureLoader.load( "textures_512/thornes_02_normal.jpeg" );
var thornes_02_roughness = textureLoader.load( "textures_512/thornes_02_roughness.jpeg" );
thornes_02_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: thornes_02_roughness,
normalMap: thornes_02_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var thornes_02 = new THREE.Mesh( geometry, mat );
thornes_02.material = thornes_02_Material;
thornes_02.scale.set( 1, 1, 1 );
thornes_02.position.x = 0;
thornes_02.position.z = 0;
thornes_02.position.x = 0;
thornes_02.castShadow = true;
thornes_02.receiveShadow = true;
thornes_two = thornes_02;
scene.add( thornes_02 );
//controls_08 = new THREE.DeviceOrientationControls(thornes_two, true);
} );
// SNAKE BOSY
loader.load( "models/snake_body.json", function( geometry, mat ) {
//var snake_body_color = textureLoader.load( "textures/snake_body_curvature.jpg" );
var snake_body_normal = textureLoader.load( "textures_512/snake_body_normal.jpeg" );
var snake_body_roughness = textureLoader.load( "textures_512/snake_body_roughness.jpg" );
snake_body_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: snake_body_roughness,
normalMap: snake_body_normal,
normalScale: new THREE.Vector2( 1.5, 1.5 ),
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var snake_body = new THREE.Mesh( geometry, mat );
snake_body.material = snake_body_Material;
snake_body.scale.set( 1, 1, 1 );
snake_body.position.x = 0;
snake_body.position.z = 0;
snake_body.position.x = 0;
snake_body.castShadow = true;
snake_body.receiveShadow = true;
snake_b = snake_body;
scene.add( snake_body );
//controls_09 = new THREE.DeviceOrientationControls(snake_b, true);
} );
// SNAKE HEAD
loader.load( "models/snake_head.json", function( geometry, mat ) {
//var snake_head_color = textureLoader.load( "textures/snake_head_curvature.jpg" );
var snake_head_normal = textureLoader.load( "textures_512/snake_head_normal.jpeg" );
var snake_head_roughness = textureLoader.load( "textures_512/snake_head_roughness.jpeg" );
snake_head_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: snake_head_roughness,
normalMap: snake_head_normal,
normalScale: new THREE.Vector2( 2, 2 ),
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var snake_head = new THREE.Mesh( geometry, mat );
snake_head.material = snake_head_Material;
snake_head.scale.set( 1, 1, 1 );
snake_head.position.x = 0;
snake_head.position.z = 0;
snake_head.position.x = 0;
snake_head.castShadow = true;
snake_head.receiveShadow = true;
snake_h = snake_head;
scene.add( snake_head );
//controls_10 = new THREE.DeviceOrientationControls(snake_h, true);
} );
/* 3D Json files end
---------------------------------------------------
*/
// RENDERER
webglRenderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
webglRenderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
webglRenderer.domElement.style.position = "relative";
webglRenderer.shadowMapEnabled = true;
//webglRenderer.shadowMapSoft = true;
webglRenderer.shadowMapType = THREE.PCFSoftShadowMap; // options are THREE.BasicShadowMap | THREE.PCFShadowMap | THREE.PCFSoftShadowMap
container.appendChild(webglRenderer.domElement);
window.addEventListener('resize', onWindowResize, false);
}
/* init end
-----------------------------------------------------------------------------------------------------------------------------
*/
/* Mouse mapping
---------------------------------------------------
*/
function onmousemove(event) {
//mouseX = (event.clientX / window.innerWidth) * 2 - 1;
//mouseY = -(event.clientY / window.innerHeight) * 2 + 1;
mouseX = ( event.clientX - windowHalfX ) / 6;
mouseY = ( event.clientY - windowHalfY ) / 4;
}
/*
---------------------------------------------------
*/
/* Window resize
---------------------------------------------------
*/
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
var f = (camera.aspect/1.583);
if(f < 1){
camera.position.z = 340 /(camera.aspect/1.583);
}else{
camera.position.z = 340;
}
camera.updateProjectionMatrix();
webglRenderer.setSize(window.innerWidth, window.innerHeight);
}
/*
---------------------------------------------------
*/
/* Animate
---------------------------------------------------
*/
function animate() {
TWEEN.update();
requestAnimationFrame(animate);
render();
}
/*
---------------------------------------------------
*/
/* Render
---------------------------------------------------
*/
function render() {
camera.lookAt(scene.position);
camera.position.x += ( - mouseX - camera.position.x ) * 0.05;
camera.lookAt( scene.position );
//Light Position
light.position.x += ( - mouseX - camera.position.x ) * 0.03;
light.lookAt( scene.position );
webglRenderer.render(scene, camera);
}
/*
---------------------------------------------------
*/
</script>
As seeinvisible said the tween is passing an object
with all 3 parameters and I tried to pass only the Y.
This is my updated tween
var from01 = {y: camera.position.y, z: camera.position.z};
var to01 = {y: yPos01, z: zPos01};
TWEEN.removeAll();
var tween = new TWEEN.Tween(from01)
.to(to01, 600)
.easing(TWEEN.Easing.Quadratic.InOut)
.onUpdate(function () {
camera.position.set(camera.position.x, this.y, this.z);
camera.lookAt(0, 0, 0);
})
.onComplete(function () {
camera.lookAt(0, 0, 0);
})
.start();
In your onUpdate function you have camera.position.set(this.y). However that seems to take 3 parameters x, y, z. Try camera.position.setY(this.y) to only set the y value.

Three.js Restrict the mouse movement to Scene only

I am working on the cube example from three.js (webgl_interactive_cubes_gpu.html). I realized that events goes to the entire html page. I mean i can rotate, zoom in or zoom out, even if the mouse pointer is not inside the scene..
I google a little bit and found some answers (Allow mouse control of three.js scene only when mouse is over canvas) but they do not work for me..Below is my code...
var container, stats;
var camera, controls, scene, renderer;
var pickingData = [], pickingTexture, pickingScene;
var objects = [];
var highlightBox;
var mouse = new THREE.Vector2();
var offset = new THREE.Vector3( 10, 10, 10 );
init();
animate();
function init() {
container = document.getElementById( "container" );
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 1000;
//camera.translateZ( -500 );
controls = new THREE.TrackballControls(camera);
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 4;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
scene = new THREE.Scene();
pickingScene = new THREE.Scene();
pickingTexture = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight );
pickingTexture.minFilter = THREE.LinearFilter;
pickingTexture.generateMipmaps = false;
scene.add( new THREE.AmbientLight( 0x555555 ));
var light = new THREE.SpotLight( 0xffffff, 1.5 );
light.position.set( 0, 500, 2000 );
scene.add( light );
var geometry = new THREE.Geometry(),
pickingGeometry = new THREE.Geometry(),
pickingMaterial = new THREE.MeshBasicMaterial( { vertexColors: THREE.VertexColors } ),
defaultMaterial = new THREE.MeshLambertMaterial({ color: 0xffffff, shading: THREE.FlatShading, vertexColors: THREE.VertexColors} );
function applyVertexColors( g, c ) {
g.faces.forEach( function( f ) {
var n = ( f instanceof THREE.Face3 ) ? 3 : 4;
for( var j = 0; j < n; j ++ ) {
f.vertexColors[ j ] = c;
}
} );
}
var geom = new THREE.BoxGeometry(0.005, 0.005, 0.005 );
var color = new THREE.Color();
var matrix = new THREE.Matrix4();
var quaternion = new THREE.Quaternion();
var coord="219_163_189;130_173_179;161_113_231;
var splitCoord=coord.split(";");
var coordColr="0_255_255;255_255_0;0_0_255;0_255_0;255_255_0;
var splitCoordColor=coordColr.split(";");
for ( var i = 0; i < splitCoord.length; i++ ) {
var position = new THREE.Vector3();
var xyz=splitCoord[i].split("_");
var col=splitCoordColor[i].split("_");
position.x = xyz[0];
position.y = xyz[1];
position.z = xyz[2];
var rotation = new THREE.Euler();
rotation.x = 0
rotation.y = 0;
rotation.z = 0;
var scale = new THREE.Vector3();
scale.x = 200 + 100;
scale.y = 200 + 100;
scale.z = 200 + 100;
quaternion.setFromEuler(rotation, false );
matrix.compose( position, quaternion, scale);
col[0]=col[0]/255;
col[1]=col[1]/255;
col[2]=col[2]/255;
applyVertexColors(geom, color.setRGB(col[0], col[1], col[2]));
geometry.merge(geom, matrix);
// give the geom's vertices a color corresponding to the "id"
applyVertexColors( geom, color.setHex( i ) );
pickingGeometry.merge( geom, matrix );
pickingData[ i ] = {
position: position,
rotation: rotation,
scale: scale
};
}
var drawnObject = new THREE.Mesh( geometry, defaultMaterial );
scene.add(drawnObject);
pickingScene.add( new THREE.Mesh( pickingGeometry, pickingMaterial ) );
highlightBox = new THREE.Mesh(
new THREE.BoxGeometry( 0.01, 0.01, 0.01 ),
new THREE.MeshLambertMaterial( { color: 0xffff00 }
) );
scene.add( highlightBox );
renderer = new THREE.WebGLRenderer( );
//renderer.setClearColor( 0xffffff );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize(800, 800);
renderer.sortObjects = false;
container.appendChild(renderer.domElement);
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild( stats.domElement );
//renderer.domElement.addEventListener('mousemove', onMouseMove );
}
function onMouseMove( e ) {
mouse.x = e.clientX;
mouse.y = e.clientY;
}
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function pick() {
//render the picking scene off-screen
renderer.render( pickingScene, camera, pickingTexture );
//create buffer for reading single pixel
var pixelBuffer = new Uint8Array( 4 );
//read the pixel under the mouse from the texture
renderer.readRenderTargetPixels(pickingTexture, mouse.x, pickingTexture.height - mouse.y, 1, 1, pixelBuffer);
//interpret the pixel as an ID
var id = ( pixelBuffer[0] << 16 ) | ( pixelBuffer[1] << 8 ) | ( pixelBuffer[2] );
var data = pickingData[ id ];
if (data) {
//move our highlightBox so that it surrounds the picked object
if ( data.position && data.rotation && data.scale ){
highlightBox.position.copy( data.position );
highlightBox.rotation.copy( data.rotation );
highlightBox.scale.copy( data.scale ).add( offset );
highlightBox.visible = true;
}
} else {
highlightBox.visible = false;
}
}
function render() {
controls.update();
pick();
renderer.render( scene, camera );
}
any help is greatly appreciated..
Thanks
You can pass in the canvas as an argument to the TrackballsControls constructor.
var controls = new THREE.TrackballControls(camera, renderer.domElement);
That should solve the problem.
EDIT: included a working example,
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, 400 / 300, 1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(400, 300);
document.body.appendChild(renderer.domElement);
var controls = new THREE.TrackballControls(camera, renderer.domElement);
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 4;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshBasicMaterial({
color: 0x00ff00
});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
var render = function() {
requestAnimationFrame(render);
controls.update();
cube.rotation.x += 0.1;
cube.rotation.y += 0.1;
renderer.render(scene, camera);
};
render();
could not get your code to run at all so..

Resources