How to set my camera behind my mesh - javascript

I created a city and a character in blender and imported thoses two JSON objects in my script. I want to move my character through the city and have this character at the center of my Screen. Now my problem is that my character is on the right side of my screen and not at the center. Does someone knows how to set my character at the center of my screen with my camera?
Here is a picture of my screen.
var scene, renderer, camera, lua;
var keyboard = new THREEx.KeyboardState();
var clock = new THREE.Clock();
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(90,window.innerWidth/window.innerHeight,0.1,50000);
renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor (0xffffff, 1);
document.body.appendChild(renderer.domElement);
var loader = new THREE.JSONLoader();
loader.load("city.json", function(geomtry , materials){
var material = new THREE.MeshFaceMaterial(materials);
var city = new THREE.Mesh(geomtry,material);
scene.add(city);
})
//my character
loader.load("lua2.json", function (geometry, materials){
var m = THREE.MeshFaceMaterial(materials);
lua = new THREE.Mesh(geometry,m);
//lua.position.set(0,3,0);
lua.position.set(0,2,0);
scene.add(lua);
})
camera.lookAt(scene);
var light = new THREE.PointLight();
//light.position.set(-100,200,100);
light.position.set(0,500,0);
scene.add(light);
var render = function () {
requestAnimationFrame( render );
renderer.render(scene, camera);
update();
};
function update()
{
var delta = clock.getDelta();
var moveDistance = 5 * delta;
var rotateAngle = Math.PI / 2 * delta;
// local transformations
// move forwards/backwards/left/right
if ( keyboard.pressed("S") )
lua.translateZ( -moveDistance );
if ( keyboard.pressed("Z") )
lua.translateZ( moveDistance );
if ( keyboard.pressed("D") )
lua.translateX( -moveDistance );
if ( keyboard.pressed("Q") )
lua.translateX( moveDistance );
// rotate left/right/up/down
var rotation_matrix = new THREE.Matrix4().identity();
if ( keyboard.pressed("Y") )
lua.rotateOnAxis( new THREE.Vector3(0,1,0), rotateAngle);
if ( keyboard.pressed("B") )
lua.rotateOnAxis( new THREE.Vector3(0,1,0), -rotateAngle);
if ( keyboard.pressed("G") )
lua.rotateOnAxis( new THREE.Vector3(1,0,0), rotateAngle);
if ( keyboard.pressed("H") )
lua.rotateOnAxis( new THREE.Vector3(1,0,0), -rotateAngle);
var relativeCameraOffset = new THREE.Vector3(0,0,0);
var cameraOffset = relativeCameraOffset.applyMatrix4( lua.matrixWorld );
camera = new THREE.PerspectiveCamera(45,window.innerWidth/window.innerHeight,0.5,50000);
camera.position.x = lua.position.x;
camera.position.y = lua.position.y+1;
camera.position.z = lua.position.z-2;
//camera.position.x = cameraOffset.x;
//camera.position.y = cameraOffset.y;
//camera.position.z = cameraOffset.z;
camera.lookAt( lua.position );
}
render();

You can change your camera position and rotation
camera.position.x=100
camera.rotation.x=Math.PI

Related

How to determine which gltf object is intersected in three js

