Sun light (Also known as directional light) is a single light source that shines from a relative position across the entirety of a world.
Controlling Sun Light
The sun light, which is called directional light, is controlled through a World instance. We're able to control its color, intensity and position.
The sun light's properties can be changed at anytime during gameplay.
Here's how we can change a world's sun light color.
world.setDirectionalLightColor({ r:255, g:0, b:0 }); // A red sun light
Here's how we can change a world's sun light intensity. Intensity can be a value from 0 to 1+, with 1 being the default brightness, and anything above that being additional brightness.
world.setDirectionalLightIntensity(10); // Very bright lighting
And finally, here's how can update the sun light's position that the light of it directionally emits from across a world.
Here's how we can use ambient & sun light (directional light) to create a day and night cycle for a world.
// Create a day/night cycle (60 second period)let time =0;constupdateRate=world.simulation.timestepS *8; // update lighting every 8 ticksconstcycleLengthS=60; // 60 secondsconstCYCLE_STEP= updateRate / cycleLengthS; // 60 fps * 60 secondsconstSUN_ORBIT_RADIUS=100;setInterval(() => { time = (time +CYCLE_STEP) %1;constangle= time *Math.PI*2;// Sun positionconstsunY=Math.sin(angle) *SUN_ORBIT_RADIUS;constsunZ=Math.cos(angle) *SUN_ORBIT_RADIUS;// Smooth transition factor (0 to 1)constdayProgress= (Math.sin(angle) +1) /2; // Normalized to 0-1 range for smooth transitions// Interpolate light intensitiesconstdirectionalIntensity=0.1+ (dayProgress *0.7); // Smoothly varies between 0.1 and 0.8constambientIntensity=0.2+ (dayProgress *0.8); // Smoothly varies between 0.2 and 1// Interpolate colorsconstdirectionalColor= { r:64+ (dayProgress *191),// 64 to 255 g:64+ (dayProgress *191),// 64 to 255 b:128+ (dayProgress *127),// 128 to 255 };constambientColor= { r:40+ (dayProgress *215),// 40 to 255 g:40+ (dayProgress *215),// 40 to 255 b:80+ (dayProgress *175),// 80 to 255 };// Update lightingworld.setDirectionalLightPosition({ x:0, y: sunY, z: sunZ });world.setDirectionalLightIntensity(directionalIntensity);world.setDirectionalLightColor(directionalColor);world.setAmbientLightIntensity(ambientIntensity);world.setAmbientLightColor(ambientColor);}, updateRate *1000);
Here's what our day/night cycle looks like!
Diving Deeper
The latest sun light API Reference can be found as part of the World API Reference here as directional lighting.
If there are features that we don't currently support for sun light that you'd like to see added to the HYTOPIA SDK, you can submit a feature request here.