Importing Blender obj file with mtl to ThreeJS - javascript

I am trying to import an object file that I created in Blender to ThreeJS. My Blender project looks like this:
image
I exported it into a waveform, for importing into ThreeJS I used MTLLoader and OBJLoader, here is my code:
<script>
var container;
var camera, controls, scene, renderer, dragControls;
var lighting, ambient, keyLight, fillLight, backLight;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var keyboard = {};
var floor;
var objects = [];
var meshes = [];
var cameraParams = {speed: 0.1, turnSpeed: Math.PI * 0.5};
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2(1, 1), INTERSECTED;
init();
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000);
camera.position.set(0, 7, 25);
scene = new THREE.Scene();
ambient = new THREE.AmbientLight(0xffffff, 1.0);
scene.add(ambient);
keyLight = new THREE.DirectionalLight(new THREE.Color('hsl(30, 100%, 75%)'), 1.0);
keyLight.position.set(-100, 0, 100);
fillLight = new THREE.DirectionalLight(new THREE.Color('hsl(240, 100%, 75%)'), 0.75);
fillLight.position.set(100, 0, 100);
backLight = new THREE.DirectionalLight(0xffffff, 1.0);
backLight.position.set(100, 0, -100).normalize();
scene.add(keyLight);
scene.add(fillLight);
scene.add(backLight);
// load model
loadMesh('road', function(obj){
obj.position.y = 0;
obj.scale.x = 1;
obj.scale.y = 1;
obj.scale.z = 1;
addMesh(obj);
});
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(new THREE.Color('hsl(0, 0%, 10%)'));
container.appendChild(renderer.domElement);
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.enableZoom = false;
dragControls = new THREE.DragControls(objects, camera, renderer.domElement);
dragControls.addEventListener('dragstart', function (event) {
event.object.material.emissive.set(0xaaaaaa);
controls.enabled = false;
});
dragControls.addEventListener('dragend', function (event) {
event.object.material.emissive.set(0x000000);
controls.enabled = true;
});
window.addEventListener('resize', onWindowResize, false);
window.addEventListener('keydown', keyDownEvent, false);
window.addEventListener('keyup', keyUpEvent, false);
window.addEventListener('mousemove', onMouseMove, false);
}
function addMesh(mesh) {
meshes.push(mesh);
scene.add(mesh);
}
function loadMesh(name, callback) {
var objLoader = new THREE.OBJLoader();
var matLoader = new THREE.MTLLoader();
matLoader.setPath('assets/');
matLoader.load('ROAD2.mtl', function(materials) {
materials.preload();
objLoader.setMaterials(materials);
objLoader.setPath('assets/');
objLoader.load('ROAD2.obj', function (obj) {
callback(obj);
});
});
}
function onWindowResize() {
camera.aspect = window.innerWidth/window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function keyDownEvent(event) {
keyboard[event.keyCode] = true;
}
function keyUpEvent(event) {
keyboard[event.keyCode] = false;
}
function onMouseMove(event) {
event.preventDefault();
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
}
function animate() {
requestAnimationFrame(animate);
if (keyboard[37]) { // left arrow key
camera.rotation.y += cameraParams.turnSpeed;
}
if (keyboard[39]) { // right arrow key
camera.rotation.y -= cameraParams.turnSpeed;
}
controls.update();
render();
}
function render() {
renderer.render(scene, camera);
}
</script>
My Blender scene rarely loads in my browser, when it does, it is without any textures. Most of the time my tab crashes before anything is able to load in because is eats up all my RAM (using Firefox and http-server to load the html). I am out of ideas about what the problem is, haven't been able to find anything on Google, most of the examples were of one object with materials and textures.
My file hierarchy looks like this in case it is important:
index.html
js/
DragControls1.js
MTLLoader.js
OBJLoader.js
OrbitControls.js
three.js
assets/
ROAD2.mtl
ROAD2.obj
cottage_textures.png
road_texture.png
Any help would be appreciated.

It seems that your scene has about 7'000'000 vertices, which is not a little but a little too much.
In Blender, try to do the export in several smaller objects. For example each one separately, the street, a tree, one of the houses, etc.
With this method, you can approach the limit of your scene.
Also, try to duplicate multiple objects in your scene in the code instead of doing it in Blender!
(In realtime 3D applications you should always try to use optimal 3D models (geometry, topology) and not oversized models with several million vertices)

Related

three.js - object look at mouse

Ok I understand it seems I did not try hard enough but I am really new to this
and I get no errors what so ever in Dreamweaver.
I deleted my old example and this is what I have now, trying to integrate
the look at function with the OBJ loader, camera and lights.
I think I understand what is happening more or less in the code,
but it's still not working, I assume it's because there is a code for
window resize but the look at function dose not take that into account,
thus it's not working since the function assume a fixed window size,
Am I right here?
Also I am not sure I need the two commented lines in the obj loader
object.rotateX(Math.PI / 2); and object.lookAt(new THREE.Vector3(0, 0, 0));
since this is just to get the starting position?
if I put these tow lines back, it will just rotate the object into an initial pose but the object will not turn relative to mouse position.
I am really not sure what is conflicting here
I changed the code now to this:
<script>
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var camera, scene;
var canvasRenderer, webglRenderer;
var container, mesh, geometry, plane;
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(40, window.innerWidth / window.innerHeight, 1, 1500);
camera.position.x = 0;
camera.position.z = 100;
camera.position.y = 0;
camera.lookAt({
x: 0,
y: 0,
z: 0,
});
scene = new THREE.Scene();
// LIGHTS
scene.add(new THREE.AmbientLight(0x666666, 0.23));
var light;
light = new THREE.DirectionalLight(0xffc1c1, 2.20);
light.position.set(0, 100, 0);
light.position.multiplyScalar(1.2);
light.castShadow = true;
light.shadowCameraVisible = true;
light.shadowMapWidth = 512;
light.shadowMapHeight = 512;
var d = 50000;
light.shadowCameraLeft = -d;
light.shadowCameraRight = d;
light.shadowCameraTop = d;
light.shadowCameraBottom = -d;
light.shadowcameranear = 0.5;
light.shadowCameraFar = 1000;
//light.shadowcamerafov = 30;
light.shadowDarkness = 0.1;
scene.add(light);
var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath( 'model/' );
mtlLoader.load( 'rope.mtl', function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.setPath( 'model/' );
objLoader.load( 'rope.obj', function ( object ) {
var positionX = 0;
var positionY = 0;
var positionZ = 0;
object.position.x = positionX;
object.position.y = positionY;
object.position.z = positionZ;
object.scale.x = 1;
object.scale.y = 1;
object.scale.z = 1;
//object.rotateX(Math.PI / 2);
//object.lookAt(new THREE.Vector3(0, 0, 0));
// castshow setting for object loaded by THREE.OBJLoader()
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.castShadow = true;
child.receiveShadow = true;
}
});
scene.add(object);
});
});
// RENDERER
//webglRenderer = new THREE.WebGLRenderer();
webglRenderer = new THREE.WebGLRenderer({
antialias: true
});
webglRenderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
webglRenderer.domElement.style.position = "relative";
webglRenderer.shadowMapEnabled = true;
webglRenderer.shadowMapSoft = true;
//webglRenderer.antialias: true;
container.appendChild(webglRenderer.domElement);
window.addEventListener('resize', onWindowResize, false);
}
window.addEventListener("mousemove", onmousemove, false);
var plane = new THREE.Plane(new THREE.Vector3(0, 0, 0), 0);
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var intersectPoint = new THREE.Vector3();
function onmousemove(event) {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
raycaster.ray.intersectPlane(plane, intersectPoint);
object.lookAt(intersectPoint);
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
webglRenderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
camera.lookAt(scene.position);
webglRenderer.render(scene, camera);
}
</script>
I took your code and adapted so it doesn't require a obj and put it into this codepen. The main problem seems to be that your intersection plane was defined incorrectly. The first argument is the normal vector which needs to be of length 1. Yours is 0. Therefore there are no meaningful intersections.
var plane = new THREE.Plane(new THREE.Vector3(0, 0, 0), 0);
If you change it to
var plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 10);
the intersections are more meaningful and the object actually rotates.

