.obj file in javascript is not moving when using keyboard - javascript

The most important part in my code is in JavaScript. I want that my objects can move when I press "down" or "right" or etc. The problem is that object from .json file is moving, but object from .obj file is not. Is it possible to fix that?
This is my code:
<script>
var container, scene, camera, renderer, controls, stats;
var keyboard = new THREEx.KeyboardState();
var keyboard = new KeyboardState();
var galva;
init();
animate();
render();
function init()
{
var spgeometry = new THREE.SphereGeometry( 30, 32, 32 );
var spmaterial = new THREE.MeshBasicMaterial( {color: 0x00000} );
galva = new THREE.Mesh( spgeometry, spmaterial );
galva.position.set(125, 150, 90);
scene.add( galva );
var jsonLoader = new THREE.JSONLoader();
jsonLoader.load( "models/android.js", addModelToScene );
var loader = new THREE.OBJLoader();
loader.load("models/teaport.obj", function ( object ) {
var material = new THREE.MeshLambertMaterial( );
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material = material;
}
} );
object.scale.set(50,50,50);
scene.add( object );
} );
}
function addModelToScene( geometry, materials )
{
var material = new THREE.MeshLambertMaterial( materials );
c = new THREE.Mesh( geometry, material );
c.scale.set(50,50,50);
scene.add( c );
}
function update()
{
keyboard.update();
if ( keyboard.down("left") ){
galva.translateX( -50 );
}
if ( keyboard.down("right") ){
c.translateX( 50 );
galva.translateX( 50 );
object.translateX( 50 );
}
controls.update();
stats.update();
}

If you put together a jsfiddle or something similar - it could be easier to figure out. I think you end up with variable shadowing, and your "object" is simply undefined. Try following change.
var loader = new THREE.OBJLoader();
loader.load("models/teaport.obj", function ( o ) {
var material = new THREE.MeshLambertMaterial( );
o.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material = material;
}
} );
o.scale.set(50,50,50);
scene.add( o );
object = o; // <-- important

Related

Three.js animation mixer not playing?