I've been trying to work on a personal project and I was wondering if there was any way to decide which gltf is intersected with the cursor in three js. Right now I have been able to load in two of the same gltfs and when either one of them is intersected, it plays the same animation for both of them. What I am trying to do is determine which gltf is intersected and only play the animation for that gltf instead of both of them. I have attached my code that I have. Any help is 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(0xFFFFFF);
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( 0, -.5, 26 );
// 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 mixer1, mixer2, mixer3, mixer4;
var mouse = new THREE.Vector2(1, 1);
var loader = new GLTFLoader();
var loader2 = new GLTFLoader();
var loader3 = new GLTFLoader();
var loader4 = new GLTFLoader();
loader.load( './assets/itc.glb', function ( gltf ) {
var object1 = gltf.scene;
scene.add( object1 );
mixer1 = new THREE.AnimationMixer( object1 );
var action1;
gltf.animations.forEach((clip) => {
action1 = mixer1.clipAction(clip);
action1.setLoop(THREE.LoopOnce);
action1.clampWhenFinished = true;
action1.play();
});
object1.scale.set( 2, 2, 2 );
object1.rotation.y = 37.0;
object1.position.x = -10; //Position (x = right+ left-)
object1.position.y = -5; //Position (y = up+, down-)
object1.position.z = -15; //Position (z = front +, back-)
});
loader2.load( './assets/itc_card.glb', function ( gltf ) {
var object2 = gltf.scene;
scene.add( object2 );
mixer2 = new THREE.AnimationMixer( object2 );
var action2;
gltf.animations.forEach((clip) => {
action2 = mixer2.clipAction(clip);
action2.setLoop(THREE.LoopOnce);
action2.clampWhenFinished = true;
action2.play();
});
object2.scale.set( 2, 2, 2 );
object2.position.x = -10; //Position (x = right+ left-)
object2.position.y = -3; //Position (y = up+, down-)
object2.position.z = -15; //Position (z = front +, back-)
});
loader3.load( './assets/itc.glb', function ( gltf ) {
var object3 = gltf.scene;
scene.add( object3 );
mixer3 = new THREE.AnimationMixer( object3 );
var action3;
gltf.animations.forEach((clip) => {
action3 = mixer3.clipAction(clip);
action3.setLoop(THREE.LoopOnce);
action3.clampWhenFinished = true;
action3.play();
});
object3.scale.set( 2, 2, 2 );
object3.rotation.y = 37.0;
object3.position.x = -8; //Position (x = right+ left-)
object3.position.y = -5; //Position (y = up+, down-)
object3.position.z = -15; //Position (z = front +, back-)
});
loader4.load( './assets/itc_card.glb', function ( gltf ) {
var object4 = gltf.scene;
scene.add( object4 );
mixer4 = new THREE.AnimationMixer( object4 );
var action4;
gltf.animations.forEach((clip) => {
action4 = mixer2.clipAction(clip);
action4.setLoop(THREE.LoopOnce);
action4.clampWhenFinished = true;
action4.play();
});
object4.scale.set( 2, 2, 2 );
object4.position.x = -8; //Position (x = right+ left-)
object4.position.y = -3; //Position (y = up+, down-)
object4.position.z = -15; //Position (z = front +, back-)
});
// Animate function
const clock1 = new THREE.Clock();
const clock2 = new THREE.Clock();
const clock3 = new THREE.Clock();
const clock4 = new THREE.Clock();
function animate() {
requestAnimationFrame( animate );
raycaster.setFromCamera( pointer, camera );
const intersects = raycaster.intersectObjects( scene.children );
if (intersects.length) {
mixer1.update(clock1.getDelta());
mixer2.update(clock2.getDelta());
mixer3.update(clock3.getDelta());
mixer4.update(clock4.getDelta());
}
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();
I have tried using const intersects = raycaster.intersectObjects( scene.children ); and conditionally checking if any of the scene children have been intersected. I want to determine a specific scene.children which is intersected instead of checking if any child is intersected.

How to load objects with Three.js with high quality?

I'm trying to create an object loader with Three.js but I noticed that the quality is way too low and used too much CPU at the same time.
When I use my version, the scene looks like this:
But when I use this website to load it, looks so much better and uses less CPU:
My JavaScript to load this object is:
var camera;
var scene;
var renderer;
var controls;
var container = document.getElementById('webgl');
var WIDTH = container.clientWidth;
var HEIGHT = container.clientHeight;
var ASPECT = WIDTH / HEIGHT;
var ANGLE = 45;
var container = document.getElementById('webgl');
if (Detector.webgl) {
main();
} else {
var warning = Detector.getWebGLErrorMessage();
document.getElementById('webgl').appendChild(warning);
}
function main(){
//Scene
scene = new THREE.Scene();
//Camera
camera = new THREE.PerspectiveCamera(
ANGLE, // field of view
ASPECT, // aspect ratio
10, // near clipping plane
100000 // far clipping plane
);
camera.position.x = 500;
camera.position.y = 200;
camera.position.z = 500;
camera.lookAt(new THREE.Vector3(100, 100, 100));
//Renderer
renderer = new THREE.WebGLRenderer();
var ambientLight = getAmbientLigth(1);
scene.add(ambientLight);
scene.background = new THREE.Color( 0xc3c3c3 );
renderer.setSize(WIDTH, HEIGHT);
renderer.shadowMap.enabled = true;
document.getElementById('webgl').appendChild(renderer.domElement);
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.maxPolarAngle = Math.PI/2;
controls.enableKeys = true;
loadObject();
update(renderer, scene, camera, controls);
}
function getAmbientLigth(intensity, color) {
color = color === undefined ? 'rgb(255, 255, 255)' : color;
var light = new THREE.AmbientLight(color, intensity);
return light;
}
function loadObject() {
var mtlLoader = new THREE.MTLLoader();
var objLoader = new THREE.OBJLoader();
mtlLoader.setPath( 'objects/Blue_shed/' );
mtlLoader.load('blueShed.mtl', function( materials ) {
materials.isMultiMaterial = true;
materials.preload();
objLoader.setMaterials( materials );
objLoader.setPath( 'objects/Blue_shed/' );
objLoader.load( 'blueShed.obj', function ( object ) {
object.name = 'cute-house';
object.receiveShadow = true;
object.castShadow = true;
object.scale.set( 30, 30, 30);
scene.add( object );
} );
});
}
function update(renderer, scene, camera, controls) {
controls.update();
renderer.render(scene, camera);
requestAnimationFrame(function() {
update(renderer, scene, camera, controls);
});
}
I used renderer.setSize to increase the resolution of the renderer and that helped a little bit but still is not as good as in the second image, and still uses too much CPU.
Any ideas? Is there a setting or something that I'm not setting up correctly? I see that website uses a JSON loader, but I don't think that has something to do with this issue, but I mention it just in case.

Why is my PlaneGeometry not receiving a shadow?

I am using three.js to create a scene that has a model on it. I have a plane on which the model sits, and a spotlight shining on the model.
The model is made up of a number of different objects. All of the objects are set to receive and cast shadows. Shadows are being cast on the model itself from other areas of the model.
The plane, however, won't receive shadows. I'm unsure why.
I have adjusted the spotLight.shadowCameraNear and spotLight.shadowCameraFar properties to ensure both the model and plane are within the shadow area. Still nothing.
Below is a screenshot of the model with the spotlight visible.
I have the shadowmap enabled and set to the soft maps:
renderer.shadowMap.enabled = true; // Shadow map enabled
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
My code is as follows:
<script>
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var container, stats, controls;
var camera, scene, renderer, sceneAnimationClip ;
var clock = new THREE.Clock();
var mixers = [];
var globalObjects = [];
init();
function init() {
var loader = new THREE.TextureLoader();
container = document.createElement( 'div' );
document.body.appendChild( container );
// Scene
scene = new THREE.Scene();
scene.fog = new THREE.Fog( 0xffffff, 50, 100 );
// Camera
camera = new THREE.PerspectiveCamera( 30, (window.innerWidth / window.innerHeight), 1, 10000 );
camera.position.x = 1000;
camera.position.y = 50;
camera.position.z = 1500;
scene.add( camera );
// LIGHTS
var spotLight = new THREE.SpotLight( 0xffffff,1 );
spotLight.position.set( 5, 5, 6 );
spotLight.castShadow = true;
spotLight.target.position.set(-1, 0, 2 );
spotLight.shadowDarkness = 0.5;
spotLight.shadowCameraNear = 4;
spotLight.shadowCameraFar = 25;
scene.add( spotLight );
// Camera helper for spotlight
var helper = new THREE.CameraHelper( spotLight.shadow.camera );
scene.add( helper );
// ground
var geometry = new THREE.PlaneGeometry( 30, 30 );
geometry.receiveShadow = true;
var material = new THREE.MeshBasicMaterial( {color: 0xcccccc, side: THREE.DoubleSide} );
material.receiveShadow = true;
var floor = new THREE.Mesh( geometry, material );
floor.receiveShadow = true;
floor.position.y = -1;
floor.rotation.x = Math.PI / 2;
scene.add( floor );
// 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 );
};
// BEGIN Clara.io JSON loader code
var i = 0;
var objectLoader = new THREE.ObjectLoader();
objectLoader.load("final-master-20170426.json", function ( object ) {
var textureLoader = new THREE.TextureLoader();
object.traverse( function ( child )
{
if ( child instanceof THREE.Mesh ) {
var material = child.material.clone();
material.shininess = 0;
material.wireframe = false;
material.normalScale = new THREE.Vector2( 1, 1 );
/* Roof Glass */
if(child.name == 'Roof_Glass') {
material.shininess = 100;
material.alphaMap = grayscale;
material.transparent = true;
}
// Beading
if(child.name.endsWith('_Beading')) {
material.color.setHex( 0x1e1e1e );
material.shininess = 100;
}
/* Pillars */
if(
child.name.indexOf('Pillar') == 0 ||
child.name == 'Main_Frame' ||
child.name == 'Main_Cross_Supports' ||
child.name == 'roof_batons' ||
child.name == 'Roof_Flashings'
) {
material.color.setHex( 0x1e1e1e );
material.shininess = 100;
}
/* Lamps */
if(child.name.indexOf('Lamp') == 0) {
material.color.setHex( 0x1e1e1e );
material.shininess = 100;
}
// Set shadows for everything
material.castShadow = true;
material.receiveShadow = true;
child.material = material;
material = undefined;
globalObjects[child.name] = child;
console.log(child);
}
});
object.position.y = -1;
object.position.x = 0;
scene.add( object );
scene.fog = new THREE.Fog( 0xffffff, 50, 100 );
i++;
} );
// END Clara.io JSON loader code
renderer = new THREE.WebGLRenderer({
'antialias': true
});
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( scene.fog.color );
container.appendChild( renderer.domElement );
renderer.gammaInput = true;
renderer.gammaOutput = true;
renderer.shadowMap.enabled = true; // Shadow map enabled
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
// controls, camera
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.target.set( 0, 0, 0 );
controls.maxPolarAngle = Math.PI * 0.5;
camera.position.set( 8, 3, 10 );
controls.update();
window.addEventListener( 'resize', onWindowResize, false );
animate();
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
//
function animate() {
requestAnimationFrame( animate );
stats.update();
render();
}
function render() {
var delta = 0.75 * clock.getDelta();
camera.lookAt( scene.position );
renderer.render( scene, camera );
}
</script>
This was fixed by using a THREE.MeshPhongMaterial instead of a THREE.MeshBasicMaterial.

Updating Three.js Skeletal Animations to New Mixer Based System

The mixer system was introduced in r73, and I've been trying since then to update my game to this new system.
I am ALMOST there except one thing. Cross-fading on some animations with certain geometries have a slight delay that did not exist in r72. I hacked r72's BlendCharacter and Animation functions to allow callbacks and it works great. In 73 this was not necessary has it has this functionality built in via an event trigger.
In the following fiddle everything works as intended (r72).
http://jsfiddle.net/titansoftime/a93w5hw0/
<script src="http://www.titansoftime.com/webgl/Three72.full.js"></script>
<script src="http://www.titansoftime.com/webgl/BlendCharacter2.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/dev/examples/js/loaders/DDSLoader.js"></script>
var scene, camera, renderer, ambient, directional;
var mesh, geoCache={};
var clock, jsLoader, ddsLoader;
init();
animate();
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 20;
camera.position.y = 10;
ambient = new THREE.AmbientLight(0xffffff);
scene.add(ambient);
directional = new THREE.DirectionalLight(0xffffff,1);
directional.position.set(1,1,0);
scene.add(directional);
clock = new THREE.Clock();
jsLoader = new THREE.JSONLoader(true);
ddsLoader = new THREE.DDSLoader();
renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( 0xffffff, 1 );
document.getElementById('idle').onclick = function(e){
play('Idle',true);
};
document.getElementById('run').onclick = function(e){
play('Run',true);
};
document.getElementById('melee').onclick = function(e){
play('MelleAttack');
};
document.getElementById('magic').onclick = function(e){
play('MagicAttack');
};
document.body.appendChild( renderer.domElement );
loadFloor();
loadModel();
}
function createModel(json){
var geo, geo2;
if( geoCache[json.name] ){
geo = geoCache[json.name];
}else{
geo2 = jsLoader.parse(json).geometry;
var m = new THREE.SkinnedMesh( geo2 );
m.normalizeSkinWeights();
geo2 = m.geometry;
geo = new THREE.BufferGeometry().fromGeometry(geo2);
geo.bones = geo2.bones;
geo.animations = geo2.animations;
geoCache[json.name] = geo;
}
var tex = ddsLoader.load('http://www.titansoftime.com/utils.php?task=getTexture&id=16');
var mat = new THREE.MeshPhongMaterial({map:tex,skinning:true,side:THREE.DoubleSide});
mesh = new THREE.BlendCharacter();
mesh.load(geo,mat);
//mesh.scale.set(10,10,10);
//mesh.mixer = new THREE.AnimationMixer( mesh );
//parseAnimations();
scene.add(mesh);
play('Idle',true);
camera.lookAt(new THREE.Vector3(mesh.position.x,7,mesh.position.z));
}
function loadModel(){
$.ajax({
url: 'http://www.titansoftime.com/utils.php',
data: 'task=getModel&id=16',
crossDomain: true,
type: 'POST',
success: function(response){
createModel(JSON.parse(response));
}
});
}
function loadFloor(){
var geo = new THREE.PlaneBufferGeometry(50,50);
geo.applyMatrix(new THREE.Matrix4().makeRotationX(-Math.PI / 2));
var mat = new THREE.MeshBasicMaterial({color:0x0000ff});
var mesh = new THREE.Mesh(geo,mat);
scene.add(mesh);
}
function play(name,loop){
loop = loop || false;
var anim = mesh.animations[name];
anim.loop = loop;
if( mesh.currentAnimation ){
var cur = mesh.animations[mesh.currentAnimation];
var theTime = 0.175;
if( !cur.loop ){
var diff = cur.data.length - cur.currentTime;
theTime = Math.max(0,Math.min(theTime,diff));
}
console.log('blending: '+name);
mesh.crossfade(name,theTime,function(){
play('Idle',true)
});
}else{
console.log('playing: '+name);
mesh.play(name,loop);
}
}
function animate() {
requestAnimationFrame( animate );
var delta = clock.getDelta();
if( mesh ){
mesh.update( delta );
}
THREE.AnimationHandler.update(delta);
renderer.render( scene, camera );
}
This one (r78) works almost fine except for one animation (Magic Attack) has a small but noticeable delay before returning to the Idle animation. On other models it's the Melee animation, on some there is no problem at all. Super confused as they all work properly in 72.
http://jsfiddle.net/titansoftime/2sh95etj/
<script src="https://rawgit.com/mrdoob/three.js/master/build/three.min.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/examples/js/loaders/DDSLoader.js"></script>
var scene, camera, renderer, ambient, directional;
var mesh, geoCache={};
var clock, jsLoader, ddsLoader;
init();
animate();
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 20;
camera.position.y = 10;
ambient = new THREE.AmbientLight(0xffffff);
scene.add(ambient);
directional = new THREE.DirectionalLight(0xffffff,1);
directional.position.set(1,1,0);
scene.add(directional);
clock = new THREE.Clock();
jsLoader = new THREE.JSONLoader(true);
ddsLoader = new THREE.DDSLoader();
renderer = new THREE.WebGLRenderer({antialias:true});
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor( 0xffffff, 1 );
document.getElementById('idle').onclick = function(e){
play('Idle',true);
};
document.getElementById('run').onclick = function(e){
play('Run',true);
};
document.getElementById('melee').onclick = function(e){
play('MelleAttack');
};
document.getElementById('magic').onclick = function(e){
play('MagicAttack');
};
document.body.appendChild( renderer.domElement );
loadFloor();
loadModel();
}
function createModel(json){
var geo, geo2;
if( geoCache[json.name] ){
geo = geoCache[json.name];
}else{
geo2 = jsLoader.parse(json).geometry;
var m = new THREE.SkinnedMesh( geo2 );
m.normalizeSkinWeights();
geo2 = m.geometry;
geo = new THREE.BufferGeometry().fromGeometry(geo2);
geo.bones = geo2.bones;
geo.animations = geo2.animations;
geoCache[json.name] = geo;
}
var tex = ddsLoader.load('http://www.titansoftime.com/utils.php?task=getTexture&id=16');
var mat = new THREE.MeshPhongMaterial({map:tex,skinning:true,side:THREE.DoubleSide});
mesh = new THREE.SkinnedMesh(geo,mat);
//mesh.scale.set(10,10,10);
mesh.mixer = new THREE.AnimationMixer( mesh );
parseAnimations();
play('Idle',true);
scene.add(mesh);
camera.lookAt(new THREE.Vector3(mesh.position.x,7,mesh.position.z));
}
function loadModel(){
$.ajax({
url: 'http://www.titansoftime.com/utils.php',
data: 'task=getModel&id=16',
crossDomain: true,
type: 'POST',
success: function(response){
createModel(JSON.parse(response));
}
});
}
function loadFloor(){
var geo = new THREE.PlaneBufferGeometry(50,50);
geo.applyMatrix(new THREE.Matrix4().makeRotationX(-Math.PI / 2));
var mat = new THREE.MeshBasicMaterial({color:0x0000ff});
var mesh = new THREE.Mesh(geo,mat);
scene.add(mesh);
}
function play(name,loop){
var to = mesh.animations[ name ];
if( mesh.currentAnimation ){
var from = mesh.animations[ mesh.currentAnimation ];
to.reset();
if( loop ){
to.setLoop(THREE.LoopRepeat);
to.clampWhenFinished = false;
}else{
to.setLoop(THREE.LoopOnce, 0);
to.clampWhenFinished = true;
mesh.mixer.addEventListener('finished',function(e){
play('Idle',true);
});
}
from.play();
to.play();
from.enabled = true;
to.enabled = true;
from.crossFadeTo( to, 0.3 );
}else{
to.play();
}
mesh.currentAnimation = name;
}
function parseAnimations(){
var o, anim, anims = {};
console.log(mesh);
for( var i=0,len=mesh.geometry.animations.length;i<len;i++){
o = mesh.geometry.animations[i];
if( o ){
anim = mesh.mixer.clipAction(o,mesh);
anim.setEffectiveWeight(1);
anims[o.name] = anim;
}
}
mesh.animations = anims;
}
function animate() {
requestAnimationFrame( animate );
var delta = clock.getDelta();
if( mesh ){
if( mesh.mixer ){
mesh.mixer.update( delta );
}
}
renderer.render( scene, camera );
}
Why is this happening?
UPDATE: I noticed this is issue is not limited to blending between animations. One of my animations just looping now has a delay!
72: http://jsfiddle.net/titansoftime/8v0pasp5/
78: http://jsfiddle.net/titansoftime/n6apnj3z/
What is going on!? Was there some sort of auto correcting behavior or something along those lines in 72 that has been removed?
This is a bug in three.js.
https://github.com/mrdoob/three.js/issues/9056
Closing.

