Rotate ThreeJS Object3D on a tilted Y axis - javascript

I've tried many ways to tilt my object then rotate it on this tilted axis, but no matter what I try it always rotates as though the Y axis is straight up, it doesn't seem to rotate on this new tilted axis, WHY NOT?
this.axis = new Vector3(0, 0, 0.5).normalize()
this.mesh = new Mesh(this.geometry, this.material)
this.mesh.rotateOnAxis(this.axis, Math.degToRad(25))
I've tried using rotateOnWorldAxis, also tried makeRotationAxis on Matrix4 and applying directly to geometry.
Example here:
codesandbox.io

There are a few ways to achieve this; one solution would be to add additional hierarchy to your scene by introducing a group node. Here the group is added as a child to the scene, and your mesh is added as a child to that group:
this.mesh = new Mesh(this.geometry, this.material);
/* New group */
this.group = new THREE.Group();
/* Tilt group */
this.group.rotateOnAxis(this.axis, Math.degToRad(25));
/* Add mesh to group */
this.group.add( this.mesh );
/* Add group to scene */
this.scene.add( group );
With this added hierarchy, the "axis tilt" is applied to the group instead of to the mesh. In threejs, doing this causes any children (ie mesh) of the group to inherit that tilt as well.
This method provides an intuitive way of combing the tilt with locally applied rotation (ie as you are doing via rotation.y += 0.005) to achieve the desired axis based rotation.
Here's a working codesandbox. Hope that helps!
Alternative method
Alternatively, you could use the rotateY() method to apply a rotation transform around the mesh object's local frame:
this.mesh.rotateY(0.005);
// this.mesh.rotation.y += 0.005 <-- not needed
Here's a working example to demonstrate this approach

Related

Why does a `Geometry` have a coordinate system and is it different to a `Mesh`?

I have been creating a simple Three.js application and so far I have a centered text in the scene that shows "Hello World". I have been copying the code examples to try and understand what is happening and so far Ihave it working but I am failing to completely understand why.
My confusion comes from reading all the Three.js tutorials describing that a Geometry object is responsible for creating the shape of the object in the scene. Therefore I did not think it would not make sense to have a position on something that is describing the shape of the mesh.
/* Create the scene Text */
let loader = new THREE.FontLoader();
loader.load( 'fonts/helvetiker_regular.typeface.json', function (font) {
/* Create the geometry */
let geometry_text = new THREE.TextGeometry( "Hello World", {
font: font,
size: 5,
height: 1,
});
/* Create a bounding box in order to calculate the center position of the created text */
geometry_text.computeBoundingBox();
let x_mid = geometry_text.boundingBox.max.x - geometry_text.boundingBox.min.x;
geometry_text.translate(-0.5 * x_mid, 0, 0); // Center the text by offsetting half the width
/* Currently using basic material because I do not have a light, Phong will be black */
let material_text = new THREE.MeshBasicMaterial({
color: new THREE.Color( 0x006699 )
});
let textMesh = new THREE.Mesh(geometry_text, material_text);
textMesh.position.set(0, 0, -20);
//debugger;
scene.add(textMesh);
console.log('added mesh')
} );
Here is the code that I use to add to shape and my confusion comes from the following steps.
/* Create a bounding box in order to calculate the center position of the created text */
geometry_text.computeBoundingBox();
let x_mid = geometry_text.boundingBox.max.x - geometry_text.boundingBox.min.x;
geometry_text.translate(-0.5 * x_mid, 0, 0); // Center the text by offsetting half the width
First, we translate the geometry to the left to center the text inside the scene.
let textMesh = new THREE.Mesh(geometry_text, material_text);
textMesh.position.set(0, 0, -20);
Secondly, we set the position of the mesh.
My confusion comes from the fact that we need both of these operations to occur to move the mesh backwards and become centered.
However I do not understand why these operations should be done of the geometry, infact what confuses me more is that why does textMesh.position.set(0, 0, -20); not override my previously performed translation and simply move the mesh to (0,0,-20). removing my previous translation. It seems that both are required.
AFAIK it is recommended (in scenegraph) to transform (translate, rotate, scale) the whole mesh (with simple) rather than prepare transformed geometry and use it to create "untransformed" mesh, since the mesh in second case is not transform-friendly. Basically "cumulative" transform will be just illegal, giving wrong, unexpected results. Even simple movement.
But sometimes it is useful to create transformed geometry and use it for some algos/computations or in meshes.
You are getting somehow "expected" results in your "combined transform" case because it is just particular case (for example it can work only if object position is (0, 0, 0) etc)
mesh.position.set doesn't modify geometry: it is only a property of mesh and it is used to compute final mesh triangles. This computation involves geometry and object matrix which is composed from object position, object quaternion (3D-rotation) and object scale. Object's geometry can be modified by "matrix" operations but none of such operations are performed dynamically by mesh.