How to control fps with requestAnimationFrame?

I have used FBX format with three js. It seems like requestAnimationFrame is the de facto way to animate things now. The animation was working very speed, Like lightening. Can't find any solutions to control the fps.
See the below image.
Source code:
if (!Detector.webgl)
Detector.addGetWebGLMessage();
var container, stats, controls;
var camera, scene, renderer, light, mesh;
var clock = new THREE.Clock();
var mixers = [];
var mouseX = 0, mouseY = 0;
var spdx = 0, spdy = 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(60, window.innerWidth / window.innerHeight, 1, 2000);
scene = new THREE.Scene();
// grid
var gridHelper = new THREE.GridHelper(28, 28, 0x303030, 0x303030);
gridHelper.position.set(0, -0.04, 0);
scene.add(gridHelper);
// stats
stats = new Stats();
container.appendChild(stats.dom);
// model
var manager = new THREE.LoadingManager();
manager.onProgress = function (item, loaded, total) {
console.log(item, loaded, total);
};
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) {
console.error(xhr);
};
var loader = new THREE.FBXLoader(manager);
loader.load('assests/JetEngine_Ani.fbx', function (object) {
object.mixer = new THREE.AnimationMixer(object);
mixers.push(object.mixer);
var action = object.mixer.clipAction(object.animations[ 0 ]);
action.play();
scene.add(object);
}, onProgress, onError);
renderer = new THREE.WebGLRenderer({alpha: true});
renderer.setClearColor(0xdddddd, 1);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.target.set(0, 12, 0);
camera.position.z = 850;
controls.update();
window.addEventListener('resize', onWindowResize, false);
light = new THREE.HemisphereLight(0xffffff, 0x444444, 1.0);
light.position.set(0, 1, 0);
scene.add(light);
light = new THREE.DirectionalLight(0xffffff, 1.0);
light.position.set(0, 1, 0);
scene.add(light); }
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;
mouseY = event.clientY;
}
function animate() {
requestAnimationFrame(animate);
if (mixers.length > 0) {
for (var i = 0; i < mixers.length; i++) {
mixers[ i ].update(clock.getDelta());
}
}
stats.update();
render();
}
function render() {
renderer.render(scene, camera);
}
How to control the animation speed. Is there have other ways or only through fps(frames per second).
How can I reduce the animation speed??..
You want to control the duration of your AnimationAction loop. To do so, you can use this pattern:
action.setDuration( 10 ).play();
three.js r.87