Ok I have an fbx successfully loaded into Three.js exported from blender with all animation boxes checked. Ive tried all export settings from blender so that's not it.
This is how I bring the model in, and I am able to accurately determine whether the fbx has animations or not:
var geoFromScene = new THREE.Geometry();
var FBXLoader = require('three-fbx-loader');
var loader = new FBXLoader();
loader.load(string, function ( object ) {
object.traverse( function ( child ) {
if ( child.isMesh ) {
child.castShadow = true;
child.receiveShadow = true;
geoFromScene = (new THREE.Geometry()).fromBufferGeometry(child.geometry);
}
} );
var theModel = new THREE.Mesh();
theModel.geometry = geoFromScene;
theModel.material = material;
theModel.position.set(5,5,-8);
//theModel.rotation.set(new THREE.Vector3( 0, MATH.pi/2, 0));
theModel.scale.set(0.1, 0.1, 0.1);
localThis.scene.add(theModel);
localThis.mixer = new THREE.AnimationMixer(theModel);
if(theModel.animations[0])
{
var action = localThis.mixer.clipAction(theModel.animations[0]);
action.play();
} else {
console.log("No animations");
}
} );
In update (which does work, because I can print the animation.time):
this.mixer.update(this.clock.getDelta());
And yet the model is just static. Whats wrong here?
UPDATE:
code from example copy pasted-
var geoFromScene = new THREE.Geometry();
var FBXLoader = require('three-fbx-loader');
var loader = new FBXLoader();
loader.load( string, function ( object ) {
localThis.mixer = new THREE.AnimationMixer( object );
var action = localThis.mixer.clipAction( object.animations[ 0 ] );
action.play();
object.traverse( function ( child ) {
if ( child.isMesh ) {
child.castShadow = true;
child.receiveShadow = true;
}
} );
object.position.set(5,5,-8)
object.scale.set(0.1, 0.1, 0.1);
localThis.scene.add( object );
} );
in animate-
this.mixer.update(this.clock.getDelta());
All I get is the model armature it seems -
New approach:
var FBXLoader = require('wge-three-fbx-loader'); //https://www.npmjs.com/package/wge-three-fbx-loader
var loader = new FBXLoader();
loader.load( string, function ( object ) {

Multiple scenes and multiple .obj models in Three.js

I am stuck with loading in two .obj models into two different div elements.
Currently, both objects end up in the last div element, as seen here:
https://casagroupproject.github.io/template1/test.html
My code is based on this example here:
https://threejs.org/examples/?q=mul#webgl_multiple_elements
I create an array with my models stored in:
var canvas;
var scenes = [], renderer;
var scene;
//external geometries
var models = {
tent: {
obj:"./assets/Tent_Poles_01.obj",
},
campfire: {
obj:"./assets/Campfire_01.obj",
}}
init();
animate();
I then load them in a loop in init():
for( var _key in models ){
scene = new THREE.Scene();
var element = document.createElement( "div" );
element.className = "list-item";
element.innerHTML = template.replace( '$', _key);
console.log('does this work', element.innerHTML);
scene.userData.element = element.querySelector( ".scene" );
content.appendChild( element );
var camera = new THREE.PerspectiveCamera( 50, 1, 1, 10 );
camera.position.z = 2;
scene.userData.camera = camera;
var objLoader = new THREE.OBJLoader();
objLoader.load(
models[_key].obj,
function ( object ) {
scene.add( object );
console.log(object);
},
);
}
And render them here:
renderer = new THREE.WebGLRenderer( { canvas: canvas, antialias: true } );
renderer.setClearColor( 0xffffff, 1 );
renderer.setPixelRatio( window.devicePixelRatio );
Why do both models end up in the last div?

How to use multiple texture use in `OBJLoader` three.js?

How to multiple textures material use in Three.js?.Here three textures using and one 3D sofa.obj format file. I tried a lot of time. Below my code. What do I mistake in my code?
var loader = new THREE.OBJLoader();
var textureLoader = new THREE.TextureLoader();
threeDTexture = new THREE.ImageUtils.loadTexture( 'models/Sofa/Texturses/paradis_beige.jpg' );
threeDTexture2 = new THREE.ImageUtils.loadTexture( 'models/Sofa/Texturses/1.jpg' );
threeDTexture3 = new THREE.ImageUtils.loadTexture( 'models/Sofa/Texturses/2.jpg' );
loader.load('models/Sofa/sofa.obj', function (object) {
var geo = object.children[0].geometry;
var mats = [threeDTexture, threeDTexture2,threeDTexture3];
objct = new THREE.Mesh(geo, mats);
object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.material = objct;
}
});
object.position.x = posX;
object.position.y = 0;
object.position.z = posZ;
var size = new THREE.Box3().setFromObject(object).getSize();
object.scale.set(width/size.x, height/size.y, depth/size.z);
scene1.add(object);
console.log(object);
console.log(size);
console.log(width/size.x, height/size.y, depth/size.z);
},
function ( xhr ) {
returnValue = ( xhr.loaded / xhr.total * 100 ) + '% loaded';
console.log(returnValue);
},
function ( error ) {
console.log( 'An error happened' );
}
);
break
first, the textureLoader declared on line-2 is not in use;
second, belowing mats is not an Material Array, you should new MeshBasicMaterial(...) to wrap a texture, see the document here.
var mats = [threeDTexture, threeDTexture2,threeDTexture3];
objct = new THREE.Mesh(geo, mats); // Mesh will not accept this mats param!

THREE.js : why THREE.DoubleSide not working in collada model?

