API

Getting Started - Chapter 3 - Extruding Polygons

Building the Car

The car is going to be a very simple one. The body will be built using the extrudePolygon method. This is another shape that can be built using MeshBuilder. The outline of the shape is drawn in the XZ plane, with points in counter-clockwise order, and the extrusion is in the Y direction. The origin for the polygon is the zero point on the bottom plane.

The outline for the car consists of an array of Vector3 points forming a horizontal baseline, a quarter circle for the front, followed by a horizontal top line. The vertical back is formed by the extrudePolygon method, as it automatically joins the first and last points.

import { Vector3 } from "@babylonjs/core/Maths/math.vector";
//base
const outline = [
new Vector3(-0.3, 0, -0.1),
new Vector3(0.2, 0, -0.1),
];
//curved front
for (let i = 0; i < 20; i++) {
outline.push(new Vector3(0.2 * Math.cos(i * Math.PI / 40), 0, 0.2 * Math.sin(i * Math.PI / 40) - 0.1));
}
//top
outline.push(new Vector3(0, 0, 0.1));
outline.push(new Vector3(-0.3, 0, 0.1));

These, together with the depth to extrude along Y, give the shape for the car.

import { MeshBuilder } from "@babylonjs/core/Meshes/meshBuilder";
const car = MeshBuilder.ExtrudePolygon("car", { shape: outline, depth: 0.2 });

Note: The extrudePolygon and PolygonMeshBuilder both use a earcut slicing algorithm.
The playground has earcut defined, but if you are following this tutorial on your own file system, you will need to download the earcut algorithm via CDN or NPM.
If you are using TypeScript then you can inject the earcut algorithm as the earcutInjection parameter on the extrudePolygon function.

Learning to Extrude

We form the wheel for the right-back position from a cylinder and add it as a child of the car. We then make copies for the right-front, left-back, and left-front wheels. This time, we use clone rather than createInstance, since we can clone a clone. When we clone a wheel, the clone inherits the wheel's parent.

import { MeshBuilder } from "@babylonjs/core/Meshes/meshBuilder";
const wheelRB = MeshBuilder.CreateCylinder("wheelRB", { diameter: 0.125, height: 0.05 });
wheelRB.parent = car;
wheelRB.position.z = -0.1;
wheelRB.position.x = -0.2;
wheelRB.position.y = 0.035;
const wheelRF = wheelRB.clone("wheelRF");
wheelRF.position.x = 0.1;
const wheelLB = wheelRB.clone("wheelLB");
wheelLB.position.y = -0.2 - 0.035;
const wheelLF = wheelRF.clone("wheelLF");
wheelLF.position.y = -0.2 - 0.035;
Extruding Wheels

Now we will make the car look a bit more like a real car by using some textures.