0

我有两个布尔变量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

非常感谢!

4

3 回答 3

1

您可以添加支票。

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

或者采用外观标志的增量。

i += 10 * (lookingRight - lookingLeft);
于 2021-03-27T15:46:45.300 回答
1

I don't know if this is intentional or not, but you're re-assigning 'i' every time draw fires, so the max you can get is 40 and the min is 20. You could do something like this:

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} 

if you don't get it, i wouldn't advise using it in your code right now. But i might aswell try to explain it: '(lookingRight)' is just if statement's thingy, '?' is the same as 'if', '-10' if true, '10' if not true, but yet again this doesn't matter, I will not advise on using this...

I also have no idea if that's what you meant and if this helps, so hope it does.

于 2021-04-01T19:39:04.103 回答
1

您在计算之前触发了椭圆函数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);
}
于 2021-03-27T16:26:43.423 回答