Getting Started - Chapter 7 - Light the Night
Street Lights
So far we have just used the hemispheric light for all the scenes. There are a range of lights, but for the moment the only new one we will introduce is the spot light. This can be positioned anywhere and given a direction in which to shine. The spread of the light is given by an angle in radians: the larger the angle, the wider the spread. The final parameter indicates how fast the light will fall away; the larger the number, the shorter the distance the light will shine. The spot light can be given a color.
import { SpotLight } from "@babylonjs/core/Lights/spotLight";import { Color3 } from "@babylonjs/core/Maths/math.color";const lampLight = new SpotLight("name", position, direction, angle_of_spread, speed_of_disipation);lampLight.diffuse = Color3.Yellow();We will add a spot light to a street lamp. In order to create a lamp post we introduce another way of creating a mesh by extruding a shape along a path.
We create the shape outline to extrude with a sequence of Vector3s, using points in the x, y plane only.
import { Vector3 } from "@babylonjs/core/Maths/math.vector";const lampShape = [];for (let i = 0; i < 20; i++) { lampShape.push(new Vector3(Math.cos(i * Math.PI / 10), Math.sin(i * Math.PI / 10), 0));}lampShape.push(lampShape[0]); //close shapeWe then set a path for the extrusion, again using Vector3s. The path does not have to be restricted to the x, y plane; it can be described using the full 3D space.
import { Vector3 } from "@babylonjs/core/Maths/math.vector";const lampPath = [];lampPath.push(new Vector3(0, 0, 0));lampPath.push(new Vector3(0, 10, 0));for (let i = 0; i < 20; i++) { lampPath.push(new Vector3(1 + Math.cos(Math.PI - i * Math.PI / 40), 10 + Math.sin(Math.PI - i * Math.PI / 40), 0));}lampPath.push(new Vector3(3, 11, 0));We then form the extrusion.
import { Mesh } from "@babylonjs/core/Meshes/mesh";import { MeshBuilder } from "@babylonjs/core/Meshes/meshBuilder";const lamp = MeshBuilder.ExtrudeShape("lamp", { cap: Mesh.CAP_END, shape: lampShape, path: lampPath, scale: 0.5 });To make the lamp light more visible, we turn down the intensity of the hemispheric light.
light.intensity = 0.5;We export the lamp at an appropriate size to use it in the village. As we need more than one street light, once the lamp is loaded we will clone it several times. For each street light we will add the lamp light. Lights are normally restricted to four in any scene. If there are more, only the last 4 created are active. To extend the number of lights used, we set the number needed on any material to be lit.
material.maxSimultaneousLights = 5;It would be good if we could fade daylight into night and vice versa. We can when we add the Babylon.js GUI.