p5.js 鼠标点击移动 Canvas

p5.js mouseclick move over Canvas

我正在尝试解决第 5 期的学校作业 JavaScript。单击鼠标后,我希望某些东西移到 canvas 上方。但它只移动了一点点,我必须点击几次才能完全移动。我做错了什么?循环不应该让它一直移动吗?如果需要,可以 post 整个代码。

function CanvasPressed()

{
  
  if ( mouseX > 0 && mouseX < 638 && mouseY > 0 && mouseY < 100 )
  {
    
    Bird.stop();
    Bird.play();

    for ( let b = 640; b > 0; b--)
    {
     x = x - 0.05;
    }
          
  } 
   

好吧,这里有一些误解:

// purely aesthetic but in javascript functions are usually written as (i think) camelCase
// so: canvasPressed() rather than CanvasPressed(), Class-es start with upper case
function CanvasPressed()
{
  // you can check for width & height if you want if ( mouseX > 0 && mouseX < width)
  if ( mouseX > 0 && mouseX < 638 && mouseY > 0 && mouseY < height )
  {

    for ( let b = 640; b > 0; b--) // this, in this case, does the same as for(let i = 0; i < width; i ++)
    {
     x += 0.05
     // 0.05 is very little, only a very small part of a pixel
    }
    // here it moves 0.05 * 640 (0.05 + 0.05 + 0.05 ... )
          
  }
}

javascript naming conventions thingy如果你想要

这就是我如何让它通过 canvas:

let mouseWasPressed = false;
let x = 20

function draw() {
  background(20);
  ellipse(x, height / 2, 40)
  
  if(mouseWasPressed) // don't need {} for 1 line after the if()
    x ++; // x = x + 1   shortening in javascript
  // }
}

function mousePressed(){
  mouseWasPressed = true
}

如果您不想要“动画”,您可以使用之前的方法,但将 0.05 更改为 1:

for(let i = 0; i <= width; i ++) // you don't have to add parentheses for 1 line
   x ++;     // x = x + 1   just a shortening in javascript

或者只是

 x = width // or x += width (x = x + width)