Three.js Cannot find Obj - three.js

I am using the file from three.js and used the OBJloader and render with canvas. Except that I cannot find the object even when I scale the object by 1000 and set the camera to 2. The code is as below.
<script src="../mrdoob/build/three.min.js"></script>
<script src="../mrdoob/examples/js/loaders/OBJLoader.js"></script>
<script src="../mrdoob/examples/js/renderers/CanvasRenderer.js"></script>
<script src="../mrdoob/examples/js/renderers/Projector.js"></script>
<script>
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 = 100;
camera.position.z = 2;
// 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);
// 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) {
alert(xhr);
};
alert("hi");
var loader = new THREE.ImageLoader(manager);
loader.load('../mrdoob/examples/textures/UV_Grid_Sm.jpg', function (image) {
texture.image = image;
texture.needsUpdate = true;
});
// model
alert("hi2");
var loader = new THREE.OBJLoader();
loader.load('../mrdoob/examples/obj/male02/male02.obj', function (object) {
object.scale = new THREE.Vector3(1000, 1000, 1000);
alert(object.position.y);
scene.add(object);
});
//
alert("hi3");
renderer = new THREE.CanvasRenderer();
renderer.setClearColor(0xf0f0f0);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
document.addEventListener('mousemove', onDocumentMouseMove, false);
//
window.addEventListener('resize', onWindowResize, false);
alert("hi4");
}
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);
}
</script>
I did an alert on the object and the position turns out to be zero, so I am not sure if the object is correctly loaded. If someone can tell me how to look for the object would be good.

It may cause if the camera located inside your object, then it always see the back faces of your object and ignore it.
Please provide jsfiddle live example.

Related

Three.js DeviceOrientationControl makes scene disappear

