Skip to content

Commit

Permalink
PwLDev/vibration: Vibration pattern block (#1522)
Browse files Browse the repository at this point in the history
The `navigator.vibrate()` function isn't limited to just buzzing your
phone once for a specific amount of time. You can actually use it to
play a pattern where the device alternates between vibrating and not
vibrating. You can learn more [on MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/API/Vibration_API#vibration_patterns).

I added a block to bring this functionality to the vibration extension.

Tested on Edge for Android.
  • Loading branch information
DNin01 committed Jun 11, 2024
1 parent b4721f4 commit 38115fe
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions extensions/PwLDev/vibration.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Name: Vibration
// ID: pwldevvibration
// Description: Control the device's vibration. Only works on Android.
// Description: Control the device's vibration. Only works on Chrome for Android.
// By: PwLDev <https://scratch.mit.edu/users/PwLDev/>
// License: MPL-2.0

Expand All @@ -22,7 +22,7 @@
blocks: [
{
blockType: Scratch.BlockType.LABEL,
text: Scratch.translate("Only works on Android."),
text: Scratch.translate("Only works on Chrome for Android."),
},
{
opcode: "start",
Expand All @@ -35,6 +35,17 @@
},
},
},
{
opcode: "startPattern",
blockType: Scratch.BlockType.COMMAND,
text: Scratch.translate("play vibration pattern [PATTERN]"),
arguments: {
PATTERN: {
type: Scratch.ArgumentType.STRING,
defaultValue: "1, 0.5, 1, 0.5, 1",
},
},
},
{
opcode: "stop",
blockType: Scratch.BlockType.COMMAND,
Expand All @@ -50,6 +61,17 @@
}
}

startPattern(args) {
if (navigator.vibrate) {
const pattern = Scratch.Cast.toString(args.PATTERN)
.match(/[\w\-.]+/g) // Make into array
?.map((val) => Scratch.Cast.toNumber(val) * 1000); // Convert to numbers in milliseconds
if (pattern) {
navigator.vibrate(pattern);
}
}
}

stop() {
if (navigator.vibrate) {
navigator.vibrate(0);
Expand Down

0 comments on commit 38115fe

Please sign in to comment.