微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我目前正在尝试制作一个程序,当手机使用 P5.JS deviceMoved() 函数移动每两个值时,文本会发生变化。 (下面的 gif 显示了我希望文本在设备移动时最终如何改变)

enter image description here

如下面的代码所示,我已将所有文本放入数组中,每次说移动值广告 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 函数中,我需要在其中定义当前值以及哪些值可以更改文本,我对此还很陌生,因此非常感谢任何对此的见解/解决方案:)

谢谢!

解决方法

有几个与 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;
    }
  }
}

为了在我的移动设备 (iOS 14) 上对此进行测试,我必须添加一些代码来请求访问 DeviceMotionEvent,并将其托管在使用 HTTPS 而不是嵌入 iframe 的环境中。您可以查看我的代码 on glitch 并实时运行它 here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。