I have a glb model which loads successfully and reacts to mouse movements. However when I add DeviceOrientationControl.js which is intended for mobile devices, the scene disappears. No errors visible in the console. Funny enough, when I change
controls = new DeviceOrientationControls( camera, renderer.domElement );
to
controls = new DeviceOrientationControls( group, renderer.domElement );
it works, but has strangely displaces the model around the axis, which I am not able to readjust manually. Can someone help me find a solution? Why doesn't it work with camera but with group (model directly)?
Also when I add
camera.lookAt(scene.position);
and disable DeviceOrientationControls, the model works however the desired controls are not, which is my main issue.
Here is my code:
import * as THREE from '../node_modules/three/build/three.module.js';
import {OrbitControls} from '../node_modules/three/examples/jsm/controls/OrbitControls.js';
import {DeviceOrientationControls} from '../node_modules/three/examples/jsm/controls/DeviceOrientationControls.js';
import {GLTFLoader} from '../node_modules/three/examples/jsm/loaders/GLTFLoader.js';
import { DRACOLoader } from '../node_modules/three/examples/jsm/loaders/DRACOLoader.js';
import Stats from '../node_modules/three/examples/jsm/libs/stats.module.js';
var camera, scene, renderer, group, stats, controls, windowHalfX = window.innerWidth / 2,
windowHalfY = window.innerHeight / 2,
mouseX = 0,
mouseY = 0;
var renderer = new THREE.WebGLRenderer();
renderer.shadowMap.enabled = true;
renderer.shadowMapSoft = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
var width = window.innerWidth;
var height = window.innerHeight;
window.onload = function () {
init();
animate();
$(".loadmain").fadeOut(500);
}
var startButton = document.getElementById( 'startButton' );
startButton.addEventListener( 'click', function () {
$("#overlay").fadeOut(700, function(){
$(this).remove();
});
document.body.className += "loaded";
document.querySelector("canvas").className += " load";
}, false );
const gltfLoader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath('https://raw.githubusercontent.com/mrdoob/three.js/dev/examples/js/libs/draco/');
dracoLoader.setDecoderConfig({ type: 'js' });
gltfLoader.setDRACOLoader(dracoLoader);
function init() {
camera = new THREE.PerspectiveCamera(45, width / height, 1, 10000);
controls = new DeviceOrientationControls( camera, renderer.domElement );
camera.position.set(0, 0, 7);
camera.zoom = 1;
camera.updateProjectionMatrix();
scene = new THREE.Scene();
scene.updateMatrixWorld();
var directionalLight = new THREE.DirectionalLight(0xffffff, 3);
directionalLight.color.setHSL(0.1, 1, 0.95);
directionalLight.position.set(0, 1, 1);
directionalLight.position.multiplyScalar(10);
scene.add(directionalLight);
directionalLight.shadow.mapSize.width = 2048;
directionalLight.shadow.mapSize.height = 2048;
var spotLight1 = new THREE.DirectionalLight( 0xff4000 );
spotLight1.position.set( -15, 3, -4 );
spotLight1.target.position.set( 0, 1, 0 );
spotLight1.castShadow = true;
scene.add( spotLight1 );
var spotLight2 = new THREE.DirectionalLight( 0xff0aea );
spotLight2.position.set( 15, 3, -4 );
spotLight2.target.position.set( 0, 1, 0 );
spotLight2.intensity = 1.2;
spotLight2.castShadow = true;
scene.add( spotLight2 );
group = new THREE.Group();
group.position.x = 0;
scene.add( group );
scene.add( camera );
gltfLoader.load('../public/res/3D/model.glb', (gltf) => {
const root = gltf.scene;
root.rotateY(-89.55);
root.position.x = 0;
root.position.y = -0.7;
root.castShadow = true;
group.add(root);
});
renderer = new THREE.WebGLRenderer({ antialias: true, canvas: document.querySelector('canvas'), alpha: true, });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild( renderer.domElement );
window.addEventListener( 'resize', onWindowResize, false );
window.addEventListener('mousemove', onDocumentMouseMove, false);
}
function onDocumentMouseMove(event) {
event.preventDefault();
mouseX = (event.clientX / window.innerWidth) * 2 - 1;
mouseY = - (event.clientY / window.innerHeight) * 2 + 1;
}
function animate() {
window.requestAnimationFrame( animate );
if (group) {
group.rotation.y = mouseX * .5;
group.rotation.x = mouseY * -.5;
}
controls.update();
render();
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function render() {
//camera.lookAt(scene.position);
renderer.render( scene, camera );
}

Three.js destroy on new page load

I'm helping a friend to set up a Three.js scene on a page in Wordpress that's running on the Lay theme. The theme is using some kind of page transition script that doesn't reload the site when navigating to a different page, creating a new initialization of the Three.js scene each time a new page is injected on the site.
I'm looking for ways to completely remove the whole instance of Three.js when a new page is loaded. So that it gets created from scratch when The Lay theme has this function window.laytheme.on("newpageshown", function(layoutObj, type, obj){} that kind of works as a substitute for window.onload.
I've tried different methods in order to remove everything, but as my Three.js code unfortunately is a mixed result of copy and pasting from different demos and examples, I'm not quite sure what exactly that needs to be destroyed and how to do it. To be honest I'm not entirely sure how the code is setup and I have very little experience with Three.js and it's lifecycle.
Here's the code creating the scene:
(function($) {
var base_url = window.location.origin;
var container, stats;
var camera, scene, renderer, controls, manager, loader, texture;
var mouseX = 0,
mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var $currentModel;
var modelName;
var initialGridPosition;
var initialScale;
window.laytheme.on("newpageshown", function(layoutObj, type, obj){
modelName = $(".modelLink.is-active").data("model-name");
initialScale = $(".modelLink.is-active").data("model-scale");
initialGridPosition = $(".modelLink.is-active").data("model-grid-position");
init();
animate();
});
function init() {
container = document.createElement('div');
container.id = "threejs-container";
document.body.appendChild(container);
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000);
camera.position.z = 300;
camera.position.y = 100;
// scene
scene = new THREE.Scene();
var ambientLight = new THREE.AmbientLight(0xffffff, 0.7);
scene.add(ambientLight);
var pointLight = new THREE.PointLight( 0xffffff, 0.3 );
camera.add( pointLight );
scene.add(camera);
// model
var onProgress = function(xhr) {
if (xhr.lengthComputable) {
var percentComplete = xhr.loaded / xhr.total * 100;
$("#domLoader").show();
$("#domLoader").text(Math.round(percentComplete, 2) + '%');
}
};
// texture
manager = new THREE.LoadingManager();
manager.onProgress = function(item, loaded, total) {
if (total == loaded) {
$("#domLoader").hide();
$(".col--row").removeClass("is-hidden");
$currentModel = $(".modelLink.is-active");
$("#meta-title").text('stevns_klint_' + $currentModel.data("model-name"));
$("#meta-vertices").text($currentModel.data("model-vertices"));
$("#meta-faces").text($currentModel.data("model-faces"));
$("#meta-coordinates").text($currentModel.data("model-coordinates"));
$("#meta-coordinates-url").attr("href", $currentModel.data("model-coordinates-url"));
$("#meta-date").text($currentModel.data("model-date"));
$("#meta-images").text($currentModel.data("model-images"));
}
console.log(item, loaded, total);
};
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');
$("#domLoader").show();
$("#domLoader").text(Math.round(percentComplete, 2) + '%');
}
};
var onError = function() {};
// Create initial model
loader = new THREE.ImageLoader(manager)
loader.setPath(base_url + '/assets/' + modelName +'/').load('texture.jpg', function(image) {
texture.image = image;
texture.needsUpdate = true;
});
loader = new THREE.OBJLoader(manager);
loader.setPath(base_url + '/assets/' + modelName +'/').load('model.obj', function(object) {
object.traverse(function(child) {
if (child instanceof THREE.Mesh) {
child.material.map = texture;
}
if( child.material ) {
child.material.side = THREE.DoubleSide;
}
});
object.scale.x = initialScale;
object.scale.y = initialScale;
object.scale.z = initialScale;
object.name = "mainModel";
scene.add(object);
}, onProgress, onError);
renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0xffffff, 1);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
var size = 300;
var divisions = 30;
var gridHelper = new THREE.GridHelper( size, divisions, 0x000000, 0x000000 );
scene.add( gridHelper );
gridHelper.position.y = initialGridPosition;
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.screenSpacePanning = true;
controls.minDistance = 150;
controls.maxDistance = 300;
controls.target.set(0, 0, 0);
controls.enableDamping = true;
controls.enablePan = false;
controls.autoRotate = true;
controls.enableKeys = false;
controls.autoRotateSpeed = 0.04;
controls.dampingFactor = 0.07;
controls.rotateSpeed = 0.04;
controls.update();
window.addEventListener('resize', onWindowResize, false);
// Change model on model link click
$(".modelLink").on("click", function(){
$(".modelLink").removeClass("is-active");
$(this).addClass("is-active");
$(".col--row").addClass("is-hidden");
var modelName = $(this).data("model-name");
var modelScale = Number($(this).data("model-scale"));
var modelGridPosition = $(this).data("model-grid-position");
loader = new THREE.ImageLoader(manager)
loader.setPath(base_url + '/assets/' + modelName +'/').load('texture.jpg', function(image) {
texture.image = image;
texture.needsUpdate = true;
});
loader = new THREE.OBJLoader(manager);
loader.setPath(base_url + '/assets/' + modelName + '/').load('model.obj', function(object) {
object.traverse(function(child) {
if (child instanceof THREE.Mesh) {
child.material.map = texture;
}
if( child.material ) {
child.material.side = THREE.DoubleSide;
}
});
object.scale.x = modelScale;
object.scale.y = modelScale;
object.scale.z = modelScale;
var selectedObject = scene.getObjectByName("mainModel");
scene.remove( selectedObject );
object.name = "mainModel";
gridHelper.position.y = modelGridPosition;
scene.add(object);
}, onProgress, onError);
})
}
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 animate() {
requestAnimationFrame(animate);
controls.update();
render();
}
function render() {
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
})( jQuery );
There code might be some code in there that's irrelevant and have nothing to do with Three.js. But I would appreciate if someone with more experience in the Three.js structure and lifecycle could help me with reading through the script and tell me what parts of the code related to Three.js that needs to be destroyed and how this would be done.