Apply three.js subdivision modifier without changing outer geometry?

I am trying to take any three.js geometry and subdivide its existing faces into smaller faces. This would essentially give the geometry a higher "resolution". There is a subdivision modifier tool in the examples of three.js that works great for what I'm trying to do, but it ends up changing and morphing the original shape of the geometry. I'd like to retain the original shape.
View the Subdivision Modifier Example
Example of how the current subdivision modifier behaves:
Rough example of how I'd like it to behave:
The subdivision modifier is applied like this:
let originalGeometry = new THREE.BoxGeometry(1, 1, 1);
let subdivisionModifier = new THREE.SubdivisionModifier(3);
let subdividedGeometry = originalGeometry.clone();
subdivisionModifier.modify(subdividedGeometry);
I attempted to dig around the source of the subdivision modifier, but I wasn't sure how to modify it to get the desired result.
Note: The subdivision should be able to be applied to any geometry. My example of the desired result might make it seem that a three.js PlaneGeometry with increased segments would work, but I need this to be applied to a variety of geometries.
Based on the suggestions in the comments by TheJim01, I was able to dig through the original source and modify the vertex weight, edge weight, and beta values to retain the original shape. My modifications should remove any averaging, and put all the weight toward the source shape.
There were three sections that had to be modified, so I went ahead and made it an option that can be passed into the constructor called retainShape, which defaults to false.
I made a gist with the modified code for SubdivisionGeometry.js.
View the modified SubdivisionGeometry.js Gist
Below is an example of a cube being subdivided with the option turned off, and turned on.
Left: new THREE.SubdivisionModifier(2, false);
Right: new THREE.SubdivisionModifier(2, true);
If anyone runs into any issues with this or has any questions, let me know!
The current version of three.js has optional parameters for PlaneGeometry that specify the number of segments for the width and height; both default to 1. In the example below I set both widthSegments and heightSegments to 128. This has a similar effect as using SubdivisionModifier. In fact, SubdivisionModifier distorts the shape, but specifying the segments does not distort the shape and works better for me.
var widthSegments = 128;
var heightSegments = 128;
var geometry = new THREE.PlaneGeometry(10, 10, widthSegments, heightSegments);
// var geometry = new THREE.PlaneGeoemtry(10,10); // segments default to 1
// var modifier = new THREE.SubdivisionModifier( 7 );
// geometry = modifier.modify(geometry);
https://threejs.org/docs/#api/en/geometries/PlaneGeometry

Three.js: global rotation

I want to rotate all objects in a scene around the origin 0,0,0 along the x axis. However, setting obj.rotation.x += 0.1; doesn't rotate along the origin, but along the the center of the object instead. How can I achieve the desired rotation of the object around the origin? I feel that there should be an easy way, but could not find any in the official docs or online.
Instead of adding the objects to the scene, add them to a THREE.Group() object:
var group = new THREE.Group();
scene.add(group);
...
var mesh1 = new THREE.Mesh(...);
group.add(mesh1);
var mesh2 = new THREE.Mesh(...);
group.add(mesh2);
//and so on with meshes
and then in the render loop:
group.rotation.x += 0.1;
Threejs.r84
You can use THREE.Object3D()
Add all your meshes to an object with myObject.add(myMesh)
And then use myObject.rotateX(angle)
where the angle is in radians, myObject is an Object3D object and myMesh is the mesh to be added.
This will rotate the object around x-axis in local space.
More can be found in the documentation: Object3D

