ThreeJS Rotation Animation - javascript

I have a cube in ThreeJS and I would like to rotate it 90 degrees clockwise every time I press a button. I think I have the basic gist of it: create a Three.Animation instance, bind it to the cube, and then have the animation begin every time I press the correct button. However, I'm having a difficult time understanding ThreeJS's API, because it doesn't seem to contain any examples for its methods.
This is THREE.js's Animation constructor: ( root, data, interpolationType, JITCompile ) I don't understand what goes into the fields. I'm guessing root would be where I put my cube, but what about the rest?
Also can I just call animation.play() to cause the animation whenever I want? And how does the animationHandler work?

I think for for rotating an object 90 degrees clockwise, using the TWEEN class will do. I think the Animation class is handy for heavier stuff (like bones/skin morphs/etc.)
To use the tween class there are 3 basic steps:
include the class in your file (<script src="js/Tween.js"></script>)
add your tween for the event you need (new TWEEN.Tween( cube.rotation ).to( { y:Math.random()}, 1000 ).easing( TWEEN.Easing.Quadratic.EaseOut).start();)
update the tween in your render loop (TWEEN.update();)
You can have a have a look at the cubes tween example for a start.
I've modified the default cube example to have the tween in:
<!doctype html>
<html lang="en">
<head>
<title>three.js canvas - geometry - cube</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
font-family: Monospace;
background-color: #f0f0f0;
margin: 0px;
overflow: hidden;
}
</style>
</head>
<body>
<script src="../build/Three.js"></script>
<script src="js/Tween.js"></script>
<script src="js/RequestAnimationFrame.js"></script>
<script src="js/Stats.js"></script>
<script>
var container, stats;
var camera, scene, renderer;
var cube, plane;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var rad90 = Math.PI * .5;
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 = 'click to tween';
container.appendChild( info );
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.y = 150;
camera.position.z = 500;
scene = new THREE.Scene();
// Cube
var materials = [];
for ( var i = 0; i < 6; i ++ ) {
materials.push( [ new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } ) ] );
}
cube = new THREE.Mesh( new THREE.CubeGeometry( 200, 200, 200, 1, 1, 1, materials ), new THREE.MeshFaceMaterial() );
cube.position.y = 150;
cube.overdraw = true;
scene.add( cube );
// Plane
plane = new THREE.Mesh( new THREE.PlaneGeometry( 200, 200 ), new THREE.MeshBasicMaterial( { color: 0xe0e0e0 } ) );
plane.rotation.x = - 90 * ( Math.PI / 180 );
plane.overdraw = true;
scene.add( plane );
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( 'mousedown', onDocumentMouseDown, false );
}
//
function onDocumentMouseDown( event ) {
event.preventDefault();
new TWEEN.Tween( cube.rotation ).to( { y: cube.rotation.y + rad90}, 1000 ).easing( TWEEN.Easing.Quadratic.EaseOut).start();
new TWEEN.Tween( plane.rotation ).to( { z: plane.rotation.z + rad90}, 1000 ).easing( TWEEN.Easing.Quadratic.EaseOut).start();
console.log("click");
}
//
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
TWEEN.update();
renderer.render( scene, camera );
}
</script>
</body>
</html>

Related

Threejs - rendering different models and animating out of view

