glb/gltf Model not loading on Netlify, but loads locally - three.js

I am using Three.js with the gltf loader to load a single .glb resource onto a page. It works locally, though then I upload to Netlify the model does not load and the xhr progressEvent's total is 0. I checked that the model is still being loaded in the network tab, but yet it still does not show in the page.
It seems this problem has occurred before, but not sure how to resolve it when using Netlify if there are any environment variables I need to change.
https://github.com/mrdoob/three.js/issues/15584
HTML
<div class="model-wrapper">
<div id="model_target" class="loading">
<div class="myimage fade" id="placeholder">
<img src="images/placeholder.png" height="328px"/></div>
</div>
</div>
<!-- THREE.js -->
<script src="https://threejs.org/build/three.js"></script>
<!-- GLTFLoader.js -->
<script src="https://cdn.rawgit.com/mrdoob/three.js/r92/examples/js/loaders/GLTFLoader.js"></script>
JS
```
let camera, scene, renderer;
const mouse = new THREE.Vector2();
const look = new THREE.Vector2();
const windowHalf = new THREE.Vector2( window.innerWidth /
2, window.innerHeight / 2 );
var plane = new THREE.Plane(new THREE.Vector3(0, 0, 0.4),
-9);
var raycaster = new THREE.Raycaster();
var pointOfIntersection = new THREE.Vector3();
let modelLoaded = false;
let placement = document.getElementById("model_target")
window.addEventListener('DOMContentLoaded', init);
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 60, 1, 1, 1000);
camera.position.set(5, 3, 28)
//camera.position.y = 13;
var light = new THREE.DirectionalLight("#fff", 1.5);
var ambient = new THREE.AmbientLight("#FFF");
light.position.set( 0, -70, 100 ).normalize();
scene.add(light);
// scene.add(ambient);
var texture = new THREE.Texture();
var loader = new THREE.GLTFLoader();
THREE.Cache.enabled = true;
// Load a glTF resource
loader.load(
// 3d model resource
'./assets/models/mrktechy3.glb',
// called when the resource is loaded
function ( gltf ) {
mesh = gltf.scene;
mesh.scale.set( 5, 5, 5 );
scene.add( mesh );
},
// called when loading is in progress
function ( xhr ) {
// Loading progress of model
console.log(xhr);
console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
if((xhr.loaded / xhr.total * 100) == 100){
modelLoaded = true;
//Loading overlay
var placeholder = document.getElementById("placeholder");
placeholder.classList.add("faded");
placement.classList.remove("loading");
}
},
// called when loading has errors
function ( error ) {
console.log( 'An error happened' );
}
);
//scene.background = new THREE.Color(0xfff); //Set background color
renderer = new THREE.WebGLRenderer( { alpha: true, antialias: true } );
renderer.setSize( 800, 500 );
placement.appendChild( renderer.domElement );
renderer.setClearColor(0x000000, 0);
renderer.gammaOutput = true;
document.addEventListener( 'mousemove', onMouseMove, false );
window.addEventListener( 'resize', onResize, false );
render()
}
function onMouseMove( event ) {
if (modelLoaded){
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 0;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 0;
raycaster.setFromCamera(mouse, camera);
raycaster.ray.intersectPlane(plane, pointOfIntersection);
mesh.lookAt(pointOfIntersection);
}
}
function onResize( event ) {
const width = 800 ;
const height = 500;
windowHalf.set( width / 2, height / 2 );
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize( width, height );
}
var easeAmount = 8;
function update(){
look.x += (mouse.x-look.x)/easeAmount;
look.y += (mouse.y-look.y)/easeAmount;
raycaster.setFromCamera(look, camera);
raycaster.ray.intersectPlane(plane, pointOfIntersection);
mesh.lookAt(pointOfIntersection);
}
function render() {
camera.aspect = renderer.domElement.clientWidth / renderer.domElement.clientHeight;
camera.updateProjectionMatrix();
requestAnimationFrame( render );
if (modelLoaded){
update();
}
renderer.render( scene, camera );
}
```
Any glb resource can be replaced in the code and it works locally but not when hosted.

In the IIS settings, try to add mime type for gltf. Something like this:
application/gltf-buffer .gltf
This solved my problem.

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 );
}

Adding DeviceOrientationControls to a GLTF GLB object