I have collada model (.dae) displayed by this code, and I add THREE.DoubleSide but it dose not work how can i fix this?
var loadingManager = new THREE.LoadingManager( function() {
scene.add( car );
} );
var loader = new THREE.ColladaLoader( loadingManager );
var textureLoader = new THREE.TextureLoader();
var texture = textureLoader.load('./model/car_Red.jpg');
loader.options.convertUpAxis = true;
loader.load( './car.dae', function ( collada ) {
car = collada.scene;
car.traverse(function (node) {
if (node.isMesh)
{
node.material.map = texture;
node.material.side = THREE.DoubleSide;
}
});
console.log(car);

texture didn't load in to 3d object(mapping)

texture is not loaded in to ring 3d model.but it will work for some other objects.there is no compile errors.I set the all all light condition correctly.but 3d model color is grey/black.texture loaded for other object correctly.3d object file format is .obj,I didn't load mtl file to my code. mtlobjloader is not in threejs.org,there are someway to load mtl file and mapping the texture to object.
plz help me.
enter code here
<html>
<head>
<title> Test Three.js</title>
<style type="text/css">
BODY
{
margin: 0;
}
canvas
{
width: 100%;
height:100%;
}
</style>
</head>
<body>
<div>
<p>Color:
<button class="jscolor{onFineChange:'onClick(this)',valueElement:null,value:'66ccff'}"
style="width:50px; height:20px;"></button>
</p>
<p>Object:
<button style="width:50px; height:20px;" id="object"></button>
</p>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="three.min.js"></script>
<script src="TrackballControls.js"></script>
<script src="jscolor.js"></script>
<script src="AmbientLight.js"></script>
<script src="SpotLight.js"></script>">
<script src="JSONLoader.js"></script>">
<script src="ObjectLoader.js"></script>">
<script src="OBJLoader.js"></script>">
<script src="MTLLoader.js"></script>">
<script src="Material.js"></script>">
<script src="MeshPhongMaterial.js"></script>">
<script>
function onClick(jscolor) {
cube.material.color = new THREE.Color('#'+jscolor);
cube.material.needsUpdate = true;
};
var onClicked=function (){
scene.remove(cube);
var material1 = new THREE.LineBasicMaterial({
color: 'red'
});
var geometry1 = new THREE.Geometry();
geometry1.vertices.push(
new THREE.Vector3( -10, 0, 0 ),
new THREE.Vector3( 0, 10, 0 ),
new THREE.Vector3( 10, 0, 0 )
);
var cube1 = new THREE.Line( geometry1, material1 );
scene.add( cube1);
};
$('#object').click(onClicked);
var scene =new THREE.Scene();
var camera=new THREE.PerspectiveCamera(45,window.innerWidth/window.innerHeight,0.1,1000);
var controls =new THREE.TrackballControls(camera);
controls.addEventListener('change',render);
var renderer = new THREE.WebGLRenderer( { alpha: true });
renderer.setSize(window.innerWidth,window.innerHeight);
document.body.appendChild(renderer.domElement);
/*var material = new THREE.MeshLambertMaterial({color:'red'});
var geometry=new THREE.CubeGeometry(100,100,100);
var cube=new THREE.Mesh(geometry,material);
scene.add(cube);*/
camera.position.z=500;
var light = new THREE.AmbientLight( 0x404040 );
light.intensity = 0;
light.position.z=10;
light.position.y=10; // soft white light
scene.add( light );
// }
//init();
/* var loader = new THREE.JSONLoader();
loader.load( 'ring.json', function ( geometry ) {
var mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
mesh.position.x =500;
mesh.position.y =100;
mesh.position.z =500;
scene.add( mesh );
}); *//*
var loader = new THREE.ObjectLoader();
loader.load("ring.json",function ( obj ) {
THREE.ImageUtils.crossOrigin = '';
var texture = THREE.TextureLoader("images.jpg");
//obj.map= texture;
obj.scale.set (10,10,10);
obj.traverse( function( child ) {
if ( child instanceof THREE.Mesh ) {
child.geometry.computeVertexNormals();
child.material.map=texture;
}
} );
scene.add( obj );
});*/
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( 'brick_bump.jpg', 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;
} );
var loader = new THREE.OBJLoader(manager);
/*var Mloader= new THREE.MTLLoader(manager);
Mloader.load('ring.mtl',function(object){
object.traverse( function ( child ) {
if (child.material instanceof THREE.MeshPhongMaterial ) {
child.material.map = texture;
}
} );
scene.add( object );
});*/
// 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( 'ring1.obj', function ( event ) {
var object = event;
/*for ( var i = 0, l = object.children.length; i < l; i ++ ) {
object.children[ i ].material.map = texture;
console.log("rgr"+ object);
}*/
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material.map = texture;
console.log("rgr"+ object.children);
}
} );
// My initial model was too small, so I scaled it upwards.
object.scale = new THREE.Vector3( 25, 25, 25 );
// 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 );
});
function render(){
renderer.render(scene,camera);
}
function animate(){
requestAnimationFrame(animate);
controls.update();
}
animate();
</script>
</body>
</html>
First I would check the ring.obj file. You'll need to verify that the ring.obj file is exporting with UV values on all vertexes. UV values assign points on the texture to specific points on the mesh. E.g. they define how the texture is draped over the surface. If you do not have control of the ring.obj export process to quality assure it, there was a conversation on stack about generating UVs at load time here:
THREE.js generate UV coordinate
But your milage may vary if the mesh author had specific texture anchors.
This may not be the issue, but since the texture is working for other meshes, I would think there is an issue with the ring mesh.

Categories