The atan2() function in p5.js is used to calculate the angle from a specified point of origin measured from the positive x-axis. The values are returned in the range of PI to -PI as floating points. It is commonly used for orienting geometry to the position of the cursor.
Syntax:
atan2(y, x)
Parameters: This function accepts two parameters as mentioned above and described below.
- y: It is a number that specifies the y-coordinate of the point.
- x: It is a number that specifies the x-coordinate of the point.
Return Value: It returns a number that denotes the arc tangent of the given point.
Below examples illustrate the atan2() function in p5.js:
Example 1:
function setup() { Â Â createCanvas(500, 200); Â Â textSize(18); Â Â Â Â text( "Move the slider to observe the effects" Â Â Â Â Â Â Â Â Â + " of the atan2() function" , 20, 30); Â Â Â Â sliderXPos = createSlider(-200, 200, 0, 1); Â Â sliderXPos.position(20, 50); Â Â Â Â sliderYPos = createSlider(-200, 200, 0, 1); Â Â sliderYPos.position(20, 80); } Â Â function draw() { Â Â clear(); Â Â text( "Move the slider to observe the effects" Â Â Â Â Â Â Â Â Â + " of the atan2() function" , 20, 30); Â Â Â Â sliderXVal = sliderXPos.value(); Â Â sliderYVal = sliderYPos.value(); Â Â Â Â atan2Val = atan2(sliderXVal, sliderYVal); Â Â Â Â text( "The X position value is: " + sliderXVal, 20, 140); Â Â text( "The Y position value is: " + sliderYVal, 20, 160); Â Â text( "The atan2 value is: " + atan2Val, 20, 180); } |
Output:
Example 2:
function setup() {   createCanvas(500, 400);   textSize(18);      text( "Move the mouse to see the rectangle"         + " align to it." , 20, 30); }    function draw() {   clear();   text( "Move the mouse to see the rectangle"         + " align with the mouse." , 20, 30);      // Move the rectangle to the   // middle of the screen   translate(width / 2, height / 2);      // Use the atan2() function to find   // the value according to the mouse   // coordinates   let adjustedValue = atan2(mouseY - height / 2,                             mouseX - width / 2);   rotate(adjustedValue);      // Draw a rectangle   rect(0, 0, 50, 25);      text(adjustedValue.toFixed(4), 100, 20); } |
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/atan2