Loading a JSON model in three.js

I have been trying to display a 3D json model using three.js. I am fairly new to three.js and have tried everything I can think of, but don't know anything else to try.
Currently when I try to load the model I get an error that says:
Uncaught TypeError: Cannot read property 'visible' of undefinedr # three.min.js:602r # three.min.js:602render # three.min.js:649render # test.html:106animate # test.html:100
I really am not sure where to go from here. Thanks for any help.
Here is my code:
<script type="text/javascript">
if (!Detector.webgl) Detector.addGetWebGLMessage();
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var FLOOR = 0;
var container;
var camera, scene;
var webglRenderer;
var zmesh, geometry;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
document.addEventListener(
'mousemove',
onDocumentMouseMove,
false
);
init();
animate();
// Renderer
webglRenderer = new THREE.WebGLRenderer();
webglRenderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
webglRenderer.domElement.style.position = 'relative';
container.appendChild(webglRenderer.domElement);
// Loader
var loader = new THREE.JSONLoader(),
callbackModel = function(geometry) {
createScene(geometry, 90, FLOOR, -50, 105)
};
loader.load('can.js', callbackModel);
function init() {
container = document.createElement('div');
document.body.appendChild(container);
// Camera
camera = new THREE.PerspectiveCamera(
75,
SCREEN_WIDTH / SCREEN_HEIGHT,
1,
100000
);
camera.position.z = 75;
// Scene
scene = new THREE.Scene();
// Lights
var ambient = new THREE.AmbientLight(0xffffff);
scene.add(ambient);
// More lights
var directionalLight = new THREE.DirectionalLight(0xffeedd);
directionalLight.position.set(0, -70, 100).normalize();
scene.add(directionalLight);
}
function createScene( geometry, x, y, z, b ) {
zmesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial() );
zmesh.position.set( 0, 16, 0 );
zmesh.scale.set( 1, 1, 1 );
scene.add( zmesh );
}
function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX);
mouseY = (event.clientY - windowHalfY);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
if(webglRenderer != undefined && zmesh != undefined) {
zmesh.rotation.set(-mouseY/500 + 1, -mouseX/200, 0);
webglRenderer.render(scene, camera);
}
}
</script>
If your JSON file contains material information, then a materials array will be passed to your callback function, and you need to do this:
callbackModel = function( geometry, materials ) {
// your code
};
...
zmesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( materials ) );
Otherwise, you need to define your own material. For example,
zmesh = new THREE.Mesh( geometry, new THREE.MeshPhongMaterial( { color: 0xff000 } ) );
three.js r.77

Categories