im have been playing with the examples but since my knowledge is very limited because im a bit dumb, i cant figure out how to change the Model Source of the OBJLoader on click to load a different a model.
I have created a variable "var: name" and have place it as the en source in " loader.load( 'models/obj/goku/' + name, function"
I want to be able to create anchors where the name of the object is the Text of the anchor, but i am unable to change the source 1st.
Any help is greatly appreciated, thanks.
<!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">
<link type="text/css" rel="stylesheet" href="main.css">
</head>
<body>
<div id="info">
three.js - OBJLoader test
</div>
<a onclick="changename('GameBoy');">click</a>
<script type="module">
import * as THREE from '../build/three.module.js';
import { OBJLoader } from './jsm/loaders/OBJLoader.js';
import { OrbitControls } from './jsm/controls/OrbitControls.js';
var container;
var camera, scene, renderer;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var controls;
var object;
var name ="Engine.obj";
init();
animate();
function changename(newname){
name = newname;
}
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
camera.position.z = 250;
// scene
scene = new THREE.Scene();
var ambientLight = new THREE.AmbientLight( 0xcccccc, 0.4 );
scene.add( ambientLight );
var pointLight = new THREE.PointLight( 0xffffff, 0.8 );
camera.add( pointLight );
scene.add( camera );
// manager
function loadModel() {
object.traverse( function ( child ) {
if ( child.isMesh ) child.material.map = texture;
} );
object.position.y = -20;
scene.add( object );
}
var manager = new THREE.LoadingManager( loadModel );
manager.onProgress = function ( item, loaded, total ) {
console.log( item, loaded, total );
};
// texture
var textureLoader = new THREE.TextureLoader( manager );
var texture = textureLoader.load( 'textures/hardwood2_diffuse.jpg' );
// model
function onProgress( xhr ) {
if ( xhr.lengthComputable ) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log( 'model ' + Math.round( percentComplete, 2 ) + '% downloaded' );
}
}
function onError() {}
var loader = new OBJLoader( manager );
loader.load( 'models/obj/goku/' + name, function ( obj ) {
object = obj;
object.position.x = 0;
object.position.z = 1;
object.scale.set(0.5,0.5,0.5);
}, onProgress, onError );
//
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
// document.addEventListener( 'mousemove', onDocumentMouseMove, false );
//
window.addEventListener( 'resize', onWindowResize, false );
// controls
controls = new OrbitControls( camera, renderer.domElement );
//controls.addEventListener( 'change', render ); // call this only in static scenes (i.e., if there is no animation loop)
controls.enableDamping = true; // an animation loop is required when either damping or auto-rotation are enabled
controls.dampingFactor = 0.05;
// controls.screenSpacePanning = true;
// controls.minDistance = 100;
// controls.maxDistance = 500;
// controls.maxPolarAngle = Math.PI / 2;
}
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 ) * .05;
// camera.position.y += ( - mouseY - camera.position.y ) * .05;
// camera.lookAt( scene.position );
renderer.render( scene, camera );
controls.update(); // only required if controls.enableDamping = true, or if controls.autoRotate = true
}
</script>
</body>
</html>
When working with modules, you can't refer to module scope functions like so:
<a onclick="changename('GameBoy');">click</a>
That does not work since changename() only exists in module but not in global scope. You have to add the click event listener by defining an id for your link/button and then select it like so:
const element = document.getElementById( 'myButton' );
element.addEventListener( 'click', changename );
Notice that you can't pass the newname parameter like in your original code. Consider to store it in a data attribute if you want to reuse the function.
Even if you register the event listener like that, your code will not work as intended. Simply because changename() only changes the name but does not trigger a new call of OBJLoader.load().
Related
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 );
}
i create a three js program that load mtl and obj and show on scene
when run program show no texture and show black object.
i use mtl loader and obj loader and add files in root folder of host
this code work on three js site fine and i copy this code in my program but dont work for me.
i also use light ambien light and point light.
its link my model : my program
here my code:
import * as THREE from './three.module.js';
import { DDSLoader } from './jsm/loaders/DDSLoader.js';
import { MTLLoader } from './jsm/loaders/MTLLoader.js';
import { OBJLoader } from './jsm/loaders/OBJLoader.js';
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( 45, window.innerWidth / window.innerHeight, 1, 2000 );
camera.position.z = 250;
// scene
scene = new THREE.Scene();
var ambientLight = new THREE.AmbientLight( 0xcccccc, 0.4 );
scene.add( ambientLight );
var pointLight = new THREE.PointLight( 0xffffff, 0.8 );
camera.add( pointLight );
scene.add( camera );
// 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 () { };
var manager = new THREE.LoadingManager();
manager.addHandler( /\.dds$/i, new DDSLoader() );
// comment in the following line and import TGALoader if your asset uses TGA textures
// manager.addHandler( /\.tga$/i, new TGALoader() );
new MTLLoader( manager )
.setPath( '/' )
.load( 'char4.mtl', function ( materials ) {
console.log(materials);
materials.preload();
new OBJLoader( manager )
.setMaterials( materials )
.setPath( '/' )
.load( 'char4.obj', function ( object ) {
object.scale.set(20,20,20);
scene.add( object );
}, onProgress, onError );
} );
//
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
//
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseMove( event ) {
mouseX = ( event.clientX - windowHalfX ) / 2;
mouseY = ( event.clientY - windowHalfY ) / 2;
}
//
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 );
}
Your MLT file contains a Kd entry which represents the diffuse color and a map_Kd entry which represents a diffuse color texture. E.g.
Kd 0.00 0.00 0.00
map_Kd char4.png
So the diffuse color is black. The (unofficial) MTL spec says: material diffuse is multiplied by the texture value. And that means all final color values are black in your case.
You can easily fix the issue my changing all Kd values to 1.00 1.00 1.00.
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'm trying to swap image texture at runtime on a loaded three.js .obj. Here's the code straight from three.js examples with slight modification:
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 );
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
camera.position.z = 100;
//scene
scene = new THREE.Scene();
var ambient = new THREE.AmbientLight( 0x101030 );
scene.add( ambient );
var directionalLight = new THREE.DirectionalLight( 0xffeedd );
directionalLight.position.set( 0, 0, 1 );
scene.add( directionalLight );
//manager
var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
console.log( item, loaded, total );
};
//model
var loader = new THREE.OBJLoader( manager );
loader.load( 'obj/female02/female02.obj', function ( object ) {
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
//create a global var to reference later when changing textures
myMesh = child;
//apply texture
myMesh.material.map = THREE.ImageUtils.loadTexture( 'textures/ash_uvgrid01.jpg');
myMesh.material.needsUpdate = true;
}
} );
object.position.y = - 80;
scene.add( object );
} );
//render
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
window.addEventListener( 'resize', onWindowResize, false );
}
function newTexture() {
myMesh.material.map = THREE.ImageUtils.loadTexture( 'textures/land_ocean_ice_cloud_2048.jpg');
myMesh.material.needsUpdate = true;
}
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;
}
//animate
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 );
}
The only thing I added was the newTexture function and a reference to the mesh as myMesh. Here's the original example (http://threejs.org/examples/webgl_loader_obj.html). The function doesn't throw any errors but the .obj does not update. I know I'm just missing something fundamental here..
Update: Per the excellent answer below, here's the correct code with some additions to swap texture via an input field:
var container, stats;
var camera, scene, renderer;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var globalObject;
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.z = 100;
//scene
scene = new THREE.Scene();
var ambient = new THREE.AmbientLight( 0x101030 );
scene.add( ambient );
var directionalLight = new THREE.DirectionalLight( 0xffeedd );
directionalLight.position.set( 0, 0, 1 );
scene.add( directionalLight );
//manager
var manager = new THREE.LoadingManager();
manager.onProgress = function (item, loaded, total) {
console.log( item, loaded, total );
};
//model
var loader = new THREE.OBJLoader( manager );
loader.load( 'obj/female02/female02.obj', function (object) {
//store global reference to .obj
globalObject = object;
object.traverse( function (child) {
if ( child instanceof THREE.Mesh ) {
child.material.map = THREE.ImageUtils.loadTexture( 'textures/grid.jpg');
child.material.needsUpdate = true;
}
});
object.position.y = - 80;
scene.add( object );
});
//render
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseMove( event ) {
mouseX = ( event.clientX - windowHalfX ) / 2;
mouseY = ( event.clientY - windowHalfY ) / 2;
}
//animate
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 );
}
function newTexture() {
var newTexturePath = "textures/" + document.getElementById("texture").value + "";
globalObject.traverse( function ( child ) {
if (child instanceof THREE.Mesh) {
//create a global var to reference later when changing textures
child;
//apply texture
child.material.map = THREE.ImageUtils.loadTexture(newTexturePath);
child.material.needsUpdate = true;
}
});
}
The problem here is that there are multiple child meshes in the object variable. By having only one myMesh global variable, you are storing only the last child mesh. Thus when you try to update the texture using this global variable, only one of the meshes gets a texture update, probably a small hidden part that is not clearly visible.
The solution would be to either:
Store a myMeshes array global variable and push myMesh into it every time there is one. Then in your newTexture() function, iterate through all items in this array and update their maps/materials.
Or, store the object variable (the one returned from OBJLoader's callback) into one single global variable. Then in your newTexture() function, iterate through all the meshes like how it is done in the code (using traverse() and if statement), and update their maps/materials.
Lastly, calling newTexture() somewhere in your code would also help ;)