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 Object3DThis is the base class for most objects in three.js.

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, shape is the MeshMesh binds geometry and material together, giving a final shape. (Object 3D).
  • It's attribute rotation is responsible for an object's local rotation, in radians.
  • We chose the y axis 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, the color we want to set.
  • THREE.Mesh: It takes as parameters, geometry and material, and gives us the required shape.

We can set the rotation for this cone by using the set method.

  • The set property takes as a parameter a 3D vector. Below is how we use set:
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 rotation property of our Mesh object.

Note: To read more on how to create a scene, please visit this link.

Copyright ©2024 Educative, Inc. All rights reserved