ThreeJS: Draw lines at mouse click coordinates

I am working with ThreeJS to create a solar system. I have a sun in the middle and 8 orbits around it. Now I want to get the nearest ring poisiton when the users clicks anywhere on the map!
Here is an image to describe it visually what I mean
The arrows stands for the "click" of the user, then there should be a function to get the nearest orbit and its coordinates (the white dots) where the line between the click point and middle collides.
I tried many different functions I found here, but non of them gave me the result I want.
Thanks for your help!
The code looks currently like this:
var container, stats, parent, pivots, domEvents, twins, planets, sun, fleets, raycaster, mouse;
var camera, controls, scene, renderer;
var cross;
planets = new Array();
init();
animate();
function init()
{
raycaster = new THREE.Raycaster();
mouse = new THREE.Vector2();
//init
camera = new THREE.PerspectiveCamera(10, 1, 1, 4000);
camera.position.z = 200;
camera.position.x = 200;
camera.position.y = 200;
controls = new THREE.OrbitControls(camera);
controls.addEventListener('change', render);
scene = new THREE.Scene();
scene.fog = new THREE.FogExp2(0x000000, 0);
// renderer
renderer = new THREE.WebGLRenderer({antialias: false, alpha: true});
renderer.setSize(document.getElementById('canvasreference').offsetWidth, document.getElementById('canvasreference').offsetWidth);
renderer.setClearColor(0x787878, 0.5); // the default
container = document.getElementById('canvasreference');
container.appendChild(renderer.domElement);
window.addEventListener('resize', onWindowResize, false);
domEvents = new THREEx.DomEvents(camera, renderer.domElement);
//axihelper
scene.add(new THREE.AxisHelper(130));
// parent
parent = new THREE.Object3D();
scene.add(parent);
//arrays
orbits = new Array();
addOrbit();
window.addEventListener('click', onMouseMove, false);
}
function onMouseMove(event) {
canvas = renderer.domElement;
raycaster = new THREE.Raycaster();
mousePosition = new THREE.Vector2();
canvasPosition = $("#canvasreference canvas").position();
console.log(canvasPosition);
mousePosition.x = ((event.clientX - canvasPosition.left) / canvas.width) * 2 - 1;
mousePosition.y = -((event.clientY - canvasPosition.top) / canvas.height) * 2 + 1;
raycaster.setFromCamera(mousePosition, camera);
var geometry = new THREE.Geometry();
var origin = new THREE.Vector3(raycaster.ray.origin.x, 0, raycaster.ray.origin.y);
geometry.vertices.push(origin);
var vektor = new THREE.Vector3(raycaster.ray.direction.x, 0, raycaster.ray.direction.y);
for (var i = 0; i < 1000; i++)
{
origin.add(vektor);
geometry.vertices.push(vektor);
}
var material = new THREE.LineBasicMaterial({
color: 0xffffff, linewidth: 20
});
var line = new THREE.Line(geometry, material);
scene.add(line);
renderer.render(scene, camera);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(600, 600);
render();
}
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
function render() {
renderer.render(scene, camera);
}
/**
* add Orbit line
* #param {type} orbit
* #returns {undefined}
*/
function addOrbit(orbit)
{
for (var i = 0; i < 8; i++)
{
//make orbit line
var orbit = new THREE.EllipseCurve(
0, 0, // ax, aY
i * 10 + 30, i * 10 + 30, // xRadius, yRadius
0, 2 * Math.PI, // aStartAngle, aEndAngle
false, // aClockwise
0 // aRotation
);
var path = new THREE.Path(orbit.getPoints(100));
var geometry = path.createPointsGeometry(100);
var material = new THREE.LineBasicMaterial({color: 0xffffff});
var ellipse = new THREE.Line(geometry, material);
ellipse.rotation.x = 1.5708;
scene.add(ellipse);
}
}
</script>
Cast a ray from your camera to a point where your mouse is. Then check closest distance from that ray to the middle of you solar system using distanceToPoint function. The length of output vector will be the radius of a sphere to which your ray is tangent. Using this length you can determine how close you are to a sphere that is an orbit and if it should be selected. Here's some pseudo code of that check:
var length = getDistanceToCenter(...);
var closestSphere = _(orbits).min(function(orbit) { return Math.abs(length - orbit.radius); });
if (Math.abs(closestSphere.radius - length) < EPSILON) {
selectOrbit(closestSphere);
}

