I'm trying to load a 3D globe into my HTML site using a ThreeJS script (found below) But it's stitched together with code from other sources, meaning the camera is mapped to MouseX and MouseY positions. I want the object to sit in the center of the page with a simple slow spin, but every time I try and achieve this the object vanishes.
The Javascript:
<script>
var container;
var camera, scene, renderer;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 5, window.innerWidth / window.innerHeight, 1, 5000 );
camera.position.z = 250;
scene = new THREE.Scene();
var ambientLight = new THREE.AmbientLight( 0xcccccc, 0.8 );
scene.add( ambientLight );
var pointLight = new THREE.PointLight( 0xFFF1CF, 0.6 , 0 );
camera.add( pointLight );
scene.add( camera );
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
console.log( item, loaded, total );
};
var onProgress = function ( xhr ) {
if ( xhr.lengthComputable ) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log( Math.round(percentComplete, 2) + '% downloaded' );
}
};
var onError = function ( xhr ) {;
};
var mtlLoader = new THREE.MTLLoader();
mtlLoader.load('planet.mtl', function(materials) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.load('planet.obj', function(object) {
object.position.y = 0;
scene.add(object);
}, onProgress, onError);
});
//
renderer = new THREE.WebGLRenderer( {alpha: true});
renderer.setClearColor( 0x000000, 0 );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
document.addEventListener( 'mouseclick', onmousedown, 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 );
mouseY = ( event.clientY );
}
//
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
camera.position.x += ( mouseX - camera.position.x ) * .05;
camera.position.y += ( - mouseY - camera.position.y ) * .05;
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
</script>
You need to change your code a little bit,
In the 'init' function, change the object loading logic as follows
var mtlLoader = new THREE.MTLLoader();
var objLoader = new THREE.OBJLoader();
mtlLoader.load( 'planet.mtl', function(materials) {
materials.preload();
objLoader.setMaterials(materials);
objLoader.load( 'planet.obj', function( object ){
object.position.set( 0, 0, 0 ); // set the position as (0,0,0)
globe = object; // globe is the object to be added to the scene
scene.add(globe);
animate(); //call the animate function only after the object is loaded
}, onProgress, onError);
} );
And change the render method,
function render() {
globe.rotation.y += 0.01; // this will rotate the object
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
Related
I have a problem with ThreeJS giving me this error message. I included all the necessary ThreeJS files but still this message appears. My intention is to have a mobile device navigating with DeviceOrientationControl.js. Mousemove works very well, but I can't get this to work. Any ideas?
Uncaught TypeError: THREE.DeviceOrientationControls is not a constructor
at init ((index):201)
at (index):193
Error Message
<script type="module">
import * as THREE from '/bftest/three/build/three.module.js';
import {OrbitControls} from '/bftest/three/examples/jsm/controls/OrbitControls.js';
import {GLTFLoader} from '/bftest/three/examples/jsm/loaders/GLTFLoader.js';
import {DeviceOrientationControls} from '/bftest/three/examples/jsm/controls/DeviceOrientationControls.js';
var camera, scene, renderer, 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;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera(45, width / height, 0.1, 1000);
controls = new THREE.DeviceOrientationControls(camera);
camera.position.set(0, 0, 8);
scene = new THREE.Scene();
var directionalLight = new THREE.DirectionalLight(0xffffff, 5);
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;
directionalLight.shadow.camera.left = -20;
directionalLight.shadow.camera.right = 20;
directionalLight.shadow.camera.top = 20;
directionalLight.shadow.camera.bottom = -20;
directionalLight.shadow.camera.near = 1;
directionalLight.shadow.camera.far = 200;
directionalLight.shadowCameraVisible = true;
var spotLight1 = new THREE.DirectionalLight( 0xff4000 );
spotLight1.position.set( -15, 3, -4 );
spotLight1.target.position.set( 0, 1, 0 );
spotLight1.intensity = 1.2;
spotLight1.shadowDarkness = 0.5;
spotLight1.shadowcameranear = 0;
spotLight1.shadowcamerafar = 15;
spotLight1.shadowcameraleft = -5;
spotLight1.shadowcameraright = 5;
spotLight1.shadowcameratop = 5;
spotLight1.shadowcamerabottom = -5;
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 );
var hemisphereLight = new THREE.HemisphereLight(0xffffff,0x000000, .5)
var shadowLight = new THREE.DirectionalLight(0xff8f16, .4);
shadowLight.position.set(50, 0, 22);
shadowLight.target.position.set(50, 50, 0);
shadowLight.rotation.set(Math.PI / -2, 0, 0);
shadowLight.shadow.camera.near = 0.5;
shadowLight.shadow.camera.far = 5000;
shadowLight.shadow.camera.left = -500;
shadowLight.shadow.camera.bottom = -500;
shadowLight.shadow.camera.right = 500;
shadowLight.shadow.camera.top = 500;
scene.add(shadowLight);
var light2 = new THREE.DirectionalLight(0xfff150, .25);
light2.position.set(-600, 350, 350);
var light3 = new THREE.DirectionalLight(0xfff150, .15);
light3.position.set(0, -250, 300);
scene.add(hemisphereLight);
scene.add(shadowLight);
const gltfLoader = new GLTFLoader();
gltfLoader.load('./3D/Bobby.glb', (gltf) => {
const root = gltf.scene;
root.rotateY(-89.55);
root.position.set(0, -0.7, 0);
root.castShadow = true;
gltf.scene.traverse(function(node) {
if (node instanceof THREE.Mesh) {
node.castShadow = true;
}
});
scene.add(root);//default is false
// compute the box that contains all the stuff
// from root and below
const box = new THREE.Box3().setFromObject(root);
const boxSize = box.getSize(new THREE.Vector3()).length();
const boxCenter = box.getCenter(new THREE.Vector3());
// set the camera to frame the box
frameArea(boxSize * 0.7, boxSize, boxCenter, camera);
box.castShadow = true;
// update the Trackball controls to handle the new size
controls.maxDistance = boxSize * 10;
controls.target.copy(boxCenter);
});
renderer = new THREE.WebGLRenderer({ antialias: true, canvas: document.querySelector('canvas'), alpha: true, });
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
window.addEventListener( 'resize', onWindowResize, false );
window.addEventListener('mousemove', onDocumentMouseMove, false);
}
function onDocumentMouseMove(event) {
mouseX = - (event.clientX - windowHalfX) /150;
mouseY = - (event.clientY - windowHalfY) /150;
}
function animate() {
requestAnimationFrame(animate);
render(scene,camera);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function render() {
camera.position.x += (mouseX - camera.position.x)*0.9;
camera.position.y += (-mouseY - camera.position.y)*0.9;
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
</script>
When importing examples files like DeviceOrientationControls via ES6 modules, using the THREE namespace is not necessary anymore. So instead of
controls = new THREE.DeviceOrientationControls(camera);
use
controls = new DeviceOrientationControls(camera);
i am using google Chrome (59.0.3071.125) in my mobile
i was Enabled : WebVR , Gamepad in my chrome using chrome://flags/ to support WEBVR when i tried first time it worked
BUT after 2 days now its givig this exception:
Uncaught (in promise) DOMException: Presentation request was denied.
I have no clue why.
i tried to search around but i found nothing
below is the code of https://threejs.org/examples/?q=vr#webvr_cubes i have tried
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webvr - cubes</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<!-- Origin Trial Token, feature = WebVR, origin = https://threejs.org, expires = 2017-06-13 -->
<meta http-equiv="origin-trial" data-feature="WebVR" data-expires="2017-06-13" content="ApAQvHfiHMQB7SmRhfvCUX61adJaTA6pAu0Ry439jjeipa5lGm1RcTQynFoHGGcaSJkWfMOv7qK6pwSUb95ClQgAAABKeyJvcmlnaW4iOiJodHRwczovL3RocmVlanMub3JnOjQ0MyIsImZlYXR1cmUiOiJXZWJWUiIsImV4cGlyeSI6MTQ5NzMxMjAwMH0=">
<style>
body {
font-family: Monospace;
background-color: #101010;
color: #fff;
margin: 0px;
overflow: hidden;
}
a {
color: #f00;
}
</style>
</head>
<body>
<script src="../build/three.js"></script>
<script src="js/controls/VRControls.js"></script>
<script src="js/effects/VREffect.js"></script>
<script src="js/vr/WebVR.js"></script>
<script>
if ( WEBVR.isAvailable() === false ) {
document.body.appendChild( WEBVR.getMessage() );
}
//
var clock = new THREE.Clock();
var container;
var camera, scene, raycaster, renderer;
var effect, controls;
var room;
var isMouseDown = false;
var INTERSECTED;
var crosshair;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
var info = document.createElement( 'div' );
info.style.position = 'absolute';
info.style.top = '10px';
info.style.width = '100%';
info.style.textAlign = 'center';
info.innerHTML = 'three.js webgl - interactive cubes';
container.appendChild( info );
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.1, 10 );
scene.add( camera );
crosshair = new THREE.Mesh(
new THREE.RingGeometry( 0.02, 0.04, 32 ),
new THREE.MeshBasicMaterial( {
color: 0xffffff,
opacity: 0.5,
transparent: true
} )
);
crosshair.position.z = - 2;
camera.add( crosshair );
room = new THREE.Mesh(
new THREE.BoxGeometry( 6, 6, 6, 8, 8, 8 ),
new THREE.MeshBasicMaterial( { color: 0x404040, wireframe: true } )
);
scene.add( room );
scene.add( new THREE.HemisphereLight( 0x606060, 0x404040 ) );
var light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 1, 1, 1 ).normalize();
scene.add( light );
var geometry = new THREE.BoxGeometry( 0.15, 0.15, 0.15 );
for ( var i = 0; i < 200; i ++ ) {
var object = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { color: Math.random() * 0xffffff } ) );
object.position.x = Math.random() * 4 - 2;
object.position.y = Math.random() * 4 - 2;
object.position.z = Math.random() * 4 - 2;
object.rotation.x = Math.random() * 2 * Math.PI;
object.rotation.y = Math.random() * 2 * Math.PI;
object.rotation.z = Math.random() * 2 * Math.PI;
object.scale.x = Math.random() + 0.5;
object.scale.y = Math.random() + 0.5;
object.scale.z = Math.random() + 0.5;
object.userData.velocity = new THREE.Vector3();
object.userData.velocity.x = Math.random() * 0.01 - 0.005;
object.userData.velocity.y = Math.random() * 0.01 - 0.005;
object.userData.velocity.z = Math.random() * 0.01 - 0.005;
room.add( object );
}
raycaster = new THREE.Raycaster();
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setClearColor( 0x505050 );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.sortObjects = false;
container.appendChild( renderer.domElement );
controls = new THREE.VRControls( camera );
effect = new THREE.VREffect( renderer );
WEBVR.getVRDisplay( function ( display ) {
document.body.appendChild( WEBVR.getButton( display, renderer.domElement ) );
} );
renderer.domElement.addEventListener( 'mousedown', onMouseDown, false );
renderer.domElement.addEventListener( 'mouseup', onMouseUp, false );
renderer.domElement.addEventListener( 'touchstart', onMouseDown, false );
renderer.domElement.addEventListener( 'touchend', onMouseUp, false );
//
window.addEventListener( 'resize', onWindowResize, false );
}
function onMouseDown() {
isMouseDown = true;
}
function onMouseUp() {
isMouseDown = false;
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
effect.setSize( window.innerWidth, window.innerHeight );
}
//
function animate() {
effect.requestAnimationFrame( animate );
render();
}
function render() {
var delta = clock.getDelta() * 60;
if ( isMouseDown === true ) {
var cube = room.children[ 0 ];
room.remove( cube );
cube.position.set( 0, 0, - 0.75 );
cube.position.applyQuaternion( camera.quaternion );
cube.userData.velocity.x = ( Math.random() - 0.5 ) * 0.02 * delta;
cube.userData.velocity.y = ( Math.random() - 0.5 ) * 0.02 * delta;
cube.userData.velocity.z = ( Math.random() * 0.01 - 0.05 ) * delta;
cube.userData.velocity.applyQuaternion( camera.quaternion );
room.add( cube );
}
// find intersections
raycaster.setFromCamera( { x: 0, y: 0 }, camera );
var intersects = raycaster.intersectObjects( room.children );
if ( intersects.length > 0 ) {
if ( INTERSECTED != intersects[ 0 ].object ) {
if ( INTERSECTED ) INTERSECTED.material.emissive.setHex( INTERSECTED.currentHex );
INTERSECTED = intersects[ 0 ].object;
INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex();
INTERSECTED.material.emissive.setHex( 0xff0000 );
}
} else {
if ( INTERSECTED ) INTERSECTED.material.emissive.setHex( INTERSECTED.currentHex );
INTERSECTED = undefined;
}
// Keep cubes inside room
for ( var i = 0; i < room.children.length; i ++ ) {
var cube = room.children[ i ];
cube.userData.velocity.multiplyScalar( 1 - ( 0.001 * delta ) );
cube.position.add( cube.userData.velocity );
if ( cube.position.x < - 3 || cube.position.x > 3 ) {
cube.position.x = THREE.Math.clamp( cube.position.x, - 3, 3 );
cube.userData.velocity.x = - cube.userData.velocity.x;
}
if ( cube.position.y < - 3 || cube.position.y > 3 ) {
cube.position.y = THREE.Math.clamp( cube.position.y, - 3, 3 );
cube.userData.velocity.y = - cube.userData.velocity.y;
}
if ( cube.position.z < - 3 || cube.position.z > 3 ) {
cube.position.z = THREE.Math.clamp( cube.position.z, - 3, 3 );
cube.userData.velocity.z = - cube.userData.velocity.z;
}
cube.rotation.x += cube.userData.velocity.x * 2 * delta;
cube.rotation.y += cube.userData.velocity.y * 2 * delta;
cube.rotation.z += cube.userData.velocity.z * 2 * delta;
}
controls.update();
effect.render( scene, camera );
}
</script>
</body>
</html>
I just hit a very similar issue. It seems that VRButton does not work well with requestAnimationFrame. Instead you need to use renderer.setAnimiationLoop.
Your code:
function animate() {
effect.requestAnimationFrame( animate );
render();
}
Change it to this:
function animate() {
renderer.setAnimationLoop(() => { render(); });
}
I used the following code (which is not mine, it's taken from this article http://blog.andrewray.me/how-to-export-a-rigged-animated-model-from-3ds-max-three-js/) in my project and tried to load my model. But the ptoblem is that the author uses animated skinned mesh, I have a simple model. I copied his complete demo page code to my project, changed the path to the js model and it doesn't show up. What should I adjust to make it work?
var container;
var camera, scene, renderer, objects;
var particleLight, pointLight;
var mesh, wiggly;
var loader = new THREE.JSONLoader();
loader.load( './humpback-whale-animated-threejs-max-exporter.js', function ( geometry, materials ) {
var originalMaterial = materials[ 0 ];
originalMaterial.skinning = true;
mesh = new THREE.SkinnedMesh( geometry, originalMaterial );
mesh.scale.set( 0.1, 0.1, 0.1 );
var animation = new THREE.Animation(
mesh,
geometry.animation
);
animation.play();
init();
animate();
});
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
scene = new THREE.Scene();
scene.add( mesh );
// Lights
scene.add( new THREE.AmbientLight( 0xcccccc ) );
var directionalLight = new THREE.DirectionalLight(/*Math.random() * 0xffffff*/0xeeeeee );
directionalLight.position.x = Math.random() - 0.5;
directionalLight.position.y = Math.random() - 0.5;
directionalLight.position.z = Math.random() - 0.5;
directionalLight.position.normalize();
scene.add( directionalLight );
pointLight = new THREE.PointLight( 0xffffff, 4 );
scene.add( pointLight );
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
var clock = new THREE.Clock();
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
var delta = clock.getDelta();
var timer = Date.now() * 0.0005;
THREE.AnimationHandler.update( delta );
camera.position.x = Math.cos( 0.5 ) * 20;
camera.position.y = 5;
camera.position.z = Math.sin( 0.5 ) * 20;
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
I know there are different loaders in three.js and I don't know which one to use for a simple static textured mesh.
I want to preload all models and textures with a loadingbar in my project. For that i use the LoadingManger from three.js but i have problems with preloading the json Models. They load but i am unable to display them. Here is an example.
You can see in the console that 200 Meshs are created. 100 For the Asteroids and 100 for the Ships.
Withoud the LoadingManger i can display the models (asteroids) so there should be no problem with the model. You can see in the example Asteroids that are loaded without the loading manager.
Here my simplified code for the problem
$(function(){
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var debugScene = true;
var controler, camera, controls, scene, renderer;
var objectControls;
var ship1geometry,ship1material;
////////////////////////////////////////////////////////
//LOADMANGER
////////////////////////////////////////////////////////
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
$('#loader').css({width:(Math.round(loaded / total *100))+"%"});
console.log( item, loaded, total );
};
manager.onLoad = function () {
$('#loaderholder').fadeOut(function(){
init();
animate();
});
console.log('all items loaded');
};
manager.onError = function () {
console.log('there has been an error');
};
var loader = new THREE.JSONLoader(manager); // init the loader util
loader.load('models/shiptest.json', function (ship1geometry) {
var ship1material = new THREE.MeshFaceMaterial();
}, "models");
function init() {
var width = window.innerWidth;
var height = window.innerHeight;
camera = new THREE.PerspectiveCamera( 45, width / height, 1, 10000000 );
camera.position.x = 0;
camera.position.y = 0;
camera.position.z = 1500;
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer();
renderer.setClearColor("black");
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.autoClear = false;
var container = document.getElementById( 'container' );
container.appendChild( renderer.domElement );
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.enableZoom = false;
controls.minDistance = 50;
controls.maxDistance = 300000;
controls.autoRotate = false;
controls.autoRotateSpeed = 0.05;
controls.target.x = 0;
controls.target.y = 0;
controls.target.z = 0;
light = new THREE.AmbientLight( 0x666666 );
scene.add( light );
light = new THREE.PointLight( 0xffffff, 1, 10000 );
light.position.set( 0, 0, 0 );
var params = { recursive: true };
objectControls = new ObjectControls( camera, params );
shipCount = 100;
for (var p = 0; p < shipCount; p++) {
var pX = Math.random() * 5000 - 2500;
var pZ = Math.random() * 5000 - 2500;
var ship = createShipMesh(pX,0,pZ,0,0,0,ship1geometry,ship1material);
scene.add(ship);
}
var loader = new THREE.JSONLoader();
loader.load('models/asteroid.json', function (geometry, mat) {
var material = new THREE.MeshFaceMaterial( mat );
asteroidCount = 100;
for (var p = 0; p < asteroidCount; p++) {
var pX = Math.random() * 5000 - 2500;
var pZ = Math.random() * 5000 - 2500;
var mesh = new THREE.Mesh(geometry,material);
mesh.rotation.y = -Math.PI/Math.random();
mesh.position.set( pX, 0, pZ );
scene.add(mesh);
}
}, "textures");
window.addEventListener( 'resize', onWindowResize, false );
if(debugScene){
var gridHelper = new THREE.GridHelper( 900000, 10000 );
gridHelper.setColors( 0x0000ff, 0x808080 );
scene.add( gridHelper );
var axisHelper = new THREE.AxisHelper( 500 );
scene.add( axisHelper );
console.log(scene);
}
}
function onWindowResize() {
var width = window.innerWidth;
var height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
var lastTimeMsec= null;
var nowMsec= null;
function animate() {
requestAnimationFrame( animate );
render();
update();
}
function update(){
controls.update();
objectControls.update();
}
function render() {
renderer.render( scene, camera );
}
function createShipMesh(positionX,positionY,positionZ,centerX,centerY,centerZ,geometry,material){
positionX = centerX + positionX;
positionY = centerY + positionY;
positionZ = centerZ + positionZ;
var mesh = new THREE.Mesh(geometry,material);
mesh.rotation.y = -Math.PI/Math.random();
mesh.position.set( positionX, positionY, positionZ );
objectControls.add( mesh );
mesh.select = function(){
controls.target.x = position.x;
controls.target.y = position.y;
controls.target.z = position.z;
controls.dollyIn(2);
controls.minDistance = 20;
}
return mesh;
}
});
Okay i found the problem on my own. the Loading Manager works with json but my mistake was to set the variable ship1geometry global and was thinking that the loader would overwrite this variable so that i can use it later in the scene. That was wrong. I just needed to assign the response from the loader in my globaly set variable. So here is the right code
var ship1geometry,ship1material
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
$('#loader').css({width:(Math.round(loaded / total *100))+"%"});
console.log( item, loaded, total );
};
manager.onLoad = function () {
$('#loaderholder').fadeOut(function(){
init();
animate();
});
console.log('all items loaded');
};
manager.onError = function () {
console.log('there has been an error');
};
var loader = new THREE.JSONLoader(manager); // init the loader util
loader.load('models/shiptest.json', function (geometry,mat) {
ship1geometry = geometry;
ship1material = new THREE.MeshLambertMaterial({map:mat });
}, "textures");
function init(){
...
}
I have a problem .
I want move the earth in 360° with the mouse but nothing happens .
However , I would like the world is fixed and does not move when I use the mouse to rotate 360 .
Waiting for a response .
<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
color: #808080;
font-family:Monospace;
font-size:13px;
text-align:center;
background-color: #000000;
margin: 0px;
overflow: hidden;
}
#info {
position: absolute;
top: 0px; width: 100%;
padding: 5px;
}
a {
color: #0080ff;
}
</style>
</head>
<body>
<div id="container"></div>
<div id="info">three.js - earth demo</div>
<script src="../build/three.min.js"></script>
<script src="js/libs/stats.min.js"></script>
<script>
var container, stats;
var camera, scene, renderer;
var group;
var mouseX = 0, mouseY = 0;
init();
animate();
function init() {
container = document.getElementById( 'container' );
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 900;
scene = new THREE.Scene();
group = new THREE.Object3D();
scene.add( group );
// earth
var earthTexture = new THREE.Texture();
var loader = new THREE.ImageLoader();
loader.addEventListener( 'load', function ( event ) {
earthTexture.image = event.content;
earthTexture.needsUpdate = true;
} );
loader.load( 'textures/1.jpg');
var geometry = new THREE.SphereGeometry( 250, 55, 55 );
var material = new THREE.MeshBasicMaterial( { map: earthTexture, overdraw: true } );
var mesh = new THREE.Mesh( geometry, material );
group.add( mesh );
// shadow
var canvas = document.createElement( 'canvas' );
canvas.width = 128;
canvas.height = 128;
var context = canvas.getContext( '2d' );
var gradient = context.createRadialGradient( canvas.width / 2, canvas.height / 2, 0, canvas.width / 2, canvas.height / 2, canvas.width / 2 );
gradient.addColorStop( 0.1, 'rgba(210,210,210,1)' );
gradient.addColorStop( 1, 'rgba(255,255,255,1)' );
context.fillStyle = gradient;
context.fillRect( 0, 0, canvas.width, canvas.height );
var texture = new THREE.Texture( canvas );
texture.needsUpdate = true;
var geometry = new THREE.PlaneGeometry( 300, 300, 3, 3 );
var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: true } );
renderer = new THREE.CanvasRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild( stats.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 );
mouseY = ( event.clientY - windowHalfY );
}
//
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
camera.position.x += ( mouseX - camera.position.x ) * 0.50;
camera.position.y += ( - mouseY - camera.position.y ) * 0.50;
camera.lookAt( scene.position );
group.rotation.y -= 0.01;
renderer.render( scene, camera );
}
// add subtle ambient lighting
var ambientLight = new THREE.AmbientLight(0x555555);
scene.add(ambientLight);
</script>
</body>
the problem that you are having is that you are only moving the camera in the X and Y direction, when the camera is a 3D entity.
In order to do the rotation, you need to move convert the mouse coordinate from 3D spherical coordinates (like latitude, longitude, altitude, assuming a constant altitude, you can assign X to longitude and Y to latitude).
Then assign the 3D cartesian coordinates to your camera:
The formula is (replacing what you have in your render function):
(assume altitude is 960, which works with your model)
camera.position.x = 960 * Math.sin(mouseX) * Math.cos(mouseY);
camera.position.y = 960 * Math.sin(mouseX) * Math.sin(mouseY);
camera.position.z = 960 * Math.cos(mouseX);
The next caveat is that sin and cos take radians (range from -pi to pi (-3.14159 to 3.14159)...so you will need to adjust your onDocumentMouseMove event to something like
mouseX = -Math.PI + (event.clientX)/(windowHalfX*2)*Math.PI*2;
mouseY = -Math.PI + (event.clientY)/(windowHalfY*2)*Math.PI*2;
This will cause the mouse to act in lat/long coordinate (which can still be a little strange if you are looking at the top of the world. You could restrict mouseY=0, then the X rotation would always be on the equator.
The math is a little more complicated if you want moving the mouse to be on a moving frame vs. the earth centric frame I've shown. But this should at least be a start.