I have a threejs project where I want to render a model and use the mouse to rotate around it.
this is the kind of idea
https://www.leroymerlin.fr/big2/guides-2021/experience-inspiration.html
I've got an example working, but the controls are bound by click and drags.
the goal is to render a model
have the ability of clicking on a button that will revolve the camera and render a new model as the old one dissipates (currently have a dropdown switching models)
on hovering over the model render a call to action/special mouse animation that would act as a link
be able to pan around the model using the mouse movement (not click drag).
-- I'm playing around with this demo first
https://threejs.org/examples/webgl_animation_keyframes.html
I tried adding stuff like here with the mouse
let mouseX = 0, mouseY = 0;
function onDocumentMouseMove( event ) {
mouseX = ( event.clientX - windowHalfX );
mouseY = ( event.clientY - windowHalfY );
}
function render() {
camera.position.x += ( mouseX - camera.position.x ) * 0.05;
camera.position.y += ( - mouseY - camera.position.y ) * 0.05;
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
but it malfunctions causing the model to spin fast and zoom in too much.
Here is the latest code
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - animation - keyframes</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link type="text/css" rel="stylesheet" href="main.css">
<style>
body {
background-color: #bfe3dd;
color: #000;
}
a {
color: #2983ff;
}
</style>
</head>
<body>
<div id="container"></div>
<div id="info">
<!--
three.js webgl - animation - keyframes<br/>
Model: Littlest Tokyo by
Glen Fox, CC Attribution.
-->
<select id="models">
<option value="models/gltf/LittlestTokyo.glb">LittlestTokyo</option>
<option value="models/gltf/Flamingo.glb" selected="selected">Flamingo</option>
</select>
</div>
<script type="module">
import * as THREE from '../build/three.module.js';
//import Stats from './jsm/libs/stats.module.js';
import { OrbitControls } from './jsm/controls/OrbitControls.js';
import { RoomEnvironment } from './jsm/environments/RoomEnvironment.js';
import { GLTFLoader } from './jsm/loaders/GLTFLoader.js';
import { DRACOLoader } from './jsm/loaders/DRACOLoader.js';
let mixer;
const clock = new THREE.Clock();
const container = document.getElementById( 'container' );
//const stats = new Stats();
//container.appendChild( stats.dom );
const renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.outputEncoding = THREE.sRGBEncoding;
container.appendChild( renderer.domElement );
const pmremGenerator = new THREE.PMREMGenerator( renderer );
const scene = new THREE.Scene();
scene.background = new THREE.Color( 0xbfe3dd );
scene.environment = pmremGenerator.fromScene( new RoomEnvironment(), 0.04 ).texture;
const camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 100 );
camera.position.set( 5, 2, 8 );
const controls = new OrbitControls( camera, renderer.domElement );
controls.target.set( 0, 0.5, 0 );
controls.update();
controls.enablePan = false;
controls.enableDamping = true;
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath( 'js/libs/draco/gltf/' );
const loader = new GLTFLoader();
loader.setDRACOLoader( dracoLoader );
loadModel('models/gltf/Flamingo.glb')
function loadModel(path){
loader.load(path, function ( gltf ) {
//remove model
// remove last model
// if(model) model.parent.remove(model)
scene.clear();
//add model
add(gltf)
}, undefined, function ( e ) {
console.error(e);
});
}
window.onresize = function () {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
};
function add(gltf){
let model = gltf.scene;
model.position.set( 1, 1, 0 );
model.scale.set( 0.01, 0.01, 0.01 );
scene.add( model );
mixer = new THREE.AnimationMixer( model );
mixer.clipAction( gltf.animations[ 0 ] ).play();
animate();
}
function load(path) {
console.log("loading", path)
loadModel(path)
}
document.getElementById('models').addEventListener('change', function() {
console.log('You selected: ', this.value);
console.log("model", window.model)
load(this.value)
});
function animate() {
requestAnimationFrame( animate );
const delta = clock.getDelta();
mixer.update( delta );
controls.update();
//stats.update();
renderer.render( scene, camera );
}
</script>
</body>
</html>
When you do camera.position.x += mouseX - camera.position.x, you're using the x-position to set itself. These self-referencing values will give you erratic behavior. Try something simpler:
camera.position.x = mouseX * 0.05;
Or if you want a smooth animation, you could do linear-interpolation between 2 values:
let mouseXTarget = 0, mouseX = 0;
function onDocumentMouseMove( event ) {
mouseXTarget = ( event.clientX - windowHalfX ) * 0.05;
}
function render() {
// mouseX will smoothly try to reach its target
mouseX = THREE.MathUtils.lerp(mouseX, mouseXTarget, 0.1);
camera.position.x += mouseX;
camera.lookAt( scene.position );
}

Create a plane mesh with pointcloud in three.js

