is there any way to know if there is an object in the scene? is there any function like isEmpty() or something ?
The THREE.Scene is the root of a scene graph, and if scene.children.length > 1 then it has at least one child / object in that scene. Whether any children are things that can be renderered depends on their type. Lights and Cameras affect the scene but are not rendered themselves. The easiest way to check for objects that could be rendered is to traverse the scene and search for Mesh instances:
let hasMesh = false;
scene.traverse(function (object) {
if (object.isMesh) hasMesh = true;
});
console.log(hasMesh ? 'Found meshes!' : 'No meshes.');
Depending on the use case you may want to check for other types, or to check properties like object.visible if you are showing/hiding objects dynamically.
Related
I have several objects grouped in a Object3D. I wanna calculate the boundingbox of the whole group, except some specific objects in that group.
Can you disable the calculation of boundingbox for those objects?
Can you disable the calculation of boundingbox for those objects?
If you are using Box3.setFromObject() then no, this is not possible. The code processes all children of the hierarchy and expands the AABB if an object has a geometry property.
three.js R101
As Mugen mentioned it's not possible to do this out of the box but you can achieve it by manually traversing the tree.
Here's an idea for how you might do that.
var box = null;
group.traverse(c => {
// logic for whether or not to include the child
var includeChild = c.isMesh;
if (includeChild) {
// initialize the box to the first valid child found
// otherwise expand the bounds
if (box === null) {
box = new THREE.Box3();
box.setFromObject(c);
} else {
box.expandByObject(c);
}
}
});
You can change the boolean logic for includeChild to determine whether or not you want an object to be included in the bounds calculations or not.
Hope that helps!
My goal is to attach separate objects (eg: wearable items) to an animated model, so that the bound objects are controlled by the models animation.
I have found these, but all seems outdated.
Three.js attaching object to bone
https://github.com/mrdoob/three.js/issues/3187
I experimenting with a character imported from blender that is skinned & rigged & animated.
My problem is: As I add a new mesh to a specific bone of the model (the commented out part in the code), the current animation clip is switched to the first one (t-pose), and the skinning get broken (model turns white).
However the object is connects to the bone, and moves with it.
const {scene, animations} = await Utils.loadModel('model/someName.gltf');
const model = scene.children[0];
const material = new THREE.MeshBasicMaterial();
material.alphaTest = 0.5;
material.skinning = true;
model.traverse((child) => {
if (child.material) {
material.map = child.material.map;
child.material = material;
child.material.needsUpdate = true;
}
if (child.isBone && child.name === 'RightHand') {
// child.add(createMesh());
}
});
gScene.add(model);
It dosen't work correctly, even if a simple cube is added, but it would be nice if I could add boots to a character, that is moves as its foot.
Looks like I have found a solution.
I updated the demo (It's only a PoC) https://github.com/tomo0613/3d-animated-char-test
first (in blender):
add bones to the shoe that should move with the character. (i guess these should heave the same bones [positions, rotations, sizes]; there are differences in the demo)
then is JS code:
add the shoe (entire mesh) as a child mesh to the leg bone.
before every render, copy the characters bone properties to the shoe bone properties [position & quaternion]
I'm still curious, is there any intended /or better way doing this.?
I'm fairly new to three.js and trying to get a better understanding of ray casting. I have used it so far in a game to show when an object collides with another on the page which works perfectly. In the game I'm building this is to take health from the hero as it crashes into walls.
I am now trying to implement a target which when hovered over some objects it will auto shoot. However the target only registers a target hit once the object passes through the target mesh rather than when its ray is cast through it.
to further detail this, the ray is cast from the camera through the target, if the target is on a mesh (stored as an object array) then I want it to trigger a function.
within my update function I have this:
var ray = new THREE.Raycaster();
var crossHairClone = crossHair.position.clone();
var coards = {};
coards.x = crossHairClone.x
coards.y = crossHairClone.y
ray.setFromCamera(coards, camera);
var collisionResults = ray.intersectObjects( collidableMeshList );
if ( collisionResults.length > 0 ) {
console.log('Target Hit!', collisionResults)
}
The console log is only triggered when the collidableMeshList actually touches the target mesh rather than when it is aiming at it.
How do I extend the ray to pass through the target (which I thought it was already doing) so that if anything hits the ray then it triggers my console log.
Edit
I've added a URL to the game in progress. There are other wider issues with the game, my current focus is just the target ray casting.
Game Link
Many thanks to everyone who helped me along the way on this one but I finally solved it, only not through the means that I had expected to. Upon reading into the setFromCamera() function it looks like it is mainly used around mouse coards which in my instance was not what I wanted. I wanted a target on the page and the ray to pass through this. For some reason my Ray was shooting vertically up from the centre of the whole scene.
In the end I tried a different approach and set the Rays position and direction directly rather rely on setting it from the cameras position.
var vector = new THREE.Vector3(crossHair.position.x, crossHair.position.y, crossHair.position.z);
var targetRay = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
var enemyHit = targetRay.intersectObject( enemy );
if ( enemyHit.length > 0 ) {
console.log('Target Hit!', targetRay)
}
I'll leave this up for a while before accepting this answer in case anyone has a better approach than this or has any corrections over what I have said in regards to setFromCamera().
I have two different threejs scenes and each has its own camera. I can control each camera individually with a corresponding TrackballControls instance.
Is there a reliable way to 'lock' or 'bind' these controls together, so that manipulating one causes the same camera repositioning in the other? My current approach is to add change listeners to the controls and update both cameras to either's change, but this isn't very neat as, for one, both controls can be changing at once (due to dampening).
I believe it should work if you set the matrices of the second camera to the values of the first and disable automatic matrix-updates of both cameras:
camera2.matrix = camera1.matrix;
camera2.projectionMatrix = camera1.projectionMatrix;
camera1.matrixAutoUpdate = false;
camera2.matrixAutoUpdate = false;
But now you need to update the matrix manually in your renderloop:
camera1.updateMatrix();
That call will take the values for position, rotation and scale (that have been updated by the controls) and compose them into camera1.matrix, which per assignment before is also used as the matrix for the second camera.
However, this feels a bit hacky and can lead to all sorts of weird problems. I personally would probably prefer the more explicit approach you have already implemented.
Question is why are you even using two camera- and controls-instances? As long as the camera isn't added to the scene you can just render both scenes using the same camera.
Is it possible to use the Observer or Publisher design patterns to control these objects?
It seems that you are manipulating the cameras with a control. You might create an object that has the same control interface, but when you pass a command to the object, it repeats that same command to each of the subscribed or registered cameras.
/* psuedo code : es6 */
class MasterControl {
constructor(){
this.camera_bindings = [];
}
control_action1(){
for( var camera of this.camera_bindings ){
camera.control_action1();
}
}
control_action2( arg1, arg2 ){
for( var camera of this.camera_bindings ){
camera.control_action2( arg1, arg2 );
}
}
bindCamera( camera ){
if( this.camera_bindings.indexOf( camera ) === -1 ){
this.camera_bindings.push( camera );
}
}
}
var master = new MasterControl();
master.bindCamera( camera1 );
master.bindCamera( camera2 );
master.bindCamera( camera3 );
let STEP_X = -5;
let STEP_Y = 10;
//the following command will send the command to all three cameras
master.control_action2( STEP_X, STEP_Y );
This binding is self created rather than using native three.js features, but it is easy to implement and can get you functional quickly.
Note: I wrote my psuedocode in es6, because it is simpler and easy to communicate. You can write it in es5 or older, but you must change the class definition into a series of functional object definitions that create the master object and its functionality.
I think the problem might be because it's a loaded object and not a "created" geometry, but I want to be able to select an object and show that it is selected, like in this example.
I load multiple objects in and I keep track of an index for each object (so the first object loaded has objIndex = 0, etc.) and I know that my code recognizes when I "mouse down" from the console. However, it says that intersects.length = 0 so the rest of the function is skipped.
I'm also not sure what "intersects.length" is actually taking the length of.
So I suppose my questions are:
What is "intersects.length" taking the length of?
Why do my objects have an "intersects.length" of 0?
What are some things I could do so that the objects are recognized?
Here's the relevant code:
function onDocumentMouseDown(event) {
event.preventDefault();
// default action of event will not be triggered
var vector = new THREE.Vector3(mouse.x, mouse.y, 0.5).unproject(camera);
// used to pass 3D positions and directions
var raycaster = new THREE.Raycaster(camera.position,
vector.sub(camera.position).normalize());
var intersects = raycaster.intersectObjects(objects);
console.log('Mouse is down.');
console.log(intersects.length);
if (intersects.length > 0) {
controls.enabled = false;
SELECTED = intersects[0].object;
var intersects = raycaster.intersectObjects(plane);
offset.copy(intersects[0].point).sub(plane.position);
container.style.cursor = 'move';
console.log('Clicked object: ' + object.name);
}
}
If you need to see more, let me know! Thank you. :)
Answering your question:
Here is an interesting read on raycast to help clarify raycasting:
http://soledadpenades.com/articles/three-js-tutorials/object-picking/
So what raycasting basically do is to (really) cast an imaginary ray. When you "mouse down" your program will, so called, cast a straight-line array into the scene. Now to answer your question:
For question one(1) and two(2) : Now when you cast a ray, it may or may not intersect an object. For example if you click into an empty space, the ray will not catch an object. However, as the name suggest, a raycast cast a ray and it may also hits multiple objects along the way. For example if you have one object and another object positioned directly behind the first object, casting a ray into the first object will also intersects the second object. The ray cast will "catch" both objects and put in the two objects into into the array "intersects". Therefore, the command
if (intersects.length > 0)
stated that if the raycast "catches" and object, do these. Moreover, it keeps on calling intersects[0] to refer to the first objects in the intersects array. In this case the most front object that the raycast catches. You can test my answer by creating hundreds of objects and state that, for every member in the intersects array, you change the color to red(for example). You will see that if the raycast catches multiple objects, all the objects will turn into that color. Hope for the first two question!
I am not sure of what you are asking for the third question. Can you clarify further? One way for the object to be recognized is to put them into the scene and put a raycast on the scene. However, I am not too sure of what you are asking to give you answer that I think you want.