Skip to content
Related Articles

Related Articles

p5.js deviceMoved() Function

Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 22 Sep, 2021
Improve Article
Save Article

 The function deviceMoved() works in the device, and it is called when the device is moved by more than the threshold value along all the three X, Y or Z axis.

It only works in the device like mobile phones and it helps in detecting when the device is moved or rotated by more than a threshold value.

It can be used as a sensor in mobile devices like detecting motion, acceleration, rotation, heading, and location.. 

The default threshold is set to 0.5 and it can be changed using setMoveThreshold() function.

Syntax:

deviceMoved()

Now we will run some examples in android phones.

Step 1: Open online web editor of p5.js in the mobile phone using any browser “https://editor.p5js.org/”

Step 2: Write the following code in the editor section and run it to see the output.

Example 1:

Javascript




// Set value to zero
let value = 0;
 
// Set the draw function
function draw() {
 
    // When the device is moved
    // in the all direction then
    // the colour fill filled
    fill(value);
 
    // Set the shape of thr Graphics
    triangle(45, 100, 54, 5, 100, 100);
}
 
// Apply the deviceMoved function
function deviceMoved() {
 
    // Increment the value everytime by 10
    value = value + 10;
 
    // If the value become greater than 255
    // then reset the value to zero.
    if (value > 255) {
        value = 0;
    }
}


Output:

Example 2:

Javascript




// Set the variable as 0
var value = 0;
 
// Set the function
function setup() {
    createCanvas(windowWidth, windowHeight);
 
    // Set the background as value which
    // will be dynamic
    background(value);
}
 
// Set the draw function
function draw() {
 
    // Set the properties of text
    background(value);
    fill(0, 0, 255);
    textAlign(CENTER, CENTER);
    textSize(25);
 
    // Set the limit for value
    value = constrain(value - 2, 0, 200)
 
    // If the value is greater than 10
    if (value > 10) {
        text("Moving Device", width / 2, height / 2);
    } else {
        text("Device is Relaxed ", width / 2, height / 2);
    }
}
 
function deviceMoved() {
 
    // Now increase the value.
    value = constrain(value + 5, 0, 255)
}


Output:


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!