I am trying to recreate a mouse interaction with an obj file - similar to this example:
http://yungjake.com/usb/
Additionally, I am trying to have it animate when clicked upon - and I really want to recreate the smoothness/physics of the mouse interaction when the mouse is hovering.
My code so far is hardly close but here it is:
<script src="three.min.js"></script>
<script src="EffectComposer.js"></script>
<script src="CopyShader.js"></script>
<script src="DotScreenShader.js"></script>
<script src="RGBShiftShader.js"></script>
<script src="FilmShader.js"></script>
<script src="FilmPass.js"></script>
<script src="RenderPass.js"></script>
<script src="MaskPass.js"></script>
<script src="ShaderPass.js"></script>
<script src="Detector.js"></script>
<script src="OBJLoader.js"></script>
<script>
var camera, scene, renderer, composer;
var object, light;
var geometry;
init();
animate();
function init() {
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
var composer = new THREE.EffectComposer(renderer);
//
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 20;
scene = new THREE.Scene();
scene.fog = new THREE.Fog( 0x000000, 1, 1000 );
//=======================================================================================================================================================
//=======================================================================================================================================================
// BACKGROUND
scene.background = new THREE.CubeTextureLoader()
.load( [ 'px.jpg', 'nx.jpg', 'py.jpg', 'ny.jpg', 'pz.jpg', 'nz.jpg' ] );
var textureCube = new THREE.CubeTextureLoader()
.load( [ 'px.jpg', 'nx.jpg', 'py.jpg', 'ny.jpg', 'pz.jpg', 'nz.jpg' ] );
textureCube.mapping = THREE.CubeRefractionMapping;
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
console.log( item, loaded, total );
};
scene.add( new THREE.AmbientLight( 0x222222 ) );
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 1, 1, 1 );
scene.add( light );
// postprocessing
composer = new THREE.EffectComposer( renderer );
var effect = new THREE.ShaderPass( THREE.RGBShiftShader );
effect.uniforms[ 'amount' ].value = .05;
effect.renderToScreen = true;
composer.addPass( effect );
var renderPass = new THREE.RenderPass(scene, camera);
composer.addPass(renderPass);
var effectFilm = new THREE.FilmPass( .5, 0, 0, false);
effectFilm.renderToScreen = true;
composer.addPass(effectFilm);
var clock = new THREE.Clock();
function render() {
var delta = clock.getDelta();
composer.render(delta); //parameter must be set with render
requestAnimationFrame(render);
}
render();
//
//=======================================================================================================================================================
//=======================================================================================================================================================
// MATERIALS + OBJ LOADER + TEXTURE
var texture = new THREE.Texture();
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 material1 = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube, refractionRatio: .25 } );
var loader = new THREE.ImageLoader( manager );
loader.load( 'UV_Grid_Sm.jpg', function ( image ) {
texture.image = image;
texture.needsUpdate = true;
} );
var loader = new THREE.OBJLoader( manager );
loader.load( 'WorkPlease.obj', function ( object ) {
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material.map = texture;
child.material = material1;
}
} );
window.addEventListener('mousemove', function(e){
var mouse3D = new THREE.Vector3(
( event.clientX / window.innerWidth ) * 2 - 1,
- ( event.clientY / window.innerHeight ) * 2 + 1,
2 );
object.lookAt(mouse3D);
var angle = Math.atan2(mouse3D.y-object.position.y, mouse3D.x-object.position.x);
object.rotation.z = angle;
})
scene.add( object );
// object.position.y = 0;
// //
// object.position.x = 0;
// //
// object.position.z = 0;
//object.rotateOnAxis( 50, 50, 50 );
// object.center.x = 0;
// object.center.y = 0;
// object.center.x = 0;
//
// mesh.position.set( object.center.x, object.center.y, object.center.z );
// mesh.geometry.applyMatrix(new THREE.Matrix4().makeTranslation( -object.center.x, -object.center.y, -object.center.z ) );
}, onProgress, onError );
function onDocumentMouseMove(event) {
mouseX = ( event.clientX - windowHalfX ) * .005;
mouseY = ( event.clientY - windowHalfY ) * .005;
}
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
//composer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
// object.rotation.x += 0.005;
// object.rotation.y += 0.01;
// composer.render();
}
</script>
</body>
Please let me know what I should change or if there are any tutorials that could help me out with this. I am a beginner so any help is appreciated.
Thanks.
Related
I have an animation prototype - which plays on scroll - is there a way to reset animation on scroll to top/bottom? Basically from the top it plays and stops when it reaches the bottom? Right now the animation loops and ignores top/bottom (start/end).
When scrolled from the top it plays forward and when reached the bottom it plays in reverse is the desired bahaviour.
var container, stats, controls;
var camera, scene, renderer, light;
var clock = new THREE.Clock();
var mixer = [];
var mixers = [];
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set( 0, 100, 100 );
scene = new THREE.Scene();
light = new THREE.HemisphereLight( 0xffffff, 0x444444 );
light.position.set( 0, 200, 0 );
scene.add( light );
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 0, 200, 100 );
light.castShadow = true;
light.shadow.camera.top = 180;
light.shadow.camera.bottom = -100;
light.shadow.camera.left = -120;
light.shadow.camera.right = 120;
scene.add( light );
// scene.add( new THREE.CameraHelper( light.shadow.camera ) );
var grid = new THREE.GridHelper( 2000, 20, 0x000000, 0x000000 );
grid.material.opacity = 0.2;
grid.material.transparent = true;
scene.add( grid );
// model
var loader = new THREE.FBXLoader();
loader.load( 'https://threejs.org/examples/models/fbx/Samba Dancing.fbx', function ( object ) {
object.mixer = new THREE.AnimationMixer( object );
mixers.push( object.mixer );
var action = object.mixer.clipAction( object.animations[ 0 ] );
action.play();
object.traverse( function ( child ) {
if ( child.isMesh ) {
child.castShadow = true;
child.receiveShadow = true;
}
} );
object.position.y = 85;
scene.add( object );
} );
renderer = new THREE.WebGLRenderer( { alpha: true, antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.shadowMap.enabled = true;
container.appendChild( renderer.domElement );
window.addEventListener( 'mousewheel', onMouseWheel, false );
window.addEventListener( 'touchstart', onTouchStart, false );
window.addEventListener( 'touchmove', onTouchMove, false );
window.addEventListener('resize', onResize, false);
// stats
stats = new Stats();
container.appendChild( stats.dom );
}
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onMouseWheel( event ) {
if(event.deltaY > 0){
for ( var i = 0; i < mixers.length; i ++ ) {
mixers[ i ].update( clock.getDelta() * 5 );
}
} else {
for ( var i = 0; i < mixers.length; i ++ ) {
mixers[ i ].update( clock.getDelta() * -5 );
}
}
}
function onTouchStart(event) {
startY = event.touches[ 0 ].pageY;
}
function onTouchMove( event ) {
var delta = event.deltaY;
if(event.deltaY > 0){
for ( var i = 0; i < mixers.length; i ++ ) {
mixers[ i ].update( clock.getDelta() * 5 );
}
} else {
for ( var i = 0; i < mixers.length; i ++ ) {
mixers[ i ].update( clock.getDelta() * -5 );
}
}
}
function animate() {
delta = clock.getDelta();
requestAnimationFrame( animate );
renderer.render( scene, camera );
stats.update();
}
body {
margin: 0px;
overflow: hidden;
}
<script src="https://threejs.org/build/three.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script src="https://threejs.org/examples/js/libs/inflate.min.js"></script>
<script src="https://threejs.org/examples/js/loaders/FBXLoader.js"></script>
<script src="https://threejs.org/examples/js/WebGL.js"></script>
<script src="https://threejs.org/examples/js/libs/stats.min.js"></script>
First off you should never link directly to threejs.org. Your example will break when the three.js devs update the version which will make your question example useless to others. Use a specific version from a CDN!
Otherwise if you save off the clips
object.mixer = new THREE.AnimationMixer( object );
mixers.push( object.mixer );
const clip = object.animations[0];
clips.push(clip);
var action = object.mixer.clipAction(clip);
action.play();
Then maybe you could use code like this
function updateAnimation(direction) {
const delta = direction * 5 * clock.getDelta();
for (let i = 0; i < mixers.length; ++i) {
const mixer = mixers[i];
const clip = clips[i];
const duration = clip.duration;
const newTime = THREE.MathUtils.clamp(mixer.time + delta, 0, duration);
mixer.setTime(newTime);
}
}
function onMouseWheel( event ) {
updateAnimation(Math.sign(event.deltaY));
}
...
var container, stats, controls;
var camera, scene, renderer, light;
var duration;
var clock = new THREE.Clock();
var mixer = [];
var mixers = [];
var clips = [];
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set( 0, 100, 100 );
scene = new THREE.Scene();
light = new THREE.HemisphereLight( 0xffffff, 0x444444 );
light.position.set( 0, 200, 0 );
scene.add( light );
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 0, 200, 100 );
light.castShadow = true;
light.shadow.camera.top = 180;
light.shadow.camera.bottom = -100;
light.shadow.camera.left = -120;
light.shadow.camera.right = 120;
scene.add( light );
// scene.add( new THREE.CameraHelper( light.shadow.camera ) );
var grid = new THREE.GridHelper( 2000, 20, 0x000000, 0x000000 );
grid.material.opacity = 0.2;
grid.material.transparent = true;
scene.add( grid );
// model
var loader = new THREE.FBXLoader();
loader.load( 'https://threejs.org/examples/models/fbx/Samba Dancing.fbx', function ( object ) {
object.mixer = new THREE.AnimationMixer( object );
mixers.push( object.mixer );
const clip = object.animations[0];
clips.push(clip);
var action = object.mixer.clipAction(clip);
action.play();
object.traverse( function ( child ) {
if ( child.isMesh ) {
child.castShadow = true;
child.receiveShadow = true;
}
} );
object.position.y = 85;
scene.add( object );
} );
renderer = new THREE.WebGLRenderer( { alpha: true, antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.shadowMap.enabled = true;
container.appendChild( renderer.domElement );
window.addEventListener( 'mousewheel', onMouseWheel, false );
window.addEventListener('resize', onResize, false);
// stats
stats = new Stats();
container.appendChild( stats.dom );
}
function onResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function updateAnimation(direction) {
const delta = direction * 5 * clock.getDelta();
for (let i = 0; i < mixers.length; ++i) {
const mixer = mixers[i];
const clip = clips[i];
const duration = clip.duration;
const newTime = THREE.MathUtils.clamp(mixer.time + delta, 0, duration);
mixer.setTime(newTime);
}
}
function onMouseWheel( event ) {
updateAnimation(Math.sign(event.deltaY));
}
function animate() {
delta = clock.getDelta();
requestAnimationFrame( animate );
renderer.render( scene, camera );
stats.update();
}
body {
margin: 0px;
overflow: hidden;
}
<script src="https://cdn.jsdelivr.net/npm/three#0.113.2/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.113.2/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.113.2/examples/js/libs/inflate.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.113.2/examples/js/loaders/FBXLoader.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.113.2/examples/js/WebGL.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.113.2/examples/js/libs/stats.min.js"></script>
Hello i just want to show an object with three js without webcam and marker juste a blank background and the object
I try to pick some part of code from the damage helmet example but nothing work :/ I just want a simple thing.
For now i have this code:
function start(){
var renderer = new THREE.WebGLRenderer({
antialias : true,
alpha: true
});
//renderer.setClearColor(new THREE.Color('lightgrey'), 0)
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.domElement.style.position = 'absolute'
renderer.domElement.style.top = '0px'
renderer.domElement.style.left = '0px'
document.body.appendChild( renderer.domElement );
// array of functions for the rendering loop
var onRenderFcts = [];
// init scene
var scene = new THREE.Scene();
// Create a camera
var camera = new THREE.Camera();
scene.add(camera);
// Create a light
var light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(0, 0, 1);
scene.add(light);
var loader = new THREE.OBJLoader();
var mtlLoader = new THREE.MTLLoader();
mtlLoader.load( "3d_models/OBJ/ano/ano.mtl", function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.load("3d_models/OBJ/ano/ano.obj", function ( object ) {
object.rotation.set(-Math.PI/2,0,0);
console.log(object.children[0])
scene.add( object );
});
},
function ( xhr ) {
console.log( 'OBJ ' + ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
},
function ( error ) {
console.log(error);
});
}
You're not positioning your camera, so it might be inside your objects.
Also without seeing the rest of your code.. it's not obvious where you are calling "start()" from ?
Here's a example of code that's work i found it on three js example and I modify some line of code to simplify it:
var renderer;
var clock = new THREE.Clock();
var mixers = [];
var onRenderFcts = [];
var camera2, scene2;
init2();
function init2() {
var container, stats;
container = document.createElement( 'div' );
document.body.appendChild( container );
camera2 = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 1000 );
camera2.position.z = 250;
scene2 = new THREE.Scene();
var ambientLight = new THREE.AmbientLight( 0xcccccc, 0.4 );
scene2.add( ambientLight );
var pointLight = new THREE.PointLight( 0xffffff, 0.8 );
camera2.add( pointLight );
scene2.add( camera2 );
var loader = new THREE.OBJLoader();
var mtlLoader = new THREE.MTLLoader();
mtlLoader.load( "3d_models/OBJ/ano/ano.mtl", function( materials ) {
materials.preload();
console.log(materials);
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.load("3d_models/OBJ/ano/ano.obj", function ( object ) {
console.log(object.children[0])
scene2.add( object );
onRenderFcts.push(function(){
object.rotation.y += 0.03;
})
});
},
function ( xhr ) {
console.log( 'OBJ ' + ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
},
function ( error ) {
console.log(error);
});
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
}
onRenderFcts.push(function(){
renderer.render( scene2, camera2 );
})
// run the rendering loop
var lastTimeMsec= null
requestAnimationFrame(function animate(nowMsec){
// keep looping
requestAnimationFrame( animate );
if ( mixers.length > 0 ) {
for ( var i = 0; i < mixers.length; i ++ ) {
mixers[ i ].update( clock.getDelta() );
}
}
// measure time
lastTimeMsec = lastTimeMsec || nowMsec-1000/60
var deltaMsec = Math.min(200, nowMsec - lastTimeMsec)
lastTimeMsec = nowMsec
// call each update function
onRenderFcts.forEach(function(onRenderFct){
onRenderFct(deltaMsec/1000, nowMsec/1000)
})
})
I just recently started creating a 3D model for a website I am creating.. and for some reason one of the arms of the character is transparent, but only partially as in you can see inside it. As seen here:
Transparent arm and I can't figure it out. I tried back tracking some of my code to no avail, and I tried re rendering it in blender (as it is a .obj import) and it still has the same issue. Does anyone happen to know a fix for the issue?
<body>
<script src="./JS/three.js"></script>
<script src="./JS/DDSLoader.js"></script>
<script src="./JS/MTLLoader.js"></script>
<script src="./JS/OBJLoader.js"></script>
<script src="./JS/OrbitControls.js"></script>
<script src="./JS/Detector.js"></script>
<script src="./JS/stats.min.js"></script>
<script>
var container, stats;
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 );
renderer = new THREE.WebGLRenderer( {
alpha: true,
antialias: true
} );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( 200,300);
container.appendChild( renderer.domElement );
camera = new THREE.PerspectiveCamera( 14, window.innerWidth / window.innerHeight, .3, 1000 );
camera.position.z = 1;
camera.position.y = 8;
//camera.rotation.y = -90*(180/3.14159265)
var orbit = new THREE.OrbitControls( camera, renderer.domElement );
orbit.enableZoom = false;
orbit.enablePan = false;
orbit.autoRotate = true;
// scene
scene = new THREE.Scene();
var ambient = new THREE.AmbientLight( 0xffffff );
scene.add( ambient );
var dirLight = new THREE.DirectionalLight(0xffffff, .41);
dirLight.position.set(100, 100, 50);
scene.add(dirLight);
var light = new THREE.PointLight( 0xf8f8ff, 0.25, 10000 );
light.position.set( 0, 100,-75);
scene.add( light );
//var directionalLight = new THREE.DirectionalLight( 0xf8f8ff );
//directionalLight.position.set( 0, 0, 1 ).normalize();
//scene.add( directionalLight );
// model
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 ) { };
THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() );
var mtlLoader = new THREE.MTLLoader();
mtlLoader.setBaseUrl( './Avatar/' );
mtlLoader.setPath( './Avatar/' );
mtlLoader.load( 'Avatar.mtl', function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.setPath( './Avatar/' );
objLoader.load( 'Avatar.obj', function ( object )
{
object.alphaTest = 0;
object.transparent = false;
object.side = THREE.DoubleSide;
//object.rotation.y = -25*(180/3.14159265)
//object.rotation.x = -35*(180/3.14159265)
object.position.y = 0;
scene.add( object );
}, onProgress, onError );
});
//
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 ) / 2;
mouseY = ( event.clientY - windowHalfY ) / 2;
}
//
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
//camera.position.x += ( mouseX - camera.position.x ) * .005;
//camera.position.y += ( - mouseY - camera.position.y ) * .005;
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
</script>
I'm a bit lost at this point and could really use your help! Thanks in advance. If you have any questions, or not sure about something in my code let me know.
Face normals of the arm might be flipped backside. As you may know, if the face normal is facing backside, it will not be rendered, and only back-side will be rendered, even in 3d modeler too such as blender.
You can check normal direction in three.js using FaceNormalsHelper as well.
Docs for the helper:
http://threejs.org/docs/#Reference/Extras.Helpers/FaceNormalsHelper
http://threejs.org/examples/#webgl_helpers
If normal direction were wrong, flip them in your 3d modeler app.
I need to do very simple 3d model viewer with rotation and so on..
I have simple code, everything works fine, but when I add these two rows with OrbitControls then there'S only blank page:
controls = new THREE.OrbitControls( camera );
controls.addEventListener( 'change', render );
Whole code:
<body>
<script src="js/OrbitControls.js"></script>
<script src="js/three.min.js"></script>
<script src="js/OBJLoader.js"></script>
<div id="ahoj" style="width:1000px; height:700px">
</div>
<script>
var container;
var camera, controls, scene, renderer;
var mouseX = 0, mouseY = 0;
var windowHalfX = 1000 / 2;
var windowHalfY = 700 / 2;
init();
animate();
function init() {
container = document.getElementById('ahoj');
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 75, 1000 / 700, 1, 2000 );
camera.position.z = 200;
// scene
scene = new THREE.Scene();
var ambient = new THREE.AmbientLight( 0x000 );
scene.add( ambient );
var directionalLight = new THREE.DirectionalLight( 0xffeedd );
directionalLight.position.set( 0, 0, 1 );
scene.add( directionalLight );
// texture
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
console.log( item, loaded, total );
};
var texture = new THREE.Texture();
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 loader = new THREE.ImageLoader( manager );
loader.load( 'textures/mapa1.png', function ( image ) {
texture.image = image;
texture.needsUpdate = true;
} );
// model
var loader = new THREE.OBJLoader( manager );
loader.load( 'obj/Immortal.obj', function ( object ) {
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
//child.material.map = texture;
}
} );
object.scale.set(3,3,3);
object.position.y = 0;
object.position.z = 0;
object.position.x = 0;
scene.add( object );
}, onProgress, onError );
//
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
//controls = new THREE.OrbitControls( camera );
//controls.addEventListener( 'change', render );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( 1000, 700 );
container.appendChild( renderer.domElement )
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
windowHalfX = 1000 / 2;
windowHalfY = 700 / 2;
camera.aspect = 1000 / 700;
camera.updateProjectionMatrix();
renderer.setSize( 1000, 700 );
}
function animate() {
render();
requestAnimationFrame( animate );
controls.update();
}
function render() {
renderer.render( scene, camera );
}
</script>
</body>
Any idea where is the problem?
I tried some few tutorials, but no one helped me..
You need to include three.min.js first:
<script src="js/three.min.js"></script>
<script src="js/OrbitControls.js"></script>
<script src="js/OBJLoader.js"></script>
I modified an example from Three.js library and I tried to add click event on objects.
After a lot of attempts... I'm still not capable to listening for clicks.
This code produces convex forms.
There is my code:
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, stats;
var camera, scene, renderer;
var objects = [];
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
camera.position.y = 400;
scene = new THREE.Scene();
var light, object, object2, materials;
scene.add( new THREE.AmbientLight( 0x404040 ) );
light = new THREE.DirectionalLight( 0xffffff );
light.position.set( 0, 1, 0 );
scene.add( light );
var map = THREE.ImageUtils.loadTexture( 'textures/ash_uvgrid01.jpg' );
map.wrapS = map.wrapT = THREE.RepeatWrapping;
map.anisotropy = 16;
materials = [
new THREE.MeshLambertMaterial( { ambient: 0xbbbbbb, map: map } ),
new THREE.MeshBasicMaterial( { color: 0x242424, wireframe: true, transparent: false, opacity: 0.1 } )
];
// random convex
points = [];
for ( var i = 0; i < 15; i ++ ) {
points.push( randomPointInSphere( 50 ) );
}
object = THREE.SceneUtils.createMultiMaterialObject( new THREE.ConvexGeometry( points ), materials );
object.position.set( -250, 0, 200 );
scene.add( object );
objects.push( object );
object.callback = function() { console.log('blabla');}
renderer = new THREE.WebGLRenderer( { antialias: true } );
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 );
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function randomPointInSphere( radius ) {
return new THREE.Vector3(
( Math.random() - 0.5 ) * 1 * radius,
( Math.random() - 0.5 ) * 1 * radius,
( Math.random() - 0.5 ) * 1 * radius
);
}
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
var timer = Date.now() * 0.0001;
camera.position.x = Math.cos( timer ) * 800;
camera.position.z = Math.sin( timer ) * 800;
camera.lookAt( scene.position );
for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
var object = scene.children[ i ];
object.rotation.x = timer * 5;
object.rotation.y = timer * 2.5;
}
renderer.render( scene, camera );
}
function addMeteor()
{
var map = THREE.ImageUtils.loadTexture( 'textures/ash_uvgrid01.jpg' );
map.wrapS = map.wrapT = THREE.RepeatWrapping;
map.anisotropy = 16;
var materials = [
new THREE.MeshLambertMaterial( { ambient: 0xbbbbbb, map: map } ),
new THREE.MeshBasicMaterial( { color: 0x242424, wireframe: true, transparent: false, opacity: 0.1 } )
];
objects.push( materials );
var object3;
var points3 = [];
for ( var i = 0; i < 10; i ++ ) {
points3.push( randomPointInSphere( 50 ) );
}
object3 = THREE.SceneUtils.createMultiMaterialObject( new THREE.ConvexGeometry( points3 ), materials );
object3.position.set( -50, Math.floor((Math.random()*window.innerWidth)), Math.floor((Math.random()* window.innerHeight)) );
scene.add( object3 );
objects.push( object3 );
}
projector = new THREE.Projector();
// listeners
document.addEventListener( 'mousedown', onDocumentMouseDown, false)
// keyboard handler
function onDocumentMouseDown( event ) {
event.preventDefault();
console.log('blabla');
var vector = new THREE.Vector3(
( event.clientX / window.innerWidth ) * 2 - 1,
- ( event.clientY / window.innerHeight ) * 2 + 1,
0.5 );
projector.unprojectVector( vector, camera );
var ray = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
console.log(objects);
var intersects = ray.intersectObjects( objects );
console.log(intersects);
if ( intersects.length > 0 ) {
intersects[0].object.callback();
console.log('blabla');
}
}
renderer.render( scene, camera );
I was supposed to push Mesh into Objects array, but which one?
THREE.SceneUtils.createMultiMaterialObject() creates an object with two child meshes.
So, you need to set the recursive flag to true when calling Raycaster.intersectObjects().
var intersects = ray.intersectObjects( objects, true );
three.js r.62