I am using Three.JS and have gotten a .glb file to display beautifully with some mouse movement.
I'm now trying to add DeviceOrientationControls to my GLtf/GLB scene, so I can move around the scene when moving the mobile phone around, however I can't quite work it out.
No matter what I try I always get one error or another.
I have tried adapting the code from this example: https://threejs.org/examples/misc_controls_deviceorientation.html
This is my current code without any DeviceOrientationControls code added:
HTML
<!-- three.min.js r87 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/92/three.min.js"></script>
<!-- GLTFLoader.js -->
<script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js#r92/examples/js/loaders/GLTFLoader.js"></script>
<!-- Orientation Controls -->
<script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/controls/DeviceOrientationControls.js"></script>
<div id="overlay">
<div>
<button id="startButton">Start Demo</button>
<p>Using device orientation might require a user interaction.</p>
</div>
</div>
<div class="single-object">
<div id="container"></div>
JS
window.addEventListener("load", loadGltf, false);
window.addEventListener("resize", onWindowResize, false);
const progressBar = document.querySelector("progress");
const gltfStore = {};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x111111);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
// Attach to container
container = document.getElementById( 'container' );
//Setup camera
const camera = new THREE.PerspectiveCamera(
75, window.innerWidth / window.innerHeight,0.1, 1000 );
camera.position.set(0, 0, 0);
camera.lookAt(0, 0, 5);
windowHalfX = window.innerWidth / 2,
windowHalfY = window.innerHeight / 2,
mouseX = 0,
mouseY = 0;
//Re-establish camera view on window resize
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
//Lighting
const lightFill = new THREE.PointLight(0xffffff, 1, 500);
lightFill.position.set(0, 0, 5);
scene.add(lightFill);
const lightKey = new THREE.PointLight(0xffffff, 1, 500);
lightKey.position.set(20, 0, 20);
scene.add(lightKey);
const loader = new THREE.GLTFLoader();
// Device Orientation
// Load the GLB file
function loadGltf() {
loader.load(
"<?php echo get_template_directory_uri();?>/objects/SM_LookDev_TextureTest_FromFBX.glb",
function(gltf) {
scene.add(gltf.scene);
mesh = gltf.scene;
gltf.scene.children[0];
gltfStore.scene = gltf.scene;
// Set listener
document.addEventListener("mousemove", onMouseMove);
}
);
container.appendChild(renderer.domElement);
// Mouse movement
function onMouseMove(event) {
mouseX = (event.clientX - windowHalfX) / 10;
mouseY = (event.clientY - windowHalfY) / 30;
}
function animate() {
requestAnimationFrame(animate);
// Adjust mouse and scene position
camera.position.x += (mouseX - camera.position.x) * .0005;
camera.position.y += (-mouseY - camera.position.y) * .0003;
camera.lookAt(0,0,10);
renderer.render(scene, camera);
}
animate();
}
I have gathered from the examples that I need to add these lines (I think):
controls = new DeviceOrientationControls( camera );
controls.update();
and the below for the start button...
var startButton = document.getElementById( 'startButton' );
startButton.addEventListener( 'click', function () {
init();
animate();
}, false );
EDIT
Below is an example of where I have tried to add the lines, but have not worked successfully.
window.addEventListener("load", loadGltf, false);
window.addEventListener("resize", onWindowResize, false);
const progressBar = document.querySelector("progress");
// Add Start Button
var startButton = document.getElementById( 'startButton' );
startButton.addEventListener( 'click', function () {
init();
animate();
}, false );
const gltfStore = {};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x111111);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
// Attach to container
container = document.getElementById( 'container' );
//Setup camera
const camera = new THREE.PerspectiveCamera(
75, window.innerWidth / window.innerHeight,0.1, 1000 );
camera.position.set(0, 0, 0);
camera.lookAt(0, 0, 5);
windowHalfX = window.innerWidth / 2,
windowHalfY = window.innerHeight / 2,
mouseX = 0,
mouseY = 0;
//Re-establish camera view on window resize
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
//Lighting
const lightFill = new THREE.PointLight(0xffffff, 1, 500);
lightFill.position.set(0, 0, 5);
scene.add(lightFill);
const lightKey = new THREE.PointLight(0xffffff, 1, 500);
lightKey.position.set(20, 0, 20);
scene.add(lightKey);
const loader = new THREE.GLTFLoader();
// Added Device Orientation Controls
controls = new DeviceOrientationControls( camera );
// Load the GLB file
function loadGltf() {
loader.load(
"<?php echo get_template_directory_uri();?>/objects/SM_LookDev_TextureTest_FromFBX.glb",
function(gltf) {
scene.add(gltf.scene);
mesh = gltf.scene;
gltf.scene.children[0];
gltfStore.scene = gltf.scene;
// Set listener
document.addEventListener("mousemove", onMouseMove);
}
);
container.appendChild(renderer.domElement);
// Mouse movement
function onMouseMove(event) {
mouseX = (event.clientX - windowHalfX) / 10;
mouseY = (event.clientY - windowHalfY) / 30;
}
function animate() {
requestAnimationFrame(animate);
// Adjust mouse and scene position
camera.position.x += (mouseX - camera.position.x) * .0005;
camera.position.y += (-mouseY - camera.position.y) * .0003;
camera.lookAt(0,0,10);
// Add Controls Update
controls.update();
renderer.render(scene, camera);
}
animate();
}
When adding the lines like this, I get these 2 error messages:
Uncaught TypeError: Cannot read property 'addEventListener' of null
and
Uncaught ReferenceError: Cannot access 'loader' before initialization at loadGltf
So, I am unsure how to actually add these lines into my specific code to get it to work?
Any assistance would be appreciated
It's hard to tell exactly the reason why it's not working, especially since your question includes so much extraneous code. You should try to ask your questions with a minimal reproducible example.
First, you're importing your <scripts> from varying sources, and varying versions. The Three.js and GLTFLoader you're loading is r92, but the DeviceOrientationControls script doesn't specify a version, so it's loading the latest at r112, which might no longer be compatible with ThreeJS r92.
Secondly, you're using:
controls = new DeviceOrientationControls( camera );, when it should be:
controls = new THREE.DeviceOrientationControls( camera );
Finally, make sure you organize your code, and call your functions in a sequential manner. Is loadGltf() being called before you initiate const loader = new THREE.GLTFLoader()? Does startButton exist, and is it defined before you call startButton.addEventListener();?
Here is a minimal example implementing the orientation controls: Notice that both scripts are being imported from the same source with r92 to ensure compatibility.
window.addEventListener("resize", resize);
const renderer = new THREE.WebGLRenderer({canvas: document.querySelector("canvas")});
const camera = new THREE.PerspectiveCamera(60, 1, 1, 1000);
const controls = new THREE.DeviceOrientationControls( camera );
// Make a scene with geometry
const scene = new THREE.Scene();
const geometry = new THREE.DodecahedronBufferGeometry(100,1);
const material = new THREE.MeshBasicMaterial({
color: 0xff9900,
wireframe: true,
});
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
function resize() {
var width = window.innerWidth;
var height = window.innerHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
function animate(time) {
controls.update();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
resize();
animate(0);
body { margin: 0; }
<canvas></canvas>
<!-- three.min.js r92 -->
<script src="https://cdn.jsdelivr.net/npm/three#0.92/build/three.min.js"></script>
<!-- Orientation Controls r92 -->
<script src="https://cdn.jsdelivr.net/gh/mrdoob/three.js#r92/examples/js/controls/DeviceOrientationControls.js"></script>
Note:
Apple disabled gyroscope access by default since iOS 12.2, so you'll have to enable it in settings when testing. See here for a discussion on the matter.

Video transition in Three.js

I want to play multiple videos in Three.js environment. I have finished loading video as texture and play it below and stuck at how to implement to load multiple video textures and play. Also adding some transition into it :(. Hope anyone can help me , give me some suggestions or right direction to do it. I'm fresh to webGL and Three.js.
// MAIN
// standard global variables
var container, scene, camera, renderer, controls, stats;
// custom global variables
var video, videoImage, videoImageContext, videoTexture;
var mouseX = 0;
var mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight;
init();
animate();
// FUNCTIONS
function init() {
// SCENE
scene = new THREE.Scene();
// CAMERA
var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
scene.add(camera);
camera.position.set(0,200,500);
camera.lookAt(scene.position);
// RENDERER
if ( Detector.webgl )
renderer = new THREE.WebGLRenderer( {antialias:true} );
else
renderer = new THREE.CanvasRenderer();
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
renderer.setClearColor (0xFFFFFF, 1);
container = document.getElementById( 'ThreeJS' );
container.appendChild( renderer.domElement );
// CONTROLS
// controls = new THREE.OrbitControls( camera, renderer.domElement );
// EVENTS
THREEx.WindowResize(renderer, camera);
// LIGHT
// var light = new THREE.PointLight(0xffffff);
// light.position.set(0,250,0);
// scene.add(light);
// FLOOR
var floorTexture = new THREE.ImageUtils.loadTexture( 'logo.jpg' );
var floorMaterial = new THREE.MeshBasicMaterial( { map: floorTexture, side: THREE.DoubleSide } );
var floorGeometry = new THREE.PlaneGeometry(500, 500, 0, 0);
var floor = new THREE.Mesh(floorGeometry, floorMaterial);
// floor.wrapS = THREE.RepeatWrapping;
// floor.position.y = -0.5;
// floor.rotation.x = - (Math.PI / 2);
floor.position.y = -100;
floor.rotation.x = - (Math.PI / 2);
scene.add(floor);
///////////
// VIDEO //
///////////
// create the video element
video = document.createElement( 'video' );
// video.id = 'video';
// video.type = ' video/ogg; codecs="theora, vorbis" ';
video.src = "video3.mp4";
video.load(); // must call after setting/changing source
video.play();
// alternative method --
// create DIV in HTML:
// <video id="myVideo" autoplay style="display:none">
// <source src="videos/sintel.ogv" type='video/ogg; codecs="theora, vorbis"'>
// </video>
// and set JS variable:
// video = document.getElementById( 'myVideo' );
videoImage = document.createElement( 'canvas' );
videoImage.width = 1280;
videoImage.height = 546;
videoImageContext = videoImage.getContext( '2d' );
// background color if no video present
videoImageContext.fillStyle = '#000000';
videoImageContext.fillRect( 0, 0, videoImage.width, videoImage.height );
videoTexture = new THREE.Texture( videoImage );
videoTexture.minFilter = THREE.LinearFilter;
videoTexture.magFilter = THREE.LinearFilter;
var movieMaterial = new THREE.MeshBasicMaterial( { map: videoTexture, overdraw: true, side:THREE.DoubleSide } );
// the geometry on which the movie will be displayed;
// movie image will be scaled to fit these dimensions.
var movieGeometry = new THREE.PlaneGeometry( 600, 300, 4, 4 );
var movieScreen = new THREE.Mesh( movieGeometry, movieMaterial );
movieScreen.position.set(0,50,-200);
scene.add(movieScreen);
camera.position.set(0,200,450);
var vector = new THREE.Vector3(0,200,450);
camera.lookAt(movieScreen.position);
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
}
function onDocumentMouseMove(event) {
mouseX = ( event.clientX - windowHalfX );
mouseY = ( event.clientY - windowHalfY ) * 0.2;
}
function animate() {
requestAnimationFrame( animate );
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);
if ( video.readyState === video.HAVE_ENOUGH_DATA )
{
videoImageContext.drawImage( video, 0, 0 );
if ( videoTexture )
videoTexture.needsUpdate = true;
}
renderer.render( scene, camera );
}

Javascript threejs multi scene and mouse event

I am using Threejs for container cargo loading interactive program. Since my cargo loading plan is layer by layer for one container. So I want to divide the browser into multiple scenes. Each scene represents one layer. Every layer has its own arrangement of cargo boxes and operator could make some adjustment. And all cargo boxes are cubic type of shape.
My codes are based on example, webgl_interactive_cubes_ortho.html (r82), and I does not so many cubes in the example so I modify the code example a little bit.
The example codes works but only has one scene with Viewport. Since I want to divide browser vertically, so I begin to divide the height into 2 scenes. Then even I just devided Viewport into 2, see Render method in the script, Then I could not catch object selected in mouse down event.
What I believe is because of mouse click and 3D scene transform calculation. Anyway, in my case, I just want to select the object and drag and drop. Anyone could help me to make the object selected and can make drag and drop?
/1/
//var height = renderer.domElement.height/2; //only want to divide into two layers
/2/
var container, stats;
var camera, scene, scene2, raycaster, renderer;
var cameras =[];
var mouse = new THREE.Vector2(), INTERSECTED,SELECTED;
var radius = 500, theta = 0;
var offset = new THREE.Vector3();
var frustumSize = 1000;
var cubesL0=[], cubesL1=[];
var plane = new THREE.Plane();
var intersection = new THREE.Vector3();
var scenes =[];
var aspect = window.innerWidth / window.innerHeight;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
var info = document.createElement( 'div' );
info.style.position = 'absolute';
info.style.top = '10px';
info.style.width = '100%';
info.style.textAlign = 'center';
info.innerHTML = 'three.js webgl - interactive cubes';
container.appendChild( info );
camera = new THREE.OrthographicCamera( frustumSize * aspect / - 2, frustumSize * aspect / 2, frustumSize /2 , frustumSize / -2, 1, 1000 );
scene = new THREE.Scene();
scene2 = new THREE.Scene();
var geometry = new THREE.BoxBufferGeometry( 150, 150, 150 );
for ( var i = 0; i < 2; i ++ ) {
var object = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { color: 0x000fff } ) );
if(i==0){
object.position.x = - 100;
object.position.y = - 100;
object.position.z = - 100;
}else{
object.position.x = 200;
object.position.y = -359;
object.position.z = -50;
}
scene.add( object );
scenes.push(scene);
cubesL0.push(object);
}
raycaster = new THREE.Raycaster();
renderer = new THREE.WebGLRenderer();
renderer.setClearColor( 0xf0f0f0 );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.sortObjects = false;
container.appendChild(renderer.domElement);
stats = new Stats();
container.appendChild( stats.dom );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
document.addEventListener( 'mousedown', onDocumentMouseDown, false );
document.addEventListener( 'mouseup', onDocumentMouseUp, false );
//
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
var aspect = window.innerWidth / window.innerHeight;
camera.left = - frustumSize * aspect / 2;
camera.right = frustumSize * aspect / 2;
camera.top = frustumSize / 2;
camera.bottom = - frustumSize / 2;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function onDocumentMouseMove( event ) {
event.preventDefault();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = (- ( event.clientY / window.innerHeight) * 2 + 1);
console.log("mouse x:"+mouse.x+", mouse y:"+mouse.y);
raycaster.setFromCamera( mouse, camera );
if ( SELECTED ) {
if ( raycaster.ray.intersectPlane( plane, intersection ) ) {
SELECTED.position.copy( intersection.sub( offset ) );
}
return;
}
var intersects = raycaster.intersectObjects( cubesL0 );
if ( intersects.length > 0 ) {
console.log(" there is object going to move");
if ( INTERSECTED != intersects[ 0 ].object ) {
if ( INTERSECTED ) INTERSECTED.material.color.setHex( INTERSECTED.currentHex );
INTERSECTED = intersects[ 0 ].object;
INTERSECTED.currentHex = INTERSECTED.material.color.getHex();
plane.setFromNormalAndCoplanarPoint(
camera.getWorldDirection( plane.normal ),
INTERSECTED.position );
}
container.style.cursor = 'pointer';
} else {
if ( INTERSECTED ) INTERSECTED.material.color.setHex( INTERSECTED.currentHex );
INTERSECTED = null;
container.style.cursor = 'auto';
}
}
function onDocumentMouseDown( event ) {
event.preventDefault();
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObjects( cubesL0 );
var getTarget = true;
if ( intersects.length > 0 ) {
SELECTED = intersects[ 0 ].object;
if ( raycaster.ray.intersectPlane( plane, intersection ) ) {
offset.copy( intersection ).sub( SELECTED.position );
}
container.style.cursor = 'move';
}
}
function onDocumentMouseUp( event ) {
event.preventDefault();
console.log(" in mouse up event ");
if ( INTERSECTED ) {
SELECTED = null;
}
container.style.cursor = 'auto';
}
//
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
var width = renderer.domElement.width;
var height = renderer.domElement.height;
//var height = renderer.domElement.height/2; //only want to divide into two layers
var left = 0;
var bottom = 0;
renderer.setViewport( left, bottom, width, height );
renderer.setScissor( left, bottom, width, height );
renderer.render( scene, camera );
}
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - interactive cubes</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
font-family: Monospace;
background-color: #f0f0f0;
margin: 0px;
overflow: hidden;
}
</style>
</head>
<body>
<script src="http://threejs.org/build/three.min.js"></script>
<script src="http://threejs.org/examples/js/libs/stats.min.js"></script>
</body>
</html>

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