如何使用 P5.js deviceMoved() 函数顺序显示文本?

How to display text sequentially using P5.js deviceMoved() function?

我目前正在尝试制作一个程序,其中文本随着 phone 使用 P5.JS deviceMoved() 函数移动每对值而变化。 (下面的 gif 显示了我希望文本最终随着设备移动而改变的方式)

如下面的代码所示,我已将所有文本放入数组中,每次说移动值 ads 30 时我都想将索引更改为 +1 并重复直到所有文本都消失。

let button;
let permissionGranted = false;
let nonios13device = false;

let cx, cy

let value = 0;

var myMessages = ["The", "Quick", "Brown", "Fox", "Jumped", "Over", "The", "Lazy", "Dog"];
var index = 0;


function setup() {
  createCanvas(windowWidth, windowHeight);
}

function draw() {
  background(255)

  text(myMessages[index], width / 2, height / 2);
  fill(value);
  text(value, width / 3, height / 3);
  textSize(30)
}

function deviceMoved() {
  value = value + 5;
  if (value > 255) {
    value = 0;
  }
}

function onMove() {
  var currentValue = value + 30;

  if (value = currentValue) {
    index++;
    return;
  }

  if (index >= myMessages.length) {
    index = 0;
  }
}
<script src="https://cdn.jsdelivr.net/npm/p5@1.3.1/lib/p5.js"></script>

我认为我的问题出在 onMove 函数中,我需要在其中定义当前值以及哪些值可以更改文本,我在这方面相当陌生,所以任何 insight/solution 都可以做到这一点高度赞赏:)

谢谢!

有几个问题与 onMove 函数相关。首先,它永远不会被调用,并且与 deviceMoved 不同,它不是 p5.js 自动调用的特殊函数。其他问题:

function onMove() {
  // You create a currentValue variable that is just value + 30.
  // Within the same function, checking if value is >= currentValue, 
  // assuming that is what you intended, will be fruitless because it
  // is never true.
  // What you probably want to do is declare "currentValue" as a global
  // variable and check the difference between value and currentValue.
  var currentValue = value + 30;

  // This is the assignment operator (single equal sign), I think you meant
  // to check for equality, or more likely greater than or equal to.
  if (value = currentValue) {
    index++;
    // You definitely do not want to return immediately here. This is where
    // you need to check for the case where index is greater than or equal
    // to myMessages.length
    return;
  }

  if (index >= myMessages.length) {
    index = 0;
  }
}

这是一个固定版本:

function deviceMoved() {
  value = value + 5;
  if (value > 255) {
    // When value wraps around we need to update currentValue as well to
    // keep track of the relative change.
    currentValue = 255 - value;
    value = 0;
  }

  onMove();
}

let currentValue = 0;
function onMove() {
  if (value - currentValue >= 30) {
    // Update currentValue so that we will wait until another increment of
    // 30 before making the next change.
    currentValue = value;
    index++;

    // We only need to make this check after we've incremented index.
    if (index >= myMessages.length) {
      index = 0;
    }
  }
}

为了在我的移动设备上对此进行测试 (iOS14),我不得不添加一些代码来请求访问 DeviceMotionEvent,并将其托管在使用 HTTPS 的环境中,而不是嵌入到 iframe 中.你可以看我的代码on glitch and run it live here.