Rotating and Scaling 3D Objects in HTML5 – BabylonJS Series part 3

BabylonJS Series by David Catuhe (@DeltaKosh):

Learn WebGL and Babylon.js at your own pace

Feel free to check out our online course 3D Programming with WebGL and Babylon.js for Beginners on Zenva Academy. The course covers the Babylon.js framework and explains all you need to get started with using this fantastic library in new or existing projects.

What you could expect

This time you are going to learn how to move and rotate any kind of objects that you created in our last tutorial. Elements

Final result

How can I do this ?

For this scene, we won’t change anything in the structure: changes are only on the scene file, in the function called “createSceneTuto”. As usual, we are beginning the function by writing basic elements of a scene:

function createSceneTuto(engine) {
    var scene = new BABYLON.Scene(engine);
    var light = new BABYLON.PointLight("Omni", new BABYLON.Vector3(0, 100, 100), scene);
    var camera = new BABYLON.ArcRotateCamera("Camera", 0, 0.8, 100, new BABYLON.Vector3.Zero(), scene);

Then create as much boxes as you want:

//Creation of 3 boxs and 2 spheres
    var box1 = BABYLON.Mesh.CreateBox("Box1", 6.0, scene);
    var box2 = BABYLON.Mesh.CreateBox("Box2", 6.0, scene);
    var box3 = BABYLON.Mesh.CreateBox("Box3", 6.0, scene);
	[…]

As we seen earlier, you can now position all the boxes on the scene

//Positioning the boxes
box1.position = new BABYLON.Vector3(-20,0,0);
box2.position.x = -10; // same as: box2.position = new BABYLON.Vector3(-20,0,0);
box3.position.x = 0;

And now, with the same ease of coding, you can rotate on all axes, and rescale in any size! For example:

  • Rotation (angles are in radians)
      //Rotate the box around the x axis
      box1.rotation.x = Math.PI/4; // or box1.rotation = new BABYLON.Vector3(Math.PI/4,0,0);
    
      //Rotate the box around the y axis
      box2.rotation.y = Math.PI/6;
  • Scaling
    //Scaling of 2x on the x axis
        Box3.scaling.x = 2;

Another Babylon’s feature is moving an object, relatively to another by creating a link between two meshes. This link implies that all parent transformations (position/rotation/scaling)will be combined with the child’s transformations.

//Positioning the box3 relative to the box1
    Box3.parent = box1;
    Box3.position.z = -10;