Three JS: CTM file not loading

Here I tried to load a .ctm file in three JS using CTM Loader. But the CTM file is not getting loaded and the object is not visible in the screen, whereas when I load the js file with geometry properties it gets loaded and the object is visible on the screen. So, when I tried to load a ctm file the object is not visible and when I load a js file with geometry properties the object gets loaded.
I have attached the code below
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var FLOOR = -250;
var container;
var camera, scene, controls;
var renderer;
var mesh;
var textureCube;
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(30, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000);
camera.position.set(185, 40, 170);
controls = new THREE.OrbitControls(camera);
controls.maxPolarAngle = Math.PI / 2;
controls.minDistance = 150;
controls.maxDistance = 500;
scene = new THREE.Scene();
scene.background = textureCube;
var light = new THREE.PointLight(0xffffff, 1);
light.position.set(2, 5, 1);
light.position.multiplyScalar(30);
scene.add(light);
var light = new THREE.PointLight(0xffffff, 0.75);
light.position.set(-12, 4.6, 2.4);
light.position.multiplyScalar(30);
scene.add(light);
scene.add(new THREE.AmbientLight(0x050505));
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
renderer.domElement.style.position = "relative";
container.appendChild(renderer.domElement);
renderer.gammaInput = true;
renderer.gammaOutput = true;
window.addEventListener('resize', onWindowResize, false);
window.addEventListener('mousemove', onDocumentMouseMove, false);
var start = Date.now();
var position = new THREE.Vector3(-105, -78, -30);
var scale = new THREE.Vector3(30, 30, 30);
var loader = new THREE.CTMLoader(true);
// loader.loadParts("models/ctm/camaro/camaro.js", function (geometries, materials) {
loader.load("models/ctm/camaro/camaro.ctm", function (geometries, materials) {
for (var i = 0; i < geometries.length; i++) {
var mesh = new THREE.Mesh(geometries[i], materials[i]);
mesh.name = "camaro car"
mesh.position.copy(position);
mesh.scale.copy(scale);
scene.add(mesh);
}
var end = Date.now();
console.log("load time:", end - start, "ms");
}, { useWorker: true });
}
function onWindowResize(event) {
SCREEN_WIDTH = window.innerWidth;
SCREEN_HEIGHT = window.innerHeight;
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
camera.aspect = SCREEN_WIDTH / SCREEN_HEIGHT;
camera.updateProjectionMatrix();
}
function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX);
mouseY = (event.clientY - windowHalfY);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
renderer.render(scene, camera);
}