Collision detection with boundingSphere

For each mesh (THREE.Object3D) Three.js provide a very handy properties - boundingSphere and boundingSphere that have intersectsSphere and isIntersectionBox methods.
With all this I thought I can use it for simple collision detection but when I try it appears that collision happens all the time because (I tried boundingSphere) boundingSphere.center is always in (0, 0, 0); So If I want to check collisions between 2 meshes I should for each object - clone boundingSphere object and then get it world coordinates and only then to use intersectsSphere.
something like this:
var bs = component.object.geometry.boundingSphere.clone();
bs.center.setFromMatrixPosition(component.object.matrixWorld);
...
if (_bs.intersectsSphere(bs)){
is this how it suppose to be used or am I missing something and there are more convenient way of doing collisions detection based on boundingBox/boundingSphere?
If you want to do collision detection with bounding boxes you need the boxes in the world coordinate system. The bounding volumes in the intersectsSphere and isIntersectionBox properties of the mesh are in the local coordinate system of the object.
You can do like you did: clone the volumes and move them to the correct position in the world coordinate system, that is a good solution.
Otherwise you can also set a new box from your meshes and do collision using those boxes. Let's say you have a THREE.Mesh called mesh then you can do:
sphere = new THREE.Sphere.setFromPoints( mesh.vertices );
box = new THREE.Box3.setFromObject( mesh );
A little tip. During development it can be nice to see the bounding boxes in your scene, for this you can use the THREE.BoundingBoxHelper:
var helper = new THREE.BoundingBoxHelper( mesh );
scene.add( helper );

Three.js - Rotating a sphere around a certain axis

I have a problem. In Three.js, I want to rotate a sphere (Earth) around axis tilted by 23.5 degs. I found sphere.rotation.x, sphere.rotation.y and sphere.rotation.z, but when I combine them in the correct ratio, the sphere's rotation is quite weird - it has no permanent rotation axis. I think I need a function like sphere.rotation.vector(1,0,-1). Does anyone know how this function is called and how the correct syntax is?
Many thanks for answers!
You do not have to understand how Euler angles or quaternions work to do what you want. You can use
Object3D.rotateOnAxis( axis, angle );
Object3D.rotateOnWorldAxis( axis, angle );
Make sure axis is a unit vector (has length 1), and angle is in radians.
Object3D.rotateOnAxis( axis, angle ) rotates on an axis in object space.
Object3D.rotateOnWorldAxis( axis, angle ) rotates on an axis in world space.
three.js r.104
You need to use quaternions for this. This video explains what quaternions are and how they are used in 3D graphics.
You can construct a quaternion like this:
quaternion = new THREE.Quaternion().setFromAxisAngle( axisOfRotation, angleOfRotation );
Then you apply it to your object by:
object.rotation.set( new THREE.Euler().setFromQuaternion( quaternion ) );
You can also achieve this by using object hierarchies. For example, you can make an Object3D() instance and tilt it by 23.5 degs, then create a sphere (Earth) and add it to the tilted object. The sphere will then rotate around the tilted Y axis. Quaternions however, are the best tool for solving this.
var quaternion = new THREE.Quaternion();
var object = scene.getObjectByName('xxx');
function render(){
quaternion.setFromAxisAngle(new THREE.Vector3(0, 1, 0).normalize(), 0.005);
object.position.applyQuaternion(quaternion);
}
three.js version is 86, see full example on codepen.
You can rotate your sphere using th 'ObjectControls' module for ThreeJS that allows you to rotate a single OBJECT (or a Group), and not the SCENE.
Include the libary:
then
var controls = new THREE.ObjectControls(camera, renderer.domElement, yourMesh);
You can find here a live demo here: https://albertopiras.github.io/threeJS-object-controls/
Here is the repo: https://github.com/albertopiras/threeJS-object-controls.
Hope this helps

Categories