Open In App

p5.js directionalLight() Function

The directionalLight() function in p5.js is used to create a directional light with the specified color and direction. The rays of the directional light travel infinitely along their path through the scene, hence the distance of the light does not matter. There can be a maximum of 5 directional lights active in a scene.

Syntax:



directionalLight( v1, v2, v3, position )

OR

directionalLight( color, x, y, z )

OR



directionalLight( color, position )

OR

directionalLight( v1, v2, v3, x, y, z )

Parameters: This function accepts eight parameters as mentioned above and described below:

Below example illustrates the directionalLight() function in p5.js:

Example 1:




let newFont;
let directionalLightEnable = false;
  
function preload() {
  newFont = loadFont('fonts/Montserrat.otf');
}
  
function setup() {
  createCanvas(600, 300, WEBGL);
  textFont(newFont, 18);
  
  directionalLightCheck = createCheckbox(
        "Enable Directional Lights", false);
  
  directionalLightCheck.position(20, 80);
  
  // Toggle point light
  directionalLightCheck.changed(() => {
    directionalLightEnable = !directionalLightEnable;
  });
}
  
function draw() {
  background('green');
  text("Click on the checkbox to enable directional"
        + " lights in the scene.", -285, -125);
  
  if (directionalLightEnable) {
    directionalLight(255, 0, 0, height / 2, width / 2, -250);
  }
  noStroke();
  sphere(80);
}

Output:

Example 2:




let newFont;
let directionalLightEnable = false;
  
function preload() {
  newFont = loadFont('fonts/Montserrat.otf');
}
  
function setup() {
  createCanvas(600, 300, WEBGL);
  textFont(newFont, 18);
}
  
function draw() {
  background('black');
  text("This sketch has 4 directional lights "
    + "from different directions", -285, -125);
  
  directionalLight(255, 0, 0, height / 2, width / 2, -1);
  directionalLight(0, 0, 255, -height / 2, -width / 2, -1);
  directionalLight(0, 255, 0, -height / 2, width / 2, -1);
  directionalLight(255, 255, 255, height / 2, -width / 2, -1);
  
  noStroke();
  sphere(100);
}

Output:

Online editor: https://editor.p5js.org/

Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/amp/

Reference: https://p5js.org/reference/#/p5/directionalLight


Article Tags :