Sun Light (Directional)
Controlling Sun Light
world.setDirectionalLightColor({ r: 255, g: 0, b: 0 }); // A red sun lightworld.setDirectionalLightIntensity(10); // Very bright lightingworld.setDirectionalLightPosition({ x: 500, y: 100, z: 200 });Basic Day & Night Cycle Example
// Create a day/night cycle (60 second period)
let time = 0;
const updateRate = world.simulation.timestepS * 8; // update lighting every 8 ticks
const cycleLengthS = 60; // 60 seconds
const CYCLE_STEP = updateRate / cycleLengthS; // 60 fps * 60 seconds
const SUN_ORBIT_RADIUS = 100;
setInterval(() => {
time = (time + CYCLE_STEP) % 1;
const angle = time * Math.PI * 2;
// Sun position
const sunY = Math.sin(angle) * SUN_ORBIT_RADIUS;
const sunZ = Math.cos(angle) * SUN_ORBIT_RADIUS;
// Smooth transition factor (0 to 1)
const dayProgress = (Math.sin(angle) + 1) / 2; // Normalized to 0-1 range for smooth transitions
// Interpolate light intensities
const directionalIntensity = 0.1 + (dayProgress * 0.7); // Smoothly varies between 0.1 and 0.8
const ambientIntensity = 0.2 + (dayProgress * 0.8); // Smoothly varies between 0.2 and 1
// Interpolate colors
const directionalColor = {
r: 64 + (dayProgress * 191), // 64 to 255
g: 64 + (dayProgress * 191), // 64 to 255
b: 128 + (dayProgress * 127), // 128 to 255
};
const ambientColor = {
r: 40 + (dayProgress * 215), // 40 to 255
g: 40 + (dayProgress * 215), // 40 to 255
b: 80 + (dayProgress * 175), // 80 to 255
};
// Update lighting
world.setDirectionalLightPosition({ x: 0, y: sunY, z: sunZ });
world.setDirectionalLightIntensity(directionalIntensity);
world.setDirectionalLightColor(directionalColor);
world.setAmbientLightIntensity(ambientIntensity);
world.setAmbientLightColor(ambientColor);
}, updateRate * 1000);
Diving Deeper
Last updated