I've created pointcloud with all points in an exact plane. I want the pointcloud to be highlighted and shown as a rectangle shape when the mouse is rolled over. For that, I think the pointcloud has to be converted in to a mesh, first.
I've googled for hours and tried to read thee.js documentation too. But couldn't find any solution. Could you please help me convert this pointcloud to a mesh. Thank you very much
<script>
if ( WEBGL.isWebGLAvailable() === false ) {
document.body.appendChild( WEBGL.getWebGLErrorMessage() );
}
var camera, scene, renderer, controls;
init();
animate();
function init() {
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 45.0, window.innerWidth / window.innerHeight, 5, 3500 );
camera.position.z = 2500;
controls = new THREE.TrackballControls( camera, renderer.domElement );
createScene();
}
function createScene() {
scene = new THREE.Scene();
scene.background = new THREE.Color( 0x000000 );
var geometry = new THREE.BufferGeometry();
var positions = [];
for ( var i = 0; i < 500; i ++ ) {
for ( var j = 0; j < 300; j ++ ) {
var y = j;
var x = i;
var z = 0;
positions.push( x, y, z );
}
}
geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) );
var material = new THREE.PointsMaterial( {color: 0xFFFFFF} );
points = new THREE.Points( geometry, material );
scene.add( points );
}
function animate( time ) {
requestAnimationFrame( animate );
controls.update();
renderer.render( scene, camera );
}
</script>
Here is a quick and dirty modification of your sample, basically it creates a thin box with the same dimensions than your pointcloud and toggle its visibility when the mouse is getting over (using a raycaster). As far as I know there is no direct/built-in way to turn a pointcloud into a plane/mesh.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Three.js - wall construction</title>
<meta charset="utf-8">
<script src="js/three.js"></script>
<script src="js/TrackballControls.js"></script>
</head>
<body style="margin:0;">
<script>
if ( WEBGL.isWebGLAvailable() === false ) {
document.body.appendChild( WEBGL.getWebGLErrorMessage() );
}
var camera, scene, renderer, controls, box, boxMaterial;
init();
animate();
function init() {
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 45.0, window.innerWidth / window.innerHeight, 5, 3500 );
camera.position.z = 2500;
controls = new THREE.TrackballControls( camera, renderer.domElement );
createScene();
renderer.domElement.addEventListener('mousemove', onMouseMove, false);
}
function createScene() {
scene = new THREE.Scene();
scene.background = new THREE.Color( 0x000000 );
var geometry = new THREE.BufferGeometry();
var positions = [];
for ( var i = -250; i < 250; ++i) {
for ( var j = -150; j < 150; ++j) {
positions.push(i, j, 0);
}
}
geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( positions, 3 ) );
var material = new THREE.PointsMaterial({color: 0xFFFFFF});
points = new THREE.Points(geometry, material);
scene.add(points);
//create box based on pointcloud extends
var geometry = new THREE.BoxGeometry(500, 300, 1 );
boxMaterial = new THREE.MeshBasicMaterial({color: 0x0000FF});
boxMaterial.visible = false //set invisible by default
box = new THREE.Mesh(geometry, boxMaterial);
scene.add(box);
}
function onMouseMove (e) {
var pointer = {
x: (e.clientX / window.innerWidth ) * 2 - 1,
y: - ( e.clientY / window.innerHeight ) * 2 + 1
}
var raycaster = new THREE.Raycaster()
raycaster.setFromCamera(pointer, camera)
var intersects = raycaster.intersectObjects([box])
boxMaterial.visible = !!intersects.length
}
function animate(time) {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
</script>
</body>
</html>

Why is the mousedown event not recognized in javascript (with THREE)?

I have a simple THREE.js and I want to click on the round object, but when I click anywhere in the browser nothing happens. I followed this suggestion without success. The complete, full code is here:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<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: #ffffff;
margin: 0px;
overflow: hidden;
}
#info {
position: absolute;
top: 0px; width: 100%;
padding: 5px;
}
a {
color: #0080ff;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="js/build/three.min.js"></script>
<script>
var container, stats;
var camera, scene, renderer;
var group1;
var mouseX = 0, mouseY = 0;
var map_width = 512;
var map_height = 512;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init();
animate();
function createMesh(filename) {
var geometry = new THREE.SphereGeometry( 70, 40, 40 );
geometry.addEventListener('onclick', onDocumentMouseDown);
var loader = new THREE.TextureLoader();
var texture = loader.load(filename);
var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5 } );
var mesh = new THREE.Mesh( geometry, material );
return mesh;
}
function init() {
container = document.getElementById( 'container' );
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 2000 );
camera.position.z = 500;
scene = new THREE.Scene();
group1 = new THREE.Group();
var mesh = createMesh("textures/canvas1.png");
group1.add( mesh );
scene.add( group1 );
renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setClearColor( 0xffffff, 0 );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
document.addEventListener( 'onclick', onDocumentMouseDown, false);
}
function onDocumentMouseDown( event) {
//event.preventDefault();
console.log("test");
window.alert("clicked");
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
</script>
</body>
</html>
To reproduce this example you just need some random image and the THREE.js library. I do neither see any error in the console (related to this problem), nor any other console output during clicking on the browser...
I tried to add a method to one of the THREE.js objects as described in the documentation (geometry.addEventListener), but this also does not do anything.
document.addEventListener( 'click', onDocumentMouseDown, false);

Embed 3D model viewer

I'm trying to implement this 3D model viewer, however I want to embed it into an already set div instead of making a new one as this does. So I've edited the code like so but it hasn't worked. Any help would be appreciated.
<script>
// This is where our model viewer code goes.
var container;
var camera, scene, renderer;
var mouseX = 0, mouseY = 0;
var windowHalfX = document.getElementById('viewer').clientHeight / 2;
var windowHalfY = document.getElementById('viewer').clientHeight / 2;
init();
animate();
// Initialize
function init() {
// This <div> will host the canvas for our scene.
container = document.getElementById( 'viewer' );
//document.body.appendChild( container );
// You can adjust the cameras distance and set the FOV to something
// different than 45°. The last two values set the clippling plane.
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
camera.position.z = 100;
// These variables set the camera behaviour and sensitivity.
controls = new THREE.TrackballControls( camera );
controls.rotateSpeed = 5.0;
controls.zoomSpeed = 5;
controls.panSpeed = 2;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
// This is the scene we will add all objects to.
scene = new THREE.Scene();
// You can set the color of the ambient light to any value.
// I have chose a completely white light because I want to paint
// all the shading into my texture. You propably want something darker.
var ambient = new THREE.AmbientLight( 0xffffff );
scene.add( ambient );
// Uncomment these lines to create a simple directional light.
// var directionalLight = new THREE.DirectionalLight( 0xffeedd );
// directionalLight.position.set( 0, 0, 1 ).normalize();
// scene.add( directionalLight );
// Texture Loading
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
console.log( item, loaded, total );
};
var texture = new THREE.Texture();
var loader = new THREE.ImageLoader( manager );
// You can set the texture properties in this function.
// The string has to be the path to your texture file.
loader.load( 'img/sickletexture.png', function ( image ) {
texture.image = image;
texture.needsUpdate = true;
// I wanted a nearest neighbour filtering for my low-poly character,
// so that every pixel is crips and sharp. You can delete this lines
// if have a larger texture and want a smooth linear filter.
texture.magFilter = THREE.NearestFilter;
texture.minFilter = THREE.NearestMipMapLinearFilter;
} );
// OBJ Loading
var loader = new THREE.OBJLoader( manager );
// As soon as the OBJ has been loaded this function looks for a mesh
// inside the data and applies the texture to it.
loader.load( 'obj/sickle.obj', function ( event ) {
var object = event;
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material.map = texture;
}
} );
// My initial model was too small, so I scaled it upwards.
object.scale = new THREE.Vector3( 2, 2, 2 );
// You can change the position of the object, so that it is not
// centered in the view and leaves some space for overlay text.
object.position.y -= 2.5;
scene.add( object );
});
// We set the renderer to the size of the window and
// append a canvas to our HTML page.
renderer = new THREE.WebGLRenderer();
renderer.setSize( document.getElementById('viewer').innerWidth, document.getElementById('viewer').innerHeight );
container.appendChild( renderer.domElement );
}
// The Loop
function animate() {
// This function calls itself on every frame. You can for example change
// the objects rotation on every call to create a turntable animation.
requestAnimationFrame( animate );
// On every frame we need to calculate the new camera position
// and have it look exactly at the center of our scene.
controls.update();
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
</script>
I'm trying to get things to work myself and this code works for me with the latest version (66) of three. Its a little different to you example as I am using a vrml model rather than an obj and I handle the material differently. But it does run fine.
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - loaders - vrml loader</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
threewindow {
border: 1px solid black;
}
</style>
<script src="../three.js/build/three.min.js"></script>
<script src="../three.js/examples/js/controls/TrackballControls.js"></script>
<script src="../three.js/examples/js/loaders/VRMLLoader.js"></script>
<script src="../three.js/examples/js/Detector.js"></script>
<script src="../three.js/examples/js/libs/stats.min.js"></script>
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, stats;
var camera, controls, scene, renderer;
var cross;
function init() {
alert("init");
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.01, 1e10 );
camera.position.z = 6;
controls = new THREE.TrackballControls( camera );
controls.rotateSpeed = 5.0;
controls.zoomSpeed = 5;
controls.panSpeed = 2;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
scene = new THREE.Scene();
scene.add( camera );
var sphereMaterial =
new THREE.MeshLambertMaterial(
{
color: 0xCC0000
});
// light
var dirLight = new THREE.DirectionalLight( 0xffffff );
dirLight.position.set( 200, 200, 1000 ).normalize();
camera.add( dirLight );
camera.add( dirLight.target );
var loader = new THREE.VRMLLoader();
loader.addEventListener( 'load', function ( event ) {
var object = event.content;
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
//child.material.map = texture;
//child.material = sphereMaterial;
child.material.side = THREE.DoubleSide;
}
} );
scene.add(object);
} );
// loader.load( "models/vrml/house.wrl" );
loader.load( "cayley.wrl" );
// renderer
renderer = new THREE.WebGLRenderer( { antialias: false } );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setSize(200, 200);
document.getElementById("threewindow").appendChild(renderer.domElement);
// container = document.createElement( 'div' );
// document.body.appendChild( container );
// 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 );
animate();
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
controls.handleResize();
}
function animate() {
requestAnimationFrame( animate );
controls.update();
renderer.render( scene, camera );
//stats.update();
}
</script>
</head>
<body onload="init()">
<h1>Cubic surfaces</h1>
<p>All the surfaces defined by cubics equations.</p>
<ul><li>Singularities of cubic surfaces.</li>
<li>A pictorial introduction to singularity theory.</li>
</ul>
<div id="threewindow"></div>
</body>
</html>
I found a rather easy solution, I'm surprised I did not find it earlier.
Create the 3D in a seperate html document (using the original script, not the edited one in the OP), then in the div <embed src="3d.html"></embed>

