How to rotate an object on its own axis in three.js
Three.js is a JavaScript library that is built on top of WebGL and is used for rendering animations on the web.
Note: If you are unfamiliar with three.js, please follow this link to read more.
Objects in three.js have properties that allow them to be translated, transformed, and rotated. In this Answer, we'll focus on making an object rotate around its axis.
This can be done using the rotation attribute of an
The rotation attribute
This attribute is used for rotating an object about its axis. Below is how we invoke it:
shape.rotation.y += 0.01;
- Here,
shapeis the (Object 3D).Mesh Mesh binds geometry and material together, giving a final shape. - It's attribute
rotationis responsible for an object's local rotation, in radians. - We chose the
yaxis and incremented its rotation.
Note: Putting this statement inside the rendering function will cause the body to rotate every time the function is called.
The set property with the rotation attribute
The rotation attribute also has the set property that takes a vector as an input and sets rotation accordingly.
Below is the code that renders a cone geometry with a basic material applied to it.
const geometry = new THREE.ConeGeometry (1, 3, 32);const material = new THREE.MeshBasicMaterial({color: 0xEA654});const cone = new THREE.Mesh(geometry, material);
THREE.ConeGeometry: It creates a cone geometry with the parameters it has been passed.THREE.MeshBasicMaterial: It creates the required material that we need to apply to our geometry. We also pass the constructor, thecolorwe want to set.THREE.Mesh: It takes as parameters,geometryandmaterial, and gives us the required shape.
We can set the rotation for this cone by using the set method.
- The
setproperty takes as a parameter a 3D vector. Below is how we useset:
sphere.rotation.set(Math.PI/2,0,0)
This rotates the cone by 90 degrees along the x-axis.
Explanation
The code shown above is of a typical scene in three.js with ConeGeometry.
- Line 34: We set the
rotationproperty of ourMeshobject.
Note: To read more on how to create a scene, please visit this link.
Free Resources