I’ve got very basic knowledge of JS. Following three.js docs Loading 3D models I have succesfully rendered 3D object and centered it:
JavaScript
x
17
17
1
const loader = new GLTFLoader();
2
3
loader.load( 'Duck.gltf', function ( duck ) {
4
5
const model = duck.scene
6
const box = new THREE.Box3().setFromObject( model );
7
const center = new THREE.Vector3();
8
box.getCenter( center );
9
model.position.sub( center ); // center the model
10
scene.add( model );
11
12
}, undefined, function ( error ) {
13
14
console.error( error );
15
16
} );
17
I would like to animate it now, begining with simple rotation:
JavaScript
1
26
26
1
/**
2
* Animate
3
*/
4
5
const clock = new THREE.Clock()
6
7
const tick = () =>
8
{
9
10
const elapsedTime = clock.getElapsedTime()
11
12
// Update objects
13
model.rotation.y = .5 * elapsedTime
14
15
// Update Orbital Controls
16
// controls.update()
17
18
// Render
19
renderer.render(scene, camera)
20
21
// Call tick again on the next frame
22
window.requestAnimationFrame(tick)
23
}
24
25
tick()
26
But the problem is console returns:
JavaScript
1
2
1
ReferenceError: Can't find variable: model
2
Advertisement
Answer
You have declared model variable inside the functional scope, try to declare it outside
JavaScript
1
16
16
1
const loader = new GLTFLoader();
2
let model, box, center;
3
4
loader.load( 'Duck.gltf', function ( duck ) {
5
6
model = duck.scene
7
box = new THREE.Box3().setFromObject( model );
8
center = new THREE.Vector3();
9
box.getCenter( center );
10
model.position.sub( center ); // center the model
11
scene.add( model );
12
13
}, undefined, function ( error ) {
14
console.error( error );
15
} );
16
Hopefully, this will work!
Edited
as @prisoner849 suggested in the comments
JavaScript
1
18
18
1
const clock = new THREE.Clock()
2
const tick = () =>
3
{
4
const elapsedTime = clock.getElapsedTime()
5
// Update objects
6
if (model) {
7
model.rotation.y = .5 * elapsedTime
8
}
9
// Update Orbital Controls
10
// controls.update()
11
// Render
12
renderer.render(scene, camera)
13
// Call tick again on the next frame
14
window.requestAnimationFrame(tick)
15
}
16
17
tick()
18