Picking selected mesh from an OBJ file

I'm using the OBJLoader to load a large 3D model (described in a .obj file) but it loads the whole file as a single Object3D object. Using scene.add(object) it adds the whole object to the scene.
I need to pick the selected mesh and change some of its properties, but when I add mouse function and use Ray.intersectObjects try to get the selected mesh it never works. I can not find where I made mistakes.
Would love some help with trying to get this working. Thanks!
It confused me for couples of days. The following is all my code:
<!doctype html>
<html lang="en">
<head>
<title>three.js webgl - loaders - OBJ loader</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
font-family: Monospace;
background-color: #000;
color: #fff;
margin: 0px;
overflow: hidden;
}
#info {
color: #fff;
position: absolute;
top: 10px;
width: 100%;
text-align: center;
z-index: 100;
display:block;
}
#info a, .button { color: #f00; font-weight: bold; text-decoration: underline; cursor: pointer }
</style>
</head>
<body>
<div id="info">
three.js - OBJLoader test
</div>
<script src="../build/Three.js"></script>
<script src="js/loaders/OBJLoader.js"></script>
<script src="js/Detector.js"></script>
<script src="js/Stats.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;
var _mouse = { x: 0, y: 0 },
objects = [],
_projector = new THREE.Projector();
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
camera.position.z = 100;
scene.add( camera );
var ambient = new THREE.AmbientLight( 0x101030 );
scene.add( ambient );
var directionalLight = new THREE.DirectionalLight( 0xffeedd );
directionalLight.position.set( 0, 0, 1 ).normalize();
scene.add( directionalLight );
var texture = THREE.ImageUtils.loadTexture( 'textures/ash_uvgrid01.jpg' );
var loader = new THREE.OBJLoader();
loader.load( "obj/male02/male02.obj", function ( object ) {
for ( var i = 0, l = object.children.length; i < l; i ++ ) {
object.children[ i ].material.map = texture;
}
object.position.y = - 80;
object.position.z = - 160;
scene.add( object );
objects.push( object );
} );
// RENDERER
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
document.addEventListener( 'mousedown', onDocumentMouseDown, false );
}
function onDocumentMouseDown( event ) {
event.preventDefault();
// find intersections
_mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
_mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
var vector = new THREE.Vector3( _mouse.x, _mouse.y, 1 );
var ray = _projector.pickingRay( vector, camera );
var intersects = ray.intersectObjects( scene.children );
if ( intersects.length > 0 ) {
alert("selected!");
_SELECTED_DOWN = true;
}
}
function animate() {
requestAnimationFrame( animate );
render();
}
function render() {
renderer.render( scene, camera );
}
</script>
</body>
</html>
ray.intersectObjects() is not recursive. You need to pass a list of the objects you want to test.

Categories