Three.js - My program dies when i place the pointer over the THREE.Line

i have a Three.js program, whenever i place the pointer over a cube, it gives me it's position. That is fine (that is what i need), but when i place the pointer over the line, my program stops. Could anybody tell me why and how to fix it? I need my program to continue running no matter where my pointer is.
When i place the pointer over the white line, i get the following error:
Uncaught TypeError: Cannot read property 'getHex' of undefined.
Code:
var container, stats;
var scene, camera, renderer, raycaster;
var cube;
var clock = new THREE.Clock();
var mouse = new THREE.Vector2(), INTERSECTED;
var radius = 100, theta = 0;
var composer;
initScene();
//Let's add a cube
var geometry = new THREE.BoxGeometry( 20, 20, 20 );
cube = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
color : Math.random() * 0xffffff
}));
cube.position.set(0,20,50)
scene.add( cube );
//Let's add another cube
var geometry2 = new THREE.BoxGeometry( 20, 20, 20 );
var cube2 = new THREE.Mesh(geometry2, new THREE.MeshLambertMaterial({
color : Math.random() * 0xffffff
}));
cube2.position.set(200,20,50)
scene.add( cube2 );
//Let's add a line
var material = new THREE.LineBasicMaterial({
color: 0xffffff
});
var geometry = new THREE.Geometry();
geometry.vertices.push(new THREE.Vector3(0, 20, 50));
geometry.vertices.push(new THREE.Vector3(200, 20, 50));
var line = new THREE.Line(geometry, material);
scene.add(line);
animate();
function initScene() {
container = document.createElement('div');
document.body.appendChild(container);
var fov = 70;
var aspect = window.innerWidth / window.innerHeight;
var near = 1;
var far = 10000;
var zpos = 300;
// Initialize camera
GlobalCamera(fov, aspect, near, far, zpos);
scene = new THREE.Scene();
// Set camera controls
cameraControls2();
// renderer controls
rendererControls2();
}
function GlobalCamera(fov, aspect, near, far, zpos) {
camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = zpos;
}
function cameraControls2() {
controls = new THREE.FlyControls(camera);
controls.movementSpeed = 2500;
controls.domElement = container;
controls.rollSpeed = Math.PI / 6;
controls.autoForward = false;
controls.dragToLook = false
}
function rendererControls2() {
renderer = new THREE.WebGLRenderer({
antialias : true,
alpha : true
});
renderer.setClearColor(0xf0f0f0);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.sortObjects = false;
container.appendChild(renderer.domElement);
renderer.gammaInput = true;
renderer.gammaOutput = true;
}
function findIntersection() {
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(scene.children);
if (intersects.length > 0) {
if (INTERSECTED != intersects[0].object) {
if (INTERSECTED)
INTERSECTED.material.emissive.setHex(INTERSECTED.currentHex);
INTERSECTED = intersects[0].object;
INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex();
INTERSECTED.material.emissive.setHex(0xff0000);
console.log(INTERSECTED.position);
}
} else {
if (INTERSECTED)
INTERSECTED.material.emissive.setHex(INTERSECTED.currentHex);
INTERSECTED = null;
}
}
function onDocumentMouseMove(event) {
event.preventDefault();
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
}
function preAnimate(){
raycaster = new THREE.Raycaster();
// events
document.addEventListener('mousemove', onDocumentMouseMove, false);
}
function animate() {
preAnimate();
requestAnimationFrame(animate);
render();
}
function render() {
var delta = clock.getDelta();
findIntersection();
controls.update(delta);
renderer.render(scene, camera);
}
This is my first adventure with Three.js, but I think I have tracked down your issue. What happens is that the THREE.LineBasicMaterial does not have the emissive property like the THREE.MeshLambertMaterial does. The property you want to manipulate on the THREE.LineBasicMaterial object is the color property.
Here is a working jsFiddle where I have added some checks on wheter the emissive property is available:
https://jsfiddle.net/thedole/4wkFu/162/ The difference is adding the mentioned checks in the findIntersection method:
function findIntersection() {
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(scene.children),
material;
if (intersects.length > 0) {
if (INTERSECTED != intersects[0].object) {
if (INTERSECTED){
material = INTERSECTED.material;
if(material.emissive){
material.emissive.setHex(INTERSECTED.currentHex);
}
else{
material.color.setHex(INTERSECTED.currentHex);
}
}
INTERSECTED = intersects[0].object;
material = INTERSECTED.material;
if(material.emissive){
INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex();
material.emissive.setHex(0xff0000);
}
else{
INTERSECTED.currentHex = material.color.getHex();
material.color.setHex(0xff0000);
}
console.log(INTERSECTED.position);
}
} else {
if (INTERSECTED){
material = INTERSECTED.material;
if(material.emissive){
material.emissive.setHex(INTERSECTED.currentHex);
}
else
{
material.color.setHex(INTERSECTED.currentHex);
}
}
INTERSECTED = null;
}
}

