Part 6: Animating a Mesh (WebXR with Babylon.js)
Tags: webxr, beginners, babylonjs, tutorial
Published: 2024-01-11 08:51:22

👀 Stumbled here on accident? Start with the [first part](https://dev.to/taikonauten/welcome-to-the-exciting-world-of-webxr-and-babylonjs-1nll)!

---

Welcome back to the 6th part of this series about Animations in Babylon.js.

ℹ️ Remember - you can always run the code associated with this article and follow along using

`npm start --part=6`

---


![animating the box mesh](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2ut1y7up0z7bcmfhjuf0.jpeg)
<figcaption>animating the box mesh</figcaption>

---

## Essentials & Similarities

Babylon.js offers a robust animation system that allows for the creation and control of animations within 3D scenes. 

Animations can be applied to various properties of objects, including position, rotation, scaling, and color.

The system supports keyframe-based animations, where you can define specific values at certain frames, creating smooth transitions over time. 

There are similarities to CSS animations:

* **Keyframe-Based**: Both Babylon.js and CSS animations can be keyframe-based, where you define certain states at specific points in time, and the system interpolates the values in between.

* **Easing Functions**: Both can use easing functions to make the transitions between keyframes smooth and more natural.

* **Transformations**: They can both animate transformations like scaling, rotating, and moving objects or elements.

* **Timeline Control**: They offer control over the timing of animations, allowing you to set durations, delays, and iteration counts.

---

📚 Babylon.js also offers advanced features like blending multiple animations, easing functions for smooth transitions, and the ability to control the playback of animations, including starting, stopping, pausing, and looping. 

This flexibility makes it suitable for creating complex and dynamic 3D animations in web applications. 

---

## Animating a box

For our experience we’re going to animate a rotation of the box we previously added into our scene.

In effect, this function will rotate the box by 180 degrees around the y-axis, with the rotation occurring smoothly over the span of 100 frames. A looping ensures that the animation will continue indefinitely, creating a rotating box effect in the scene.

### These are the steps to accomplish our goal:

```typescript
animateBox() {
    const rotateAnimation = new Animation("rotateAnimation", "rotation.y", 30, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CYCLE);

    const keyFrames: { frame: number, value: number }[] = [];

    keyFrames.push({
        frame: 0,
        value: 0
    });

    keyFrames.push({
        frame: 50,
        value: Math.PI / 2
    });

    keyFrames.push({
        frame: 100,
        value: Math.PI
    });

    rotateAnimation.setKeys(keyFrames as IAnimationKey[]);

    this._box!.animations = [rotateAnimation];

    this._scene.beginAnimation(this._box, 0, 100, true);
}
```

1. **Create Animation Object**: A new Animation object named `rotateAnimation` is created. This animation is set to change the `rotation.y` property, which affects the y-axis rotation of the box.

2. **Animation Properties**:
  * `30` specifies the frame rate per second. This indicates how many times the animation values are updated per second.
  * `Animation.ANIMATIONTYPE_FLOAT` indicates that the property being animated (`rotation.y`) is a float.
  * `Animation.ANIMATIONLOOPMODE_CYCLE` ensures that the animation will repeat in a loop.

3. **Define Key Frames**:
  * Keyframes are set up to define how the animation progresses over time. Each keyframe specifies a frame number and the corresponding value of the `rotation.y` at that frame.
  * The first keyframe at frame `0` sets the rotation to `0` (start position).
  * The second keyframe at frame `50` sets the rotation to `Math.PI / 2`, which is a 90-degree rotation.
  * The third keyframe at frame `100` sets the rotation to `Math.PI`, a 180-degree rotation.

4. **Apply Keyframes to Animation**: The `setKeys` method of the `rotateAnimation` object is used to apply the keyframes. This method defines the animation sequence according to the keyframes.

5. **Assign Animation to the Box**: The animation array of the `_box` object (presumably a predefined mesh in the scene) is set to include the `rotateAnimation`.

6. **Begin Animation**: Finally, `this._scene.beginAnimation` is called with the `_box`, the start frame (0), the end frame (100), and a boolean to indicate that the animation should loop (`true`).

---

## Adding the animation to the scene

```typescript
async createScene(): Promise<Scene> {
  ...
  this.animateBox();

  return this._scene;
}
```
Finally, we’re adding the this.animateBox() function to the scene.

---

{% vimeo 901446605 %}

---

## Conclusion

This article demonstrates the powerful and flexible animation system of Babylon.js, ideal for creating dynamic 3D animations in web applications. Through a practical example of animating a box, it showcases how to set up keyframe-based animations, define keyframes, and apply them to create smooth and looping animations, emphasizing Babylon.js's capability to bring 3D objects to life with ease and precision.

The seventh part of the series will be about Anchors.