Can't rotate each mesh on animation update

I am quite new to Three.js and have been experimenting to get familiar with it.
I am making this exercise where I add to the scene 35 icosahedrons. I would like for each one of them to rotate when calling requestAnimationFrame.
I thought that by looping into each group children element (which is each mesh) and adding value to x and y rotation I could make the meshes rotate. Why is not so? Any help is very appreciated. Thank you.
This my approach:
var camera, scene, renderer;
var geometry, material, mesh;
var edgesGeometry, edgesMaterial, edges;
var group;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
init()
animate()
function init() {
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 1500;
scene = new THREE.Scene();
group = new THREE.Group();
for ( var i = 0; i < 35; i ++ ) {
var randomSize = Math.floor( Math.random() * (150 - 20) + 20 )
geometry = new THREE.IcosahedronGeometry( randomSize, 1 );
material = new THREE.MeshBasicMaterial({ color: 0x000000 });
mesh = new THREE.Mesh( geometry, material );
mesh.position.x = Math.random() * 2000 - 1000;
mesh.position.y = Math.random() * 2000 - 1000;
mesh.position.z = Math.random() * 2000 - 1000;
mesh.rotation.x = Math.random() * 2 * Math.PI;
mesh.rotation.y = Math.random() * 2 * Math.PI;
edgesGeometry = new THREE.EdgesGeometry( mesh.geometry )
edgesMaterial = new THREE.LineBasicMaterial( { color: 0x63E260, linewidth: 2 } )
edges = new THREE.LineSegments( edgesGeometry, edgesMaterial )
mesh.add( edges )
mesh.matrixAutoUpdate = false;
mesh.updateMatrix();
group.add( mesh );
}
scene.add( group );
//
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.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 ) * 0.25;
mouseY = ( event.clientY - windowHalfY ) * 0.25;
}
function animate() {
requestAnimationFrame( animate );
for ( var i = 0; i < group.children.length; i ++ ) {
group.children[i].rotation.x += 0.001;
group.children[i].rotation.y += 0.001;
}
render();
}
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 );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/93/three.js"></script>
To expand on #prisoner849's comment:
When three.js renders a scene, it parses the entire scene looking for renderable items (visible, within the view frustum, etc.). Part of that process involves multiplying out the transformation matrices to populate the world matrix (matrixWorld) of each renderable item is up-to-date. As you can imagine, this can potentially be a process hog, so you also have the ability to turn off that auto-update.
It looks like you understand that, because your line of code: mesh.matrixAutoUpdate = false; does exactly that, then you follow it up by manually updating the mesh's matrix. This is mostly correct, but you also need to do this for each frame.
For a simple/shallow scene like yours, #prisoner849's approach is correct--just let three.js auto-update the matrices by removing the lines mentioned. But if your scene is more complex, and you want finer control over it, you'll need to exert that control for each frame you want to render.
In the example below, I took your original code and made it so that only every second icosahedron rotates. This is accomplished by collecting them into an array, and then only updating the matrices for objects in that array. (Also note I turned off matrix auto-updating for the entire scene, rather than individual objects.)
var camera, scene, renderer;
var geometry, material, mesh;
var edgesGeometry, edgesMaterial, edges;
var group;
var mouseX = 0,
mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var updatableObjects = [];
init()
animate()
function init() {
camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.z = 1500;
scene = new THREE.Scene();
scene.autoUpdateMatrix = false; // turn off automatic matrix computation
group = new THREE.Group();
for (var i = 0; i < 35; i++) {
var randomSize = Math.floor(Math.random() * (150 - 20) + 20)
geometry = new THREE.IcosahedronGeometry(randomSize, 1);
material = new THREE.MeshBasicMaterial({
color: 0x000000
});
mesh = new THREE.Mesh(geometry, material);
mesh.position.x = Math.random() * 2000 - 1000;
mesh.position.y = Math.random() * 2000 - 1000;
mesh.position.z = Math.random() * 2000 - 1000;
mesh.rotation.x = Math.random() * 2 * Math.PI;
mesh.rotation.y = Math.random() * 2 * Math.PI;
edgesGeometry = new THREE.EdgesGeometry(mesh.geometry)
edgesMaterial = new THREE.LineBasicMaterial({
color: 0x63E260,
linewidth: 2
})
edges = new THREE.LineSegments(edgesGeometry, edgesMaterial)
mesh.add(edges)
if (i % 2) {
updatableObjects.push(mesh);
}
group.add(mesh);
}
scene.add(group);
//
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.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) * 0.25;
mouseY = (event.clientY - windowHalfY) * 0.25;
}
function updateMeshes(mesh) {
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.01;
mesh.updateMatrix();
}
function animate() {
requestAnimationFrame(animate);
updatableObjects.forEach(updateMeshes);
render();
}
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);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/93/three.js"></script>