How to change one texture image of a 3d model(maya ) in three.js at runtime

This site is loading a maya model using three.js.
This model has Below texture pictures
Here is the JS
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var container;
var camera, scene;
var canvasRenderer, webglRenderer;
var mesh, zmesh, geometry, materials;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var meshes = [];
function init() {
container = document.createElement('div');
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(75, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 100000);
camera.position.x = 400;
camera.position.y = 200;
camera.position.z = 400;
scene = new THREE.Scene();
// LIGHTS
var ambient = new THREE.AmbientLight(0x666666);
scene.add(ambient);
var directionalLight = new THREE.DirectionalLight(0xffeedd);
directionalLight.position.set(0, 70, 100).normalize();
scene.add(directionalLight);
// RENDERER
webglRenderer = new THREE.WebGLRenderer();
webglRenderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
webglRenderer.domElement.style.position = "relative";
container.appendChild(webglRenderer.domElement);
var loader = new THREE.JSONLoader(),
callbackKey = function (geometry, materials) {
createScene(geometry, materials, 0, 0, 0, 6)
};
loader.load("chameleon.js", callbackKey);
window.addEventListener('resize', onWindowResize, false);
}
function createScene(geometry, materials, x, y, z, scale) {
zmesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
zmesh.position.set(x, y, z);
zmesh.scale.set(scale, scale, scale);
meshes.push(zmesh);
scene.add(zmesh);
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
webglRenderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
for (var i = 0; i < meshes.length; i++) {
meshes[i].rotation.y += .01;
}
requestAnimationFrame(animate);
render();
}
function render() {
camera.lookAt(scene.position);
webglRenderer.render(scene, camera);
}
$(document).ready(function () {
init();
animate();
});
now i want to change the 1st texture picture to some other texture and rest of the texture remains same on runtime! how to do it?
if you'd like to change the texture at runtime. All you need to do is look at the zmesh objects material. Find the appropriate index of the blue dress material and swap it out. Your model is a little tricky in that you have an array of materials but no matter. For a single material object you simply change the mesh.material.map and update it, in your case we need mesh.material.materials[index].map. So try adding this to the bottom of your createScene function. It will replace the dress with the eyeball texture:
zmesh.material.materials[1].map = THREE.ImageUtils.loadTexture( 'c006_10.jpg' );
Of course, replace 'c006_10.jpg' with the appropriate path to your eyeball texture. One added Note, if you hook up the texture swap to an onclick for example you'll want to have an active render loop or call renderer's render function to get it to display.

Categories

Resources