I tried loading my .obj and .mtl files and now I'm trying to change the material of the object on keypress, I'm able to do changes as expected using texture images. However when I want to change materials using a phong effect with or without texture image it's not happening.
//THIS METHOD IS WORKING FINE WHEN I USE BASIC TEXTURE IMAGES ON KEYPRESS
var texture1 = THREE.ImageUtils.loadTexture("neavik/9.jpg");
var texture2 = THREE.ImageUtils.loadTexture("neavik/10.jpg");
if (child.material.name == "meta") {
child.material.map = texture1;
child.material.needsUpdate = true;
child.receiveShadow = true;
var index = 0;
var onKeyDown = function(event) {
if (event.keyCode == 67) { // when 'c' is pressed
object.traverse(function(child) {
if (child instanceof THREE.Mesh) {
var colors = [texture2, texture1];
if (child.material.name == "meta") {
if (index == colors.length) index = 0;
child.material.map = colors[index++];
child.material.needsUpdate = true;
child.geometry.buffersNeedUpdate = true;
child.geometry.uvsNeedUpdate = true;
}
}
}
};
document.addEventListener('keyup', onKeyDown, true);
});
// Now if i try to change materials with same effect like PHONG it doesn't reflect any changes on Keypress.[ No errors as well ]
var texture1 = THREE.ImageUtils.loadTexture("neavik/9.jpg");
var texture2 = THREE.ImageUtils.loadTexture("neavik/10.jpg");
var cleana = new THREE.MeshPhongMaterial({
map: texture1,
color: 0xffffef,
specular: 0x000000,
combine: THREE.AddOperation,
reflectivity: 0
})
var cleanb = new THREE.MeshPhongMaterial({
map: texture2,
color: 0xffffef,
specular: 0x000000,
combine: THREE.AddOperation,
reflectivity: 0
})
if (child.material.name == "meta") {
child.material = cleana;
child.material.needsUpdate = true;
child.receiveShadow = true;
var index = 0;
var onKeyDown = function(event) {
if (event.keyCode == 67) { // when 'c' is pressed
object.traverse(function(child) {
if (child instanceof THREE.Mesh) {
var colors = [cleana, cleanb];
if (child.material.name == "meta") {
if (index == colors.length) index = 0;
child.material = colors[index++];
child.material.needsUpdate = true;
child.geometry.buffersNeedUpdate = true;
child.geometry.uvsNeedUpdate = true;
}
}
}
};
document.addEventListener('keyup', onKeyDown, true);
});
Please let me know if there is another way to do this.
If you want to exchange the whole material you need to do:
child.material = cleana;
or
child.material = cleanb;
and then you most likely have to do:
child.material.needsUpdate = true;
Read more on how to update material in this How to update things reference page in the chapter Materials
UPDATE
So if you want to set using an array:
var materials = [cleana, cleanb];
child.material = materials[0]; // cleana
or
child.material = materials[1]; // cleanb
and then also most likely:
child.material.needsUpdate = true;
It works totally fine with an array of materials. You don't even need to set material.needsUpdate = true. A demonstration here in this fiddle.
Related
I'm trying to load two different maya files that are animated but only one is animating, the second one isn't.
I tried to load fbx files using the fbx loaders
var loader = new THREE.FBXLoader();
loader.load('models/jumpi.fbx', function(object) {
mixer = new THREE.AnimationMixer(object);
var action = mixer.clipAction(object.animations[0]);
action.play();
window.addEventListener("keydown", function(event) {
if (event.defaultPrevented) {
return; // Do nothing if the event was already processed
keyPressed = event.key;
// If the button pressed is "e" or "E" (using caps lock or shift), then the player jumps.
if (keyPressed == "e" || keyPressed == "E") {
// call your jump function.
// console.log('working');
//action.play();
}
// Cancel the default action to avoid it being handled twice
event.preventDefault();
}, true); object.traverse(function(child) {}); scene.add(object);
});
var loader = new THREE.FBXLoader(); loader.load('models/move.fbx', function(object) {
mixer = new THREE.AnimationMixer(object);
object.traverse(function(child) {});
object.position.y = 2;
object.position.x = 50;
object.scale.x = 20;
object.scale.y = 20;
object.scale.z = 20;
scene.add(object);
});
I have recently started playing around with Threejs cars example at below URL:
https://threejs.org/examples/webgl_loader_ctm_materials.html
Fantastic piece to test realistic objects. I wanted to change materials for this car on runtime but I have been blocked due to the way that mesh is being added to the scene. I will appreciate someone can bail me out and post a fiddle or share code.
Here is how the mesh is added to the scene:
var loader = new THREE.CTMLoader();
loader.loadParts( "catalog/view/javascript/models/ctm/camaro/camaro.js", function( geometries, materials ) {
hackMaterials( materials );
for ( var i = 0; i < geometries.length; i ++ ) {
var mesh = new THREE.Mesh( geometries[ i ], materials[ i ] );
mesh.position.copy( position );
mesh.scale.copy( scale );
scene.add( mesh );
}
Here is the hackMaterials(materials) function.
function hackMaterials( materials ) {
for ( var i = 0; i < materials.length; i ++ ) {
var m = materials[ i ];
if ( m.name.indexOf( "Body" ) !== -1 ) {
var mm = new THREE.MeshStandardMaterial( );
mm.color.setHex( 0x56cc5b ); //
mm.lightMap = m.map;
//mm.envMap = textureCube;
mm.metalness = 0.5;
mm.roughness = 0.3;
materials[ i ] = mm;
}
else if ( m.name.indexOf( "tire_car" ) !== -1 ) {
var mm = new THREE.MeshStandardMaterial();
mm.color.setHex( 0x000000 );
mm.lightMap = m.map;
mm.metalness = 0.1;
mm.roughness = 0.9;
materials[ i ] = mm;
}
else if ( m.name.indexOf( "mirror" ) !== -1 ) {
var mm = new THREE.MeshStandardMaterial();
mm.color.setHex( 0x808080 );
mm.lightMap = m.map;
mm.envMap = textureCube;
mm.metalness = 0.9;
mm.roughness = 0.5;
materials[ i ] = mm;
}
else if ( m.name.indexOf( "glass" ) !== -1 ) {
var mm = new THREE.MeshStandardMaterial();
mm.color.copy( m.color );
// mm.lightMap = m.map;
mm.envMap = textureCube;
mm.metalness = 1;
mm.roughtness = 0.1;
mm.opacity = m.opacity;
mm.transparent = true;
materials[ i ] = mm;
}
else if ( m.name.indexOf( "Material.001" ) !== -1 ) {
var mm = new THREE.MeshPhongMaterial( { map: m.map } );
mm.specularMap = m.map;
mm.shininess = 30;
mm.color.setHex( 0xffffff );
mm.metal = true;
materials[ i ] = mm;
}
materials[ i ].side = THREE.DoubleSide;
}
}
Needless to point out that function hackMaterials is looping through material names in an array and then based on the names, it is assigning different values for materials.
I have been trying to use dat.gui.js but only thing I have been able to do so far is to create a color control via this code and produce console output via below code:
var color = 0xffffff;
var params = {
modelcolor: "#ffffff"
};
var gui = new dat.GUI();
var folder = gui.addFolder('Model Colour');
folder.addColor(params, 'modelcolor')
.name('Model Color')
.onChange(function() {
//var mm = new THREE.MeshStandardMaterial( {color: params.modelcolor});
//alert(params.modelcolor)
color = params.modelcolor.replace("#", "0x");
//mm.color.setHex(0xdd5353);
console.log(color);
for ( var i = 0; i < geometries.length; i ++ ) {
//console.log(materials[i].name);
if (materials[i].name.indexOf("Plane") !== -1) {
materials[i].color.setHex(0x56cc5b);
console.log("color should be changed for " + materials[i].name);
}
}
It outputs the desired color code in console but does not apply it to the car.
That will be of great help if someone could post even a basic working example with a drop down color changer.
Thanks in advance
In THREE.js, whenever you update a material and you want the effect to be updated across the scene, you need to set the following flag on the material:
material.needsUpdate = true;
Did this solve your problem or are there some other issues?
Hey if anybody can please help me animate this object :
Up - Down To Move |
Left - Right to Rotate |
a to look up |
z to look down
Link to orignal file : http://www.aacctrust.org/anim/anim.htm
JSON Model File (with animation tail-wag):
http://wikisend.com/download/654748/wolf.json
The problem is the json model file has been provided with necessary details regarding the animation of the tail. The tail of the wolf is suppose to wag.
But it doesnot , I have tried everything but to no help .
Is something wrong in the code or am I not exporting properly frm Blender.
Below is the code :
<html>
<head>
<style>
body { margin: 0; }
</style>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script src="three.js"></script>
<script>
var scene = new THREE.Scene();
var canvas = document.getElementById("myCanvas");
renderer = new THREE.WebGLRenderer({ canvas: canvas });
var camera = new THREE.PerspectiveCamera( 75, (canvas.width / canvas.height) , 1, 10000 );
var clock = new THREE.Clock(),mixer;
var forest,wolf,animation;
var fwd,bck,lft,rgt,up,down = 0 ;
var action = {};
camera.fov *= 0.3;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight);
document.body.appendChild( renderer.domElement );
renderer.setClearColor (0x22222222, 1);
camera.position.z = 28;
var material = new THREE.MeshPhongMaterial( { map: THREE.ImageUtils.loadTexture('wolf_uvcons.png') } );
// Wolf Texture Above # Forest Uses Local Materials #Blender
var loader = new THREE.JSONLoader();
loader.load('forest.json', function(geometry, materials) {
forest = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
forest.scale.x = forest.scale.y = forest.scale.z = 0.25;
forest.rotateX( Math.PI / 2 );forest.rotateZ( Math.PI ); //load :env:
forest.translation = THREE.GeometryUtils.center(geometry);
scene.add(forest);
});
loader.load('wolf.json', function(geometry, materials) {
wolf = new THREE.SkinnedMesh(geometry,material);
wolf.scale.x = wolf.scale.y = wolf.scale.z = 0.25; //load wolf
wolf.translation = THREE.GeometryUtils.center(geometry);
scene.add(wolf);
wolf.add(camera);
wolf.translateY(-27); /// Bring it down
wolf.translateZ(100); /// Bring it down
action.idle = new THREE.AnimationAction(geometry.animations[ 0 ]);
action.idle.weight = 1;
// Create animation mixer and pass object to it
mixer = new THREE.AnimationMixer(wolf);
mixer.addAction( action.idle );
});
var light = new THREE.AmbientLight(0xFFFFFFFF,1);
scene.add(light);
var pointLight = new THREE.PointLight( 0xffcccc,0.41 );
pointLight.position.set( 0, 100, 3 );
scene.add( pointLight );
var pointLight1 = new THREE.PointLight( 0xff0000,0.81 );
pointLight1.position.set( 100, 200, 3 );
scene.add( pointLight1 );
function moveWolf()
{
if (fwd==1)
{ wolf.translateZ(-1);}
if (bck==1)
{ wolf.translateZ(1);}
if (lft==1)
{ wolf.rotateY(Math.PI/200)}
if (rgt==1)
{ wolf.rotateY(-Math.PI/200);}
if (up==1)
{ camera.rotateX(Math.PI/200);}
if (down==1)
{ camera.rotateX(-Math.PI/200);}
}
function animate() {
requestAnimationFrame( animate );
moveWolf();
render();
var delta = clock.getDelta();
var theta = clock.getElapsedTime();
if ( mixer ) { mixer.update( delta ); }
}
function render() {
renderer.render( scene, camera );
}
animate();
</script>
<script>
document.onkeydown = checkKey1;
document.onkeyup = checkKey2;
function checkKey1(e) {
e = e || window.event;
if (e.keyCode == '38') {
// up arrow
fwd=1;
}
else if (e.keyCode == '40') {
// down arrow
bck=1;
}
else if (e.keyCode == '37') {
// left arrow
lft=1;
}
else if (e.keyCode == '39') {
// right arrow
rgt=1;
}
else if (e.keyCode == '65') {
up=1;
}
else if (e.keyCode == '90') {
down=1;
}
}
function checkKey2(e) {
e = e || window.event;
if (e.keyCode == '38') {
// up arrow
fwd=0;
}
else if (e.keyCode == '40') {
// down arrow
bck=0;
}
else if (e.keyCode == '37') {
// left arrow
lft=0;
}
else if (e.keyCode == '39') {
// right arrow
rgt=0;
}
else if (e.keyCode == '65') {
// right arrow
up=0;
}
else if (e.keyCode == '90') {
// right arrow
down=0;
}
}
</script>
</body>
</html>
UPDATE :
During the process of waiting for a reply I went on a self-exploration trip ;)
And found a nearly acceptable solution , steps are aa follows :
File >> Export >> Wavefront (OBJ)
Ensure that Animation is checked as option .
Click export (while exporting plz do it in a separate folder as no of files could be large depending on the number of frames.)
Copy the folder in Blender > Python > Bin directory.
Copy convertor from three.js utils OBJ for python3 to Blender > Python > Bin directory.
Launch command prompt in Admin mode and run the following command :
python objtothreejs_conv_python3 -i meshdirname\meshname_000001.obj -o output.js -m "meshdirname\meshname_*.obj"
Output Animation would be morph animation and would require some changes in the mixer for playing MorphAnims.
var leftf;
var rightf;
$(document).keyup(function() {
clearInterval(leftf);
clearInterval(rightf);
});
$(document).keydown(function (e) {
if (e.which == 37) {
// Left Arrow Pushed
leftf=setInterval(function(){
meshes[0].rotation.y=Math.PI/4;
if(meshes[0].position.x>-3.5)meshes[0].position.x-=0.1;
console.log(meshes[0].position.x);
},1000/engine.getFps());
} else if (e.which == 39) {
// Right Arrow Pushed
meshes[0].rotation.y=3*Math.PI/4;
//meshes[0].translate(BABYLON.Axis.X, Math.sin(v), BABYLON.Space.WORLD);
rightf=setInterval(function(){
meshes[0].position.x+=0.1;
},1000/engine.getFps());
}
});
Can you please tell me why this is not working in the browser although it is in my opinion the right way of moving the mesh on the screen without being torn (torn animation)?
It starts moving the mesh correctly but after a while the mesh is flying around without the logic. Is setting and clearing the Interval such a problem for the browsers?
Thank you.
Now it is running, perhaps I have a solution:
<!DOCTYPE html>
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Babylon.js sample code keyboard arrows</title>
<!-- Babylon.js -->
<script src="index_subory/hand.js"></script>
<script src="index_subory/cannon.js"></script>
<script src="index_subory/oimo.js"></script>
<script src="index_subory/babylon.2.0.debug.js"></script>
<script src="index_subory/jquery.min.js"></script>
<style>
html, body {
overflow: hidden;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#renderCanvas {
width: 100%;
height: 100%;
touch-action: none;
}
</style>
</head>
<body>
<div id="idecko" style="background-color:grey;color:white;font-weight:bold;margin-left:auto;margin-right:auto;text-align:center;">text </div>
<canvas height="782" width="1440" id="renderCanvas"></canvas>
<script>
var canvass = $('#renderCanvas');
// check to see if we can do webgl
// ALERT FOR JQUERY PEEPS: canvas is a jquery obj - access the dom obj at canvas[0]
var dcanvas = canvass[0];
expmt = false;
if ("WebGLRenderingContext" in window) {
//alert("browser at least knows what webgl is.");
}
// some browsers don't have a .getContext for canvas...
try {
gl = dcanvas.getContext("webgl");
}catch (x){
gl = null;
}
if (gl == null) {
try {
gl = dcanvas.getContext("experimental-webgl");
}catch (x){
gl = null;
}
if (gl == null) {
//console.log('but can\'t speak it');
}else {
expmt = true; //alert('webgl experimentally.');
}
} else {
//alert('webgl natively');
}
if (gl || expmt) {
//alert("loading webgl content.");
} else {
alert("CHYBA: Váš prehliadač nepodporuje WebGL, ľutujeme. (ERROR: Your browser does not support WebGL, sorry.)");
canvas.remove();
}
if (BABYLON.Engine.isSupported()) {
var canvas = document.getElementById("renderCanvas");
var engine = new BABYLON.Engine(canvas, true);
var scene = new BABYLON.Scene(engine);
// Skybox
var skybox = BABYLON.Mesh.CreateBox("skyBox", 800.0, scene);
var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", scene);
skyboxMaterial.backFaceCulling = false;
skyboxMaterial.reflectionTexture = new BABYLON.CubeTexture("index_subory/skybox/cubemap", scene);
skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
skybox.material = skyboxMaterial;
//var sphere = BABYLON.Mesh.CreateSphere("sphere", 1.0, 1.0, scene);
var createScene = function () {
// setup environment
var light0 = new BABYLON.PointLight("Omni", new BABYLON.Vector3(0, 10,80), scene);
var camera = new BABYLON.FreeCamera("FreeCamera", new BABYLON.Vector3(0, 0, -5), scene);
var light2 = new BABYLON.PointLight("Omni", new BABYLON.Vector3(10, 10, -80), scene);
var turnLeft = false; var turnRight = false;
var accelerate = false; var breaking = false;
BABYLON.SceneLoader.ImportMesh("Cube.001", "index_subory/", "jet2b.babylon", scene,function(meshes){
meshes[0].position.x = Math.round((Math.random() * 1) + 0);
meshes[0].position.y = Math.round((Math.random() * 1) + 0);
var speed = 0;
scene.registerBeforeRender(function() {
if (scene.isReady()) {
camera.target = sphere.position;
speed=0.02;
if (turnRight) {
meshes[0].rotation.y=3*Math.PI/4;
meshes[0].position.x += speed;
}
if (turnLeft) {
meshes[0].rotation.y=Math.PI/4;
meshes[0].position.x -= speed;
}
if (breaking) {
meshes[0].rotation.y=Math.PI/2;
meshes[0].position.y -= speed;
}
if (accelerate) {
meshes[0].rotation.y=Math.PI/2;
meshes[0].position.y += speed;
}
}
});
var sphere = BABYLON.Mesh.CreateSphere("sphere", 0.5, 0.5, scene);
var simpleMaterial = new BABYLON.StandardMaterial("texture2", scene);
simpleMaterial.diffuseColor = new BABYLON.Color3(0, 1, 0);//Green
sphere.material=simpleMaterial;
sphere.position.x = Math.floor((Math.random() * 2) );
sphere.position.y = Math.floor((Math.random() * 2) );
sphere.position.z=3;
var myVar2;
function myFunction2() {
myVar = setInterval(function(){
//sphere.translate(BABYLON.Axis.Z, -0.1, BABYLON.Space.WORLD);
sphere.position.z-=0.1;
var delta=0.2;
if(Math.abs(Math.round(meshes[0].position.x-sphere.position.x))<=delta&&Math.abs(Math.round(meshes[0].position.y-sphere.position.y))<=delta&&Math.abs(Math.round(meshes[0].position.z-sphere.position.z))<=delta){
$('#idecko').html('<span style=\'background-color:yellow;color:red;\'>BANG! Červeného trpaslíka trafila zelená planéta! (Red dwarf shot by green planet!)</span>');
//$('#idecko').append("<embed src='index_subory/explosion.mp3' hidden=true autostart=true loop=false>");
if(navigator.userAgent.indexOf("Trident")==-1)var audio = new Audio('index_subory/explosion.mp3');
if(navigator.userAgent.indexOf("Trident")!=-1)var audio = new Audio('index_subory/explosion.wav');
audio.loop = false;
audio.play();
simpleMaterial.diffuseColor = new BABYLON.Color3(0, 0, 1);//Green
sphere.material=simpleMaterial;
}else{
$('#idecko').html('<span style=\'background-color:grey;color:white;\'>Unikaj červený trpaslík (šípky na klávesnici)! (Run away red dwarf (keyboard arrows)!)</span>');
}
if(sphere.position.z<-5){
sphere.position.x = Math.floor((Math.random() * 2) );
sphere.position.y = Math.floor((Math.random() * 2) );
sphere.position.z=3;
simpleMaterial.diffuseColor = new BABYLON.Color3(0, 1, 0);//Green
sphere.material=simpleMaterial;
}
}, 50);
}
function myStopFunction2() {
clearTimeout(myVar2);
}
myFunction2();
$(document).keyup(function (evt) {
if (evt.keyCode == 37 || evt.keyCode == 39) {
turnLeft = false;
turnRight = false;
}
if (evt.keyCode == 38 || evt.keyCode == 40) {
accelerate = false;
breaking = false;
}
});
$(document).keydown(function (evt) {
if (!scene)
return;
//console.log(evt.keyCode);
if (evt.keyCode == 32) {
}
//Key LEFT
if (evt.keyCode == 37) {
turnLeft = true;
turnRight = false;
}
//Key RIGHT
if (evt.keyCode == 39) {
turnLeft = false;
turnRight = true;
}
//Key UP
if (evt.keyCode == 38) {
accelerate = true;
breaking = false;
}
//Key BACK
if (evt.keyCode == 40) {
breaking = true;
accelerate = false;
}
});
});
return scene;
}
var scene = createScene();
var assetsManager = new BABYLON.AssetsManager(scene);
//var meshTask = assetsManager.addMeshTask("jet2 task", "", "./index_subory/", "jet2.babylon");
var textTask0 = assetsManager.addTextFileTask("text task0", "./index_subory/jet2b.babylon");
var textTask1 = assetsManager.addTextFileTask("text task1", "./index_subory/hand.js");
var textTask2 = assetsManager.addTextFileTask("text task2", "./index_subory/cannon.js");
var textTask3 = assetsManager.addTextFileTask("text task3", "./index_subory/oimo.js");
var textTask4 = assetsManager.addTextFileTask("text task4", "./index_subory/babylon.2.0.debug.js");
var textTask5 = assetsManager.addTextFileTask("text task5", "./index_subory/jquery.min.js");
var binaryTask1 = assetsManager.addBinaryFileTask("binary task 1", "./index_subory/explosion.mp3");
var binaryTask2 = assetsManager.addBinaryFileTask("binary task 2", "./index_subory/explosion.wav");
var binaryTask3 = assetsManager.addBinaryFileTask("binary task 3", "./index_subory/skybox/cubemap_nx.jpg");
var binaryTask4 = assetsManager.addBinaryFileTask("binary task 4", "./index_subory/skybox/cubemap_ny.jpg");
var binaryTask5 = assetsManager.addBinaryFileTask("binary task 5", "./index_subory/skybox/cubemap_nz.jpg");
var binaryTask6 = assetsManager.addBinaryFileTask("binary task 6", "./index_subory/skybox/cubemap_px.jpg");
var binaryTask7 = assetsManager.addBinaryFileTask("binary task 7", "./index_subory/skybox/cubemap_py.jpg");
var binaryTask8 = assetsManager.addBinaryFileTask("binary task 8", "./index_subory/skybox/cubemap_pz.jpg");
//engine.displayLoadingUI();
engine.loadingUIText = "Loading... (Načítavanie...)";
assetsManager.onTaskSuccess = function (task) {
// Do something with task.data.
//engine.hideLoadingUI();
};
assetsManager.onTaskError = function (task) {
// Do something with task.data.
alert('Error with loading by assetsManager...');
};
assetsManager.onFinish = function (task) {
//engine.hideLoadingUI();
engine.setSize($(window).width(), $(window).height());
engine.runRenderLoop(function () {
scene.render();
});
};
assetsManager.load();
// Resize
window.addEventListener("resize", function () {
engine.resize();
});
}else{
alert("Chyba: Nemôžem spustiť WebGL. (Error: Can't run WebGL.)");
}
</script>
</body></html>
I am new to three.js and I am making an augmented reality app on web to show plates of food. So far I have managed to show a cube. The problem raised when I tried to show a model.obj instead of geomerty and material in mesh. Can anyone please help me on how to put a model.obj in THREE.MESH since I cannot do it. Below is my code.
function createContainer() {
var model = new THREE.Object3D();
model.matrixAutoUpdate = false;
return model;
}
function createMarkerMesh(color) {
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);
loader.load(texturePath, function (image) {
texture.image = image;
texture.needsUpdate = true;
texture.transparent = true;
});
var loader = new THREE.OBJLoader(manager);
return loader.load(objectPath, function (object) {
object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.material.map = texture;
child.material.transparent = true;
}
});
object.position.z = -50;
return object;
});
// var geometry = new THREE.CubeGeometry( 100,100,100 );
//var material = new THREE.MeshPhongMaterial( {color:color, side:THREE.DoubleSide } );
var mesh = new THREE.Mesh( object.geometry, object.material);
mesh.position.z = -50;
return mesh;
}
function createMarkerObject(params) {
//return createMarkerMesh(params.color);
var modelContainer = createContainer();
var modelMesh = createMarkerMesh(params.color);
console.log(modelMesh);
modelContainer.add( modelMesh);
function transform(matrix) {
modelContainer.transformFromArray( matrix );
}
return {
transform: transform,
model: modelContainer
}
return {
createMarkerObject:createMarkerObject
}
}
The code in function Create MArker MEsh is were the cube was created and worked fine now I have commented those parts and tried to show the object but nothing is happening please help me.
try this change in your code... let me know if any problem raise..
function createMarkerMesh(color) {
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);
loader.load(texturePath, function (image) {
texture.image = image;
texture.needsUpdate = true;
texture.transparent = true;
});
var tmpMesh;
var loader = new THREE.OBJLoader(manager);
loader.load(objectPath, function (object) {
var group = new THREE.Object3D()
object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.material.map = texture;
child.material.transparent = true;
//here in child the geometry and material are available
var mesh = new THREE.Mesh( child.geometry, child.material);
//mesh.position.z = -50;
group.add(mesh);
}
});
group.position.z = -50;
scene.add(group);//return group;
});
}
Finally I have found an answer for this problem and here I am going to explain what the problem was with the above code. Hope that this will help.
The problem was that the createMarkerObject was being called before the mesh was created so the object3D container was being filled with an empty mesh. To arrange this I have declared the modelContainer as a global variable and inserted it in the createMarkerMesh function. In the createMarkerObject I have made an if condition so that it checks if the modelContainer is full before adding it to the object3D container. Below is the updated code.
//Loads the model and texture and creates a mesh returns mesh with model
function createMarkerMesh() {
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);
loader.load(texturePath, function (image) {
texture.image = image;
texture.needsUpdate = true;
texture.transparent = true;
});
var tmpMesh, mesh;
var loader = new THREE.OBJLoader(manager);
loader.load(objectPath, function (object) {
tmpMesh = object; //store the object in a variable
object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.material.map = texture;
child.material.transparent = true;
}
});
mesh = new THREE.Mesh( tmpMesh.children[0].geometry, tmpMesh.children[0].material);
mesh.position.z = -10;
mesh.scale.set( 3, 3, 0 );
console.log(mesh);
modelContainer.add( mesh);
console.log(modelContainer);
//return mesh;
});
}
//Creates the position of the object on the marker
function createMarkerObject() {
modelContainer = createContainer();
var modelMesh = createMarkerMesh();
//console.log(modelMesh);
if(modelMesh){
modelContainer.add( modelMesh);
}
function transform(matrix) {
modelContainer.transformFromArray( matrix );
}
return {
transform: transform,
model: modelContainer
}
return {
createMarkerObject:createMarkerObject
}
}