Three.js is a JavaScript library. It makes use of WebGL to render animations on the web.
Objects in three.js that belong to the Object3D
class (base class for most 3D objects) have properties that allow them to be translated, transformed, and rotated. In this Answer, we will focus on translating an object on an axis which can be achieved using the following methods:
translateX()
translateY()
translateZ()
These methods translate the object on their respective axes by some magnitude. The way they work is shown below.
The syntax for translating an object on any of the three axes is as follows:
object.translateX(d);
// or
object.translateY(d);
// or
object.translateZ(d);
Here, object
is an instance of class Object3D
and contains the translate
methods.
The methods mentioned above pass only one parameter:
d
: This parameter is of type float
and specifies the magnitude by which we want to translate an object in a particular direction (for example, in our case , or axes).Below is an example that demonstrates the use of translate
methods. In this code example, the sphere inside the scene can move in a particular direction as specified by the user using the 'WASD’ keys on the keyboard.
We start by creating a scene. The rest of the code helps in translating in a specific direction, as directed by the user input.
Line 37: Here, we set the event listener using the addEventListener()
method to listen for the keydown
event and trigger the callback function as the user presses a key.
Lines 39–47: Here, we create an if-else
block to check which key was pressed.
Lines 40, 42, 44, and 46: These lines of code add translation to the sphere on the respective axes. We pass the translate
methods a lower value so that the motion can be observed.
Note: To read more on
addEventListener()
, please visit this link.
Free Resources