Getting Started - Chapter 3 - Wheel Animation
Foundation of Animation
We will start with a wheel and rotate it about its axle. Remember that, to make the car upright, we rotated it about the x axis, so the axle is along the y axis of the cylinder.
We need to create a new animation object:
import { Animation } from "@babylonjs/core/Animations/animation";const animWheel = new Animation("wheelAnimation", "rotation.y", 30, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CYCLE);This has the following parameters: name, property to animate, animation frames per second, property-to-animate type, and loop mode, which in this case repeats the animation.
We follow this with the key frame array, where we set values for the property to animate by frame number.
const wheelKeys = [];
//At the animation key 0, the value of rotation.y is 0wheelKeys.push({ frame: 0, value: 0,});
//At the animation key 30, (after 1 sec since animation fps = 30) the value of rotation.y is 2PI for a complete rotationwheelKeys.push({ frame: 30, value: 2 * Math.PI,});Finally, we link the key frame array to the animation, link the animation to the mesh, and begin it.
//set the keysanimWheel.setKeys(wheelKeys);
//Link this animation to the right back wheelwheelRB.animations = [];wheelRB.animations.push(animWheel);
//Begin animation - object to animate, first frame, last frame and loop if truescene.beginAnimation(wheelRB, 0, 30, true);Since all the wheels rotate the same way, we can use the same animation for all of them.
scene.beginAnimation(wheelRF, 0, 30, true);scene.beginAnimation(wheelLB, 0, 30, true);scene.beginAnimation(wheelLF, 0, 30, true);To ensure that new code in later playgrounds is not overwhelmed by a large amount of previous code, we will save the car as a model and import and animate it as an item.
import { ImportMeshAsync } from "@babylonjs/core/Loading/sceneLoader";ImportMeshAsync("url to model car" + "car.babylon").then(() => { const wheelRB = scene.getMeshByName("wheelRB"); const wheelRF = scene.getMeshByName("wheelRF"); const wheelLB = scene.getMeshByName("wheelLB"); const wheelLF = scene.getMeshByName("wheelLF"); scene.beginAnimation(wheelRB, 0, 30, true); scene.beginAnimation(wheelRF, 0, 30, true); scene.beginAnimation(wheelLB, 0, 30, true); scene.beginAnimation(wheelLF, 0, 30, true);});We can now animate the car itself and add it to the village.