firstpersoncontrols delta is not defined

I test for use the firstpersoncontrols in three.js. but in copying examples to anderstand how it's work, i have always the same error in console : delta is not defined. if you are an explication :
<!-- upload librarie -->
<script src="../THREEJS03/build/three.min.js"></script>
<!-- upload les modes d'interactions -->
<script src="js/controls/FirstPersonControls.js"></script>
<script src="js/loaders/MTLLoader.js"></script>
<script src="js/loaders/OBJMTLLoader.js"></script>
<!-- upload la detection du webgl -->
<script src="js/Detector.js"></script>
<script>
//detection du webgl
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container;
var camera, cubeCamera, controls, scene, renderer;
var clock = new THREE.Clock();
init();
animate();
//////////////////////// SCENE /////////////////////////////////////
function init() {
// scene
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 3000 );
camera.position.x = 00;
camera.position.y = 80;
camera.position.z = 00;
controls = new THREE.FirstPersonControls( camera );
controls.movementSpeed = 1000;
controls.lookSpeed = 0.125;
controls.lookVertical = true;
controls.constrainVertical = false;
controls.verticalMin = 1.1;
controls.verticalMax = 2.2;
controls.noFly = true;
scene = new THREE.Scene();
scene.add( camera );
// light
// add ambient lighting
var ambientLight = new THREE.AmbientLight(0x020202);
scene.add(ambientLight);
var pointLight = new THREE.PointLight(0xffffff); //0xffaa00
pointLight.position.x = -300;
pointLight.position.y = 300;
pointLight.position.z = 500;
scene.add(pointLight);
//SKYBOX (only reflexive)
// Cubic Texture
var r = "models/world/";
var urls = [r + "posx.jpg", r + "negx.jpg",
r + "posy.jpg", r + "negy.jpg",
r + "posz.jpg", r + "negz.jpg"];
var textureCube = THREE.ImageUtils.loadTextureCube(urls);
////////////////////////// OBJET ////////////////////////////
var loader = new THREE.OBJMTLLoader();
loader.addEventListener( 'load', function ( event ) {
var object = event.content;
object.position.y = 0;
scale = 1;
scene.add( object );
});
loader.load( 'models/macabann/obj/scene/scene01.obj', 'models/macabann/obj/scene/scene01.mtl' );
var material = new THREE.MeshPhongMaterial( {
//Environnement
envMap: textureCube,
combine: THREE.MixOperation,
//Color Application
side: THREE.DoubleSide,
shading: THREE.SmoothShading
});
///////////////////// FIN OBJET ///////////////////////
/////////////////// RENDERER //////////////////////
//type de rendu (antialias true or false)
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setClearColorHex( 0xf3f3f3, 1 );
renderer.shadowMapEnabled = true;
//dimension du rendu
renderer.setSize( window.innerWidth, window.innerHeight );
// create wrapper object that contains three.js objects
container = document.createElement( 'div' );
document.body.appendChild( container );
container.appendChild( renderer.domElement );
///////////////////// FIN RENDERER ///////////////////////
//////////////////// WINDOWS ////////////////////////
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
controls.handleResize();
}
//////////////////////////FIN WINDOWS //////////////////////
function render() {
var delta = clock.getDelta();
time = clock.getElapsedTime() * 10;
}
function animate() {
requestAnimationFrame( animate );
controls.update(delta);
renderer.render( scene, camera );
}
</script>
thank to explications and answers
You have some problems in this part:
function render() {
var delta = clock.getDelta();
time = clock.getElapsedTime() * 10;
}
function animate() {
requestAnimationFrame( animate );
controls.update(delta);
renderer.render( scene, camera );
}
You define delta variable in render() function, which is outside of the skope of animate. Try moving those lines to the animate() function, like this:
function render() {
// is this function needed at all?
}
function animate() {
var delta = clock.getDelta();
time = clock.getElapsedTime() * 10;
requestAnimationFrame(animate);
controls.update(delta);
renderer.render( scene, camera );
}

Resources