Animating custom GLTF mesh in three js - javascript

I have a custom GLTF model I have loaded into my scene, however I'm having trouble positioning and animating the mesh. Currently, I have the mesh's position set to 0,0,0 and have moved the camera position so that the mesh is on the screen when it is loaded, otherwise you would have to pan around to find it. I just changed the camera position slowly until I could finally see it without having to pan the camera. I'm trying to set the default rotation of the mesh, however whenever I change any of the values, the mesh moves really far away and I would have to redo the camera position so that you can see it again. Why does this happen, and is there a way so that once I have the default rotation and position set I can create an animation that just rotates the hand's z-axis in place without the position changing?
Here's my current code:
import * as THREE from './three.js-master/build/three.module.js'
import { OrbitControls } from './three.js-master/examples/jsm/controls/OrbitControls.js';
import {GLTFLoader} from './three.js-master/examples/jsm/loaders/GLTFLoader.js';
const scene = new THREE.Scene();
const loader = new GLTFLoader();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
window.addEventListener('resize', () => {
renderer.setSize(window.innerWidth,window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
})
const controls = new OrbitControls( camera, renderer.domElement );
controls.enablePan = false;
controls.enableZoom = false;
controls.update();
// const geometry = new THREE.TorusGeometry( 6.46, 1.5, 20, 100 );
// const material = new THREE.MeshBasicMaterial( { color: 0xf542d7 } );
// const torus = new THREE.Mesh( geometry, material );
// scene.add( torus );
loader.load(
// resource URL
'./models/hand/hand.gltf',
// called when the resource is loaded
function ( gltf ) {
scene.add( gltf.scene );
gltf.animations; // Array<THREE.AnimationClip>
gltf.scene; // THREE.Group
gltf.scenes; // Array<THREE.Group>
gltf.cameras; // Array<THREE.Camera>
gltf.asset; // Object
gltf.scene.children[0].position.set(0,0,0);
},
// called while loading is progressing
function ( xhr ) {
console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
},
// called when loading has errors
function ( error ) {
console.log( 'An error happened' );
}
);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(0,0,100)
scene.add( directionalLight );
camera.position.set(-300,570,0);
function animate() {
// torus.rotation.y += 0.01;
gltf.scene.children[0].rotation.z += 0.01;
requestAnimationFrame( animate );
controls.update();
renderer.render( scene, camera );
}
animate();`
I have tried to set the rotation axis separately as well as trying to set an outside variable equal to the gltf.scene.children[0] to rotate it in the animate function.

Related

How to play a gltf animation in reverse if intersects is not true. Three JS

I have been working on implementing a gltf model into a three js project and would like to know if there is any way to reverse a gltf animation when the mouse hovers away from the gltf model. So far I have been able to get the gltf model to play its animation as the mouse hovers over the model, but I would like to reverse the animation once the mouse leaves the model. If anyone could please give me some insight on how I might go about this, it would be greatly appreciated. Thank you.
import * as THREE from 'three';
import { GLTFLoader } from 'GLTFLoader';
import { OrbitControls } from 'OrbitControls';
// Load 3D Scene
var scene = new THREE.Scene();
scene.background = new THREE.Color('black');
const pointer = new THREE.Vector2();
const raycaster = new THREE.Raycaster();
// Load Camera Perspective
var camera = new THREE.PerspectiveCamera( 25, window.innerWidth /
window.innerHeight );
camera.position.set( 10, 1, 25 );
// Load a Renderer
var renderer = new THREE.WebGLRenderer({ alpha: false });
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Load the Orbitcontroller
var controls = new OrbitControls( camera, renderer.domElement );
// Load Light
var ambientLight = new THREE.AmbientLight( 0xFFFFFF );
scene.add( ambientLight );
// Load gltf model and play animation
var mixer;
var mouse = new THREE.Vector2(1, 1);
var loader = new GLTFLoader();
loader.load( './assets/itc.glb', function ( gltf ) {
var object = gltf.scene;
scene.add( object );
mixer = new THREE.AnimationMixer( object );
var action;
gltf.animations.forEach((clip) => {
action = mixer.clipAction(clip);
action.setLoop(THREE.LoopOnce);
action.clampWhenFinished = true;
action.play();
});
object.scale.set( 2, 2, 2 );
object.rotation.y = 37.0;
object.position.x = -10; //Position (x = right+ left-)
object.position.y = -5; //Position (y = up+, down-)
object.position.z = -15; //Position (z = front +, back-)
});
// Animate function
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame( animate );
raycaster.setFromCamera( pointer, camera );
const intersects = raycaster.intersectObjects( scene.children );
if (intersects.length){
mixer.update(clock.getDelta());
}
else{
// How can i reverse the animation when mouse pointer leaves the gltf model
}
renderer.render( scene, camera );
}
// Render function
function render() {
requestAnimationFrame(render);
renderer.render( scene, camera );
}
// On window resize
var tanFOV = Math.tan( ( ( Math.PI / 180 ) * camera.fov / 2 ) );
var windowHeight = window.innerHeight;
window.addEventListener( 'resize', onWindowResize, false );
function onWindowResize( event ) {
camera.aspect = window.innerWidth / window.innerHeight;
// adjust the FOV
camera.fov = ( 360 / Math.PI ) * Math.atan( tanFOV * (
window.innerHeight / windowHeight ) );
camera.updateProjectionMatrix();
camera.lookAt( scene.position );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.render( scene, camera );
}
function onPointerMove( event ) {
pointer.x = ( event.clientX / window.innerWidth ) * 2 - 1;
pointer.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}
window.addEventListener( 'pointermove', onPointerMove );
render();
animate();
An easy way to reverse an animation is to set the timeScale property to - 1. So in your case:
action.timeScale = - 1;
You can update the timeScale property at any point in your code.

Jquery .html method does not seem to work

The editor project I am making should allow me to Import a cdn library and use it to write code . So to show my problem , enter https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js in the import cdn input and click import . Then enter this in the code section :
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer();
document.body.appendChild( renderer.domElement );
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );
camera.position.z = 5;
const animate = function () {
requestAnimationFrame( animate );
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render( scene, camera );
};
animate();
Click the run button at the top . You should get a tiny three js window at the bottom. My first question is , why is the text undefined coming above the render ? And two , if you change the code in the input to :
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );
camera.position.z = 5;
const animate = function () {
requestAnimationFrame( animate );
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render( scene, camera );
};
animate();
It adds another render to the div . Why ? especially when I have used the .html method to replace the contents of the div . My complete code is visible here
By inspecting the Javascript console, it's clear that the renderer is not added to #body2 but rather to the document.body.
This line:
document.body.appendChild( renderer.domElement );
appends the renderer to the body element.
The undefined is because of String( eval( $("#editor #editor-textarea").val() ));
The text content in eval must return something.
https://www.w3schools.com/jsref/jsref_eval.asp
In this case, the return value of $("#editor #editor-textarea").val() is undefined. Hence eval(undefined) is undefined and String(undefined) is "undefined"

OrbitControls autoRotate does not work with three js

Im having troubles with Orbitcontrols. I have my threee js model and i want it to autorotate when the page is loaded for the first time but for some reason it does not work properly. The 3d model stand still as if the command line was not considered.
Here is the code where i initialize the function:
the init() function where i declare my model and add them to the scene:
controls.autoRotate=true
controls.addEventListener('change', render);
render();
the render function:
function render() {
renderer.render(scene, camera);
}
Please note that i can move my model as i wish in my page but the automatic rotation does not seem to be triggered.
Using OrbitControls.autoRotate only works if you call controls.update() in your animation loop. You can't use automatic rotation in combination with on-demand rendering (meaning by utilizing the change event listener of the controls).
let camera, scene, renderer, controls;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
camera.position.z = 1;
scene = new THREE.Scene();
const geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
const material = new THREE.MeshNormalMaterial();
const mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.autoRotate = true;
}
function animate() {
requestAnimationFrame( animate );
controls.update();
renderer.render( scene, camera );
}
body {
margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three#0.124/build/three.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three#0.124/examples/js/controls/OrbitControls.js"></script>

Three.js Collada model displayed black with no lights till a mouse movement

I've encountered one strange problem with displaying collada model in three.js
I suspect that something wrong with the logic of the script but I can't figure out.
The problem is that the Collada model is displayed black till a user moves a mouse (orbit controls). Only after this the model gets lighted.
So, initially, when the page loads, the model is black and this is confusing a user.
What's wrong with the code? Where could be the error?
The code of the script is the following:
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, stats;
var camera, controls, scene, renderer;
var pointLight;
init();
render();
function animate()
{
pointLight.position.copy( camera.position );
requestAnimationFrame(animate);
controls.update();
}
function init() {
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.set( -40, 70, 70 );
controls = new THREE.OrbitControls( camera );
controls.damping = 0.2;
controls.addEventListener( 'change', render );
scene = new THREE.Scene();
// world
var mesh;
var loader = new THREE.ColladaLoader();
loader.load('./models/collada/test.dae', function (result) {
mesh = result.scene;
mesh.scale.set(0.3, 0.3, 0.3);
scene.add(mesh);
render();
});
// lights
var hemLight = new THREE.HemisphereLight(0x000000, 0x303030, 0.8);
scene.add(hemLight);
pointLight = new THREE.PointLight( 0xffffff, 1.1 );
pointLight.position.copy( camera.position );
scene.add( pointLight );
// renderer
renderer = new THREE.WebGLRenderer({antialias:true, alpha:true});
renderer.setClearColor(0xEEEEEE, 1);
renderer.shadowMapType = THREE.PCFSoftShadowMap;
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container = document.getElementById( 'container' );
container.appendChild( renderer.domElement );
window.addEventListener( 'resize', onWindowResize, false );
animate();
}
function onWindowResize()
{
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
render();
}
function render()
{
renderer.render( scene, camera );
}
</script>
You're not calling render() from your animate() function, so the scene is only rendered through the OrbitControls onChange event. Add render() at the end of animate() and it will work. You can also then remove the onChange callback, since you'll be rendering steadily.

Embed 3D model viewer

I'm trying to implement this 3D model viewer, however I want to embed it into an already set div instead of making a new one as this does. So I've edited the code like so but it hasn't worked. Any help would be appreciated.
<script>
// This is where our model viewer code goes.
var container;
var camera, scene, renderer;
var mouseX = 0, mouseY = 0;
var windowHalfX = document.getElementById('viewer').clientHeight / 2;
var windowHalfY = document.getElementById('viewer').clientHeight / 2;
init();
animate();
// Initialize
function init() {
// This <div> will host the canvas for our scene.
container = document.getElementById( 'viewer' );
//document.body.appendChild( container );
// You can adjust the cameras distance and set the FOV to something
// different than 45°. The last two values set the clippling plane.
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 2000 );
camera.position.z = 100;
// These variables set the camera behaviour and sensitivity.
controls = new THREE.TrackballControls( camera );
controls.rotateSpeed = 5.0;
controls.zoomSpeed = 5;
controls.panSpeed = 2;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
// This is the scene we will add all objects to.
scene = new THREE.Scene();
// You can set the color of the ambient light to any value.
// I have chose a completely white light because I want to paint
// all the shading into my texture. You propably want something darker.
var ambient = new THREE.AmbientLight( 0xffffff );
scene.add( ambient );
// Uncomment these lines to create a simple directional light.
// var directionalLight = new THREE.DirectionalLight( 0xffeedd );
// directionalLight.position.set( 0, 0, 1 ).normalize();
// scene.add( directionalLight );
// Texture Loading
var 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 );
// You can set the texture properties in this function.
// The string has to be the path to your texture file.
loader.load( 'img/sickletexture.png', function ( image ) {
texture.image = image;
texture.needsUpdate = true;
// I wanted a nearest neighbour filtering for my low-poly character,
// so that every pixel is crips and sharp. You can delete this lines
// if have a larger texture and want a smooth linear filter.
texture.magFilter = THREE.NearestFilter;
texture.minFilter = THREE.NearestMipMapLinearFilter;
} );
// OBJ Loading
var loader = new THREE.OBJLoader( manager );
// As soon as the OBJ has been loaded this function looks for a mesh
// inside the data and applies the texture to it.
loader.load( 'obj/sickle.obj', function ( event ) {
var object = event;
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.material.map = texture;
}
} );
// My initial model was too small, so I scaled it upwards.
object.scale = new THREE.Vector3( 2, 2, 2 );
// You can change the position of the object, so that it is not
// centered in the view and leaves some space for overlay text.
object.position.y -= 2.5;
scene.add( object );
});
// We set the renderer to the size of the window and
// append a canvas to our HTML page.
renderer = new THREE.WebGLRenderer();
renderer.setSize( document.getElementById('viewer').innerWidth, document.getElementById('viewer').innerHeight );
container.appendChild( renderer.domElement );
}
// The Loop
function animate() {
// This function calls itself on every frame. You can for example change
// the objects rotation on every call to create a turntable animation.
requestAnimationFrame( animate );
// On every frame we need to calculate the new camera position
// and have it look exactly at the center of our scene.
controls.update();
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
</script>
I'm trying to get things to work myself and this code works for me with the latest version (66) of three. Its a little different to you example as I am using a vrml model rather than an obj and I handle the material differently. But it does run fine.
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - loaders - vrml loader</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
threewindow {
border: 1px solid black;
}
</style>
<script src="../three.js/build/three.min.js"></script>
<script src="../three.js/examples/js/controls/TrackballControls.js"></script>
<script src="../three.js/examples/js/loaders/VRMLLoader.js"></script>
<script src="../three.js/examples/js/Detector.js"></script>
<script src="../three.js/examples/js/libs/stats.min.js"></script>
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, stats;
var camera, controls, scene, renderer;
var cross;
function init() {
alert("init");
camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.01, 1e10 );
camera.position.z = 6;
controls = new THREE.TrackballControls( camera );
controls.rotateSpeed = 5.0;
controls.zoomSpeed = 5;
controls.panSpeed = 2;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
scene = new THREE.Scene();
scene.add( camera );
var sphereMaterial =
new THREE.MeshLambertMaterial(
{
color: 0xCC0000
});
// light
var dirLight = new THREE.DirectionalLight( 0xffffff );
dirLight.position.set( 200, 200, 1000 ).normalize();
camera.add( dirLight );
camera.add( dirLight.target );
var loader = new THREE.VRMLLoader();
loader.addEventListener( 'load', function ( event ) {
var object = event.content;
object.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
//child.material.map = texture;
//child.material = sphereMaterial;
child.material.side = THREE.DoubleSide;
}
} );
scene.add(object);
} );
// loader.load( "models/vrml/house.wrl" );
loader.load( "cayley.wrl" );
// renderer
renderer = new THREE.WebGLRenderer( { antialias: false } );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setSize(200, 200);
document.getElementById("threewindow").appendChild(renderer.domElement);
// container = document.createElement( 'div' );
// document.body.appendChild( container );
// container.appendChild( renderer.domElement );
// stats = new Stats();
// stats.domElement.style.position = 'absolute';
// stats.domElement.style.top = '0px';
// container.appendChild( stats.domElement );
window.addEventListener( 'resize', onWindowResize, false );
animate();
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
controls.handleResize();
}
function animate() {
requestAnimationFrame( animate );
controls.update();
renderer.render( scene, camera );
//stats.update();
}
</script>
</head>
<body onload="init()">
<h1>Cubic surfaces</h1>
<p>All the surfaces defined by cubics equations.</p>
<ul><li>Singularities of cubic surfaces.</li>
<li>A pictorial introduction to singularity theory.</li>
</ul>
<div id="threewindow"></div>
</body>
</html>
I found a rather easy solution, I'm surprised I did not find it earlier.
Create the 3D in a seperate html document (using the original script, not the edited one in the OP), then in the div <embed src="3d.html"></embed>

Categories