【问题标题】:If Boolean variable true, increment i如果布尔变量为真,则增加 i
【发布时间】:2021-03-27 15:40:59
【问题描述】:

我有两个布尔变量 var lookingLeft = falsevar lookingRight = false 和一个椭圆 ellipse(40, 40, i, i)

var lookingLeft = false;
var lookingRight = false;

function draw() {

    let i = 30;
    ellipse(40, 40, i, i);
    
    if (nose.x > leftEye.x) {
      lookingLeft = true;
    }
    
    if (nose.x > rightEye.x) {
      lookingRight = true;
    }
    
    if (lookingLeft === true) {
      i = i + 10 //this is not working
      rect(10, 10, 50, 50); //but this is
    }
    
    if (lookingRight === true) {
      i = i - 10 //again, this is not working
      rect(300, 300, 50, 50); //but this is
    }
  }

我希望i 增加 10,lookingLeft = true 减少 10,lookingRight = true

这是我的 p5 网络编辑器草图:https://editor.p5js.org/saskiasmith/sketches/7WMDPGPbrc

非常感谢!

【问题讨论】:

  • i = i + 10i = i - 10?
  • 除了左右方向还有别的方向吗?
  • 感谢您的回复@VLAZ,但我已经尝试过了,但由于某种原因无法在草图中工作......不太确定我做错了什么
  • 那么我们需要在问题中发布minimal reproducible example

标签: javascript p5.js ml5


【解决方案1】:

我不知道这是不是故意的,但你每次都在重新分配“i”,所以你可以获得的最大值是 40,最小值是 20。你可以做这样的事情:

if(lookingLeft){ // if it's true it runs, you don't really need "===" with bools in if()
i += 10  //i = i + 10
} else if (lookingRight){
i -= 10
} else{  // OR else if(!lookingLeft && !lookingRight) {}"!" just means NOT so "if not looking left..."
i = 30
}

// and also there are more prettier ways to do this:  *I "explain" in the lower text*

i += (lookingRight) ? -10 : 10
if(!lookingRight && !lookingLeft){i = 30} 

如果你不明白,我不建议现在在你的代码中使用它。但我不妨试着解释一下: '(lookingRight)' 只是 if 语句的事情,'?'与 'if' 相同,如果为 true,则为 '-10',如果不是 true,则为 '10',但这又没关系,我不建议使用它... p>

我也不知道这是否是你的意思,如果这有帮助,所以希望它有用。

【讨论】:

    【解决方案2】:

    你可以加上支票。

    i += lookingLeft && -10 || lookingRight && 10;
    

    或者取寻找标志的增量。

    i += 10 * (lookingRight - lookingLeft);
    

    【讨论】:

    • 嗨@Nina Scholz,已经在草图中尝试过这个,但椭圆的大小没有改变......
    【解决方案3】:

    您在计算 i 之前触发了椭圆函数。 一旦ellipse 被触发,不管你对i 做什么,函数都会运行。 将调用移到draw 的后面,它应该可以工作。

    var lookingLeft = false;
    var lookingRight = false;
    
    function draw() {
      let i = 30;
      
      if (nose.x > leftEye.x) {
        lookingLeft = true;
      }
      
      if (nose.x > rightEye.x) {
        lookingRight = true;
      }
      
      if (lookingLeft === true) {
        i = i + 10 //this is not working
      }
      
      if (lookingRight === true) {
        i = i - 10 //again, this is not working
      }
    
      ellipse(40, 40, i, i);
    }
    

    【讨论】:

    • 谢谢@Kevin,很有意义!为什么它只增加一次?
    • 你是什么意思?您的函数以let i = 30 开头。然后根据左或右加/减 10。所以i 可以是 20、30 或 40,仅此而已。
    猜你喜欢
    • 2014-01-24
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2012-06-28
    • 2021-01-13
    • 1970-01-01
    相关资